Sunday, May 29, 2011

Chapter[2]: Data Types, Input and Output

In this chapter we will be writing a few short programs. You must write all the programs here and run it successfully. Do little experiments with these, change a little of this and that in the code and observe how the output changes.

Our first program here is a performs simple addition of two numbers. Think about how we add two numbers on paper. We use some space on the paper to write (or store) the numbers that we will add. But how do we get a paper-like thing in our program? The computer memory does it for our programs. Every programming language supports variables that can be assigned values. These variables are stored in computer memory. Therefore, variables are just names for a space in the memory. To set the value stored in a variable, we have to write a the code like variablename = some value. Lets use the code below to help explain it further.


#include<stdio.h>

int main() 
{
    int a;
    int b;
    int sum;


    a = 50;
    b = 60;


    sum = a + b;


    printf("Sum is %d", sum);


    return 0;
}
Program 2.1 

Run the program now. You should see Sum is 110 on the screen.

In this program, a, b and sum are three variables each storing different values. The first step is to declare these names as variables of a data type. All these variables are of type integer, and hence they are declared as int. Thus, the line int a; tells the compiler that we are interested in using a as a variable that will be used to store integer values. Like int, there are many other data types supported by C. We will get to know them with use. There is a shorter version of declaring variables of the same type. Instead of typing three int declarations for a, b and sum, we could have written int a, b, sum;, which has the same effect as the former. Note how semicolon terminates variable declaration.


In the next two lines, we have two statements. 


a = 50;
b = 60;


Here we have assigned a value of 50 to a, and 60 to b. Unless we change the value ourselves, the compiler will always find these values for these variables in our program.

No comments:

Post a Comment