08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3 ■ Programs with Sequence Logic

using a printf statement. The program must then wait for us to type the number and, when it is

typed, read it. This can be done with the scanf statement. (Strictly speaking, printf and scanf

are functions, but the distinction is not too important for us.) Before we look at this statement, let

us rewrite the algorithm using these new ideas:

prompt for the first number

read the number

prompt for the second number

read the number

find the sum

print the sum

We can implement this algorithm in C as Program P3.3.

Program P3.3

//prompt for two numbers and find their sum

#include <stdio.h>

int main() {

int a, b;

printf("Enter first number: ");

scanf("%d", &a);

printf("Enter second number: ");

scanf("%d", &b);

printf("%d + %d = %d\n", a, b, a + b);

}

When run, the first printf statement will print:

Enter first number:

The scanf statement, explained shortly, will cause the computer to wait for the user to type a

number.

Suppose she types 23; the screen will look like this:

Enter first number: 23

When she presses the “Enter” or “Return” key on the keyboard, scanf reads the number and

stores it in the variable a.

The next printf statement then prompts:

Enter second number:

49

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!