Friday, March 6, 2015

C program to add even numbers

The C program given below is able to add the even numbers from 1 to 100 and able to display the result. There are two C programs given below, the first one can add all the even numbers from 1 to 100. After adding all even numbers it stores the result into an integer type variable sum, later it displays the result.

!important
All the lines starting with double slash (//) are comments. I have added lots of comments, so that one can understand the program clearly.

I have used a for-loop at the 10th line to check all the numbers one by one. Inside the for-loop there is an if condition to check the value of i if it is even or not.

If any even number found then it will be added with the value of sum variable and it will be continued till the condition is true. Thus all the even numbers will be added together and will be stored into the variable sum.

//including header file
#include<stdio.h>
//main function
int main(){
    //declaring integer type variables
    int i, sum=0;

    //for-loop for chacking even numbers
    //and to add them together
    for(i=1; i<=100; i++){
        //if condition to check if it is even or not
        if(i%2==0){
            //adding all even number together
            //and saving them to the variable sum
            sum = sum + i;
        } //end of if-condition
    } //end of for-loop
    //displaying summation from variable sum
    printf("The summation is: %d",sum);
} //end of main function

The program given below is almost same to the above program, but the main difference is- user can input a starting number and a limit to check if there is any even numbers. If the program gets even numbers then all of them will be added to an integer type variable sum. And later the result will be displayed as like as the above program.

//including header file
#include<stdio.h>
//main function
int main(){
    //declaring integer type variables
    int i, start, limit, sum=0;

    //displaying a message to input starting number
    printf("Enter the starting number: ");
    //getting the starting number
    scanf("%d",&start);


    //displaying message to input the limit
    printf("Enter the limit: ");
    //getting the limit
    scanf("%d",&limit);

    //for-loop for chacking even numbers
    //and to add them together
    for(i=start; i<=limit; i++){
        //if condition to check if it is even or not
        if(i%2==0){
            //adding all even number together
            //and saving them to the variable sum
            sum = sum + i;
        } //end of if-condition
    } //end of for-loop
    //displaying summation from variable sum
    printf("\nThe summation of the even numbers from %d to %d is: %d",start,limit,sum);
} //end of main function

Feel free to contact with me if you have any query! Just leave a comment below, I will reply as soon as I can.


No comments:

Post a Comment