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

Remember that a comment (or lack of it) has absolutely no effect on how the program runs.

If you remove all the comments from a program, it will run exactly the same way as with the

comments.

Each language has its own way of specifying how a comment must be written. In C, we write a

comment by enclosing it within /* and */, for example:

/* This program prints a greeting */

A comment extends from /* to the next */ and may span one or more lines. The following is a

valid comment:

/* This program reads characters one at a time

and counts the number of letters found */

C also lets you use // to write one-line comments. The comment extends from // to the end

of the line, for example:

a = s * s; //calculate area; store in a

In this book, we will use mainly one-line comments.

1.9 Programming with Variables

To reinforce the ideas discussed so far, let us write a program that adds the numbers 14 and 25

and prints the sum.

We would need storage locations for the two numbers and the sum. The values to be stored in

these locations are integer values. To refer to these locations, we make up the names a, b, and sum,

say. (Any other names would do. In C, as in all programming languages, there are rules to follow

for making up variable names, for instance, a name must start with a letter and cannot contain

spaces. We will see the C rules in the next chapter.)

One possible algorithm might look like this:

set a to 14

set b to 25

set sum to a + b

print sum

The algorithm consists of four statements. The following explains the meaning of each statement:

• set a to 14: store the number 14 in memory location a; this is an example

of an assignment statement.

• set b to 25: store the number 25 in memory location b.

• set sum to a + b: add the numbers in memory locations a and b and store

the sum in location sum. The result is that 39 is stored in sum.

• print sum : print (on the screen) the value in sum, i.e., 39.

18

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!