08.01.2023 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 1 ■ Elementary Programming Concepts

Program P1.4 shows how we can write this algorithm as a C program.

Program P1.4

//This program prints the sum of 14 and 25. It shows how

//to declare variables in C and assign values to them.

#include <stdio.h>

int main() {

int a, b, sum;

a = 14;

b = 25;

sum = a + b;

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

}

When run, this program will print the following:

14 + 25 = 39

In C, variables are declared as integer using the required word int. (In programming

terminology, we say that int is a reserved word.) Thus, the statement

int a, b, sum;

declares that a, b, and sum are integer variables. In C, all variables must be declared before they are

used in a program. Note that the variables are separated by commas, with a semicolon after the

last one. If we need to declare just one variable (a, say), we will write

int a;

a = 14;

The statement

is C’s way of writing the assignment statement

set a to 14

It is sometimes pronounced “a becomes 14.” In C, an assignment statement consists of a

variable (a in the example), followed by an equals sign (=), followed by the value to be assigned to

the variable (14 in the example), followed by a semicolon. In general, the value can be a constant

(like 14), a variable (like b), or an expression (like a + b). Thus,

set b to 25

19

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!