Thursday, May 2, 2013

C program to add 1-10 altogether

The c program given below will add the numbers from 1 to 10 and finally the result will be displayed. In the line 6, two integer type variables i and sum are taken. But you may avoid this line, then you need to change the 9th line as for(int i=1; i<=10; i++){ and the 10th line as int sum=sum+i;

From the 9th line the for-loop has started, where the variable i is initialized by 1. There is a condition i<=10, that means the loop will continue till the value of i become 10.

Inside the for-loop there is an operation sum=sum+i;, that means the value of i will be added with the value of sum and finally the summation will be stored into the variable. This process will continue till the value of i become 10. Thus the program will add all the numbers from 1-10.

By the 13th line printf("The Sumation is: %d",sum); will display the value stored into the variable sum.

//c program to add number 1-10
#include<stdio.h>
//main function
void main(){
    //declaring integer type variables
    int i, sum=0;
    
    //for loop to add numbers 1-10
    for(i=1; i<=10; i++){
        sum=sum+i;
    }
    //displaying the result
    printf("The Sumation is: %d",sum);
}



No comments:

Post a Comment