Sum of Five digit number

 In this I will tell you how to do sum of five digit number . So, without any further delay let's get started .Like our previous post we here going to use all three loops in C .

Code:

Using for loop

#include <stdio.h>
//sum of five digit number using loop
int main()
{
    int number;
    printf("Enter any  five digit number\n");
    scanf("%d", &number);
    int sum = 0;
    int number1;
    for (int i = 0i < 5i++)
    {
        number1 = number % 10;
        sum = sum + number1;
        number = number / 10;
    }
    printf("%d \n"sum);
    return 0;
}

Using while loop 

#include <stdio.h>
//sum of five digit number using loop
int main()
{
    int number;
    printf("Enter any  five digit number\n");
    scanf("%d", &number);
    int sum = 0;
    int number1;
    int i=0;
    while(i<5){
        number1 = number % 10;
        sum = sum + number1;
        number = number / 10;
        i++;
    }
    printf("%d \n"sum);
    return 0;
}

Using do-while loop 

#include <stdio.h>
//sum of five digit number using loop
int main()
{
    int number;
    printf("Enter any  five digit number\n");
    scanf("%d", &number);
    int sum = 0;
    int number1;
    int i=0;
    do{
        number1 = number % 10;
        sum = sum + number1;
        number = number / 10;
        i++;
    }while(i<5);
    
    printf("%d \n"sum);
    return 0;
}

Logic:

First we define Variable of  type int   that is number  and we take input of five digit number from user in this . Then we define another variable of type int  that is number1 and sum=0. we give sum as value zero. In number1 we assign value number%10 that means remainder remains  after dividing five digit number with 10. And then we add it in sum variable . And Then we divide number by 10 in order to get quotient and store in same variable number .This happens five times  and loop gets exit.

Output:

 You can give different input to this program and check by yourself. And please try by yourself  .

  I hope that you find this helpful in you work . 

Thanks for reading .









No comments:

Post a Comment