GET EDUCATE

Contents
Basics of C Programming

⯈Basic C Programs

C Program to add two numbers

Whenever we start the program always, we start with reading the inputs and calculating the outputs. 

Input: Two numbers. (int)

Output: Sum of two numbers. (int)

We read the inputs using runtime initialization, so we write the scanf statement as,

scanf("%d%d",&a,&b);

Let ‘a’ and ‘b’ be the two integers as input.

No variables can be used unless they are declared.

Hence, we update the program as,

int main()
{
int a, b;
scanf("%d%d",&a,&b);
}

We calculate the output after reading all the necessary inputs,

sum = a+b

Hence, the updated program will be,

Note:

1. No variable should be used unless it is declared.

2. The value of the variable on RHS of ‘=’, its value should be known before its first point of usage.

int main()
{
int a, b;
int sum;
scanf("%d%d",&a,&b);
sum = a + b;

}

An algorithm should have at least one output, the answer is stored in variable sum. Hence, we need to print it. 

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

The final program becomes,

Since, we are using printf and scanf, we need to include stdio.h as these files are present in these header files.

C
#include<stdio.h>
int main()
{
    int a, b;
    int sum;
    scanf("%d%d",&a,&b);
    sum = a + b;
    printf("sum = %d\n",sum);
    return 0;
}

Output window of above program

output add two numbers

Let the two numbers be 3 and 4, We see that we get the output.

output add two numbers

We see that the cursor is blinking, and we don’t know what to enter. Shall we enter number or a string, its not clear.

Its like the form given below to fill the details, but the captions are not provided.

form

In order to have good user interface, we can provide a message before reading the numbers as, (Optional, user interface may or may not be provided)

#include<stdio.h>
int main()
{
 int a, b;
 int sum;
 printf("Enter two numbers:");
 scanf("%d%d",&a,&b);
 sum = a + b;
 printf("sum = %d\n",sum);
 return 0;
}

Output window of above program

output add two numbers

We see that there is a user interface asking for Enter two numbers: which gives more meaning for end user, what to give as an input.

Memory layout of above program

The scope after declaring all the variables, 

scope add two numbers

Scope after reading the values of ‘a’ and ‘b’.

scope 2 add two numbers

Scope after calculating the sum

scope add two numbers

As the function ends, (main here) all the variables are erased from the memory and the scope from the memory deactivates.

scope add two numbers
Scroll to Top