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

}

sum = a + b;

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

C allows us to declare a variable and give it an initial value in one statement so we could write

the program more concisely (without the comment) as Program P3.1:

Program P3.1

#include <stdio.h>

int main() {

int a = 14;

int b = 25;

int sum = a + b;

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

}

And since, as discussed earlier, we do not really need the variable sum, this program can be

written as Program P3.2.

Program P3.2

#include <stdio.h>

int main() {

int a = 14;

int b = 25;

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

}

This program is very restrictive. If we wish to add two other numbers, we will have to change

the numbers 14 and 25 in the program to the ones required. We would then have to re-compile

the program. And each time we want to add two different numbers, we would have to change the

program. This can become very tedious.

It would be nice if we could write the program in such a way that when we run the program,

we will have the opportunity to tell the program which numbers we wish to add. In this way, the

numbers would not be tied to the program, and the program would be more flexible. When we

“tell” the program the numbers, we say we are supplying data to the program. But how do we get

the program to “ask” us for the numbers and how do we “tell” the program what the numbers are?

We can get the program to prompt us for a number by printing a message such as:

Enter first number:

48

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!