Sunday, 10 April 2016

C and C++ Program to Calculate the Sum of Odd & Even Numbers Problem Solution.


C Solution:

#include <stdio.h>
 /*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
void main(){
    long long i, num, odd_sum = 0, even_sum = 0;

    printf("Enter the value of num: ");
    scanf("%d",&num);
    for (i = 1; i <= num; i++){
        if (i % 2 == 0)even_sum += i;
        else odd_sum += i;
    }
    printf("Sum of all odd numbers  = %lld\n", odd_sum);
    printf("Sum of all even numbers = %lld\n", even_sum);
}


Another Way:

#include <stdio.h>
 /*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
void main(){
    long long i = 1, num, odd_sum = 0, even_sum = 0;

    printf("Enter the value of num: ");
    scanf("%d",&num);
    while(i <= num){
        odd_sum += i++;
        even_sum += i++;
    }
    printf("Sum of all odd numbers  = %lld\n", odd_sum);
    printf("Sum of all even numbers = %lld\n", even_sum);
}


C++ Solution:

#include <iostream>
using namespace std;
 /*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){
    long long i, num, odd_sum = 0, even_sum = 0;

    cout << "Enter the value of num: ";
    cin >> num;
    for (i = 1; i <= num; i++){
        if (i % 2 == 0)even_sum += i;
        else odd_sum += i;
    }
    cout << "Sum of all odd numbers  = " <<  odd_sum << endl;;
    cout << "Sum of all even numbers = " << even_sum;
    return 0;
}


Another Way:

#include <iostream>
using namespace std;
 /*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){
    long long i = 1, num, odd_sum = 0, even_sum = 0;

    cout << "Enter the value of num: ";
    cin >> num;
    while(i <= num){
        odd_sum += i++;
        even_sum += i++;
    }
    cout << "Sum of all odd numbers  = " <<  odd_sum << endl;;
    cout << "Sum of all even numbers = " << even_sum;
    return 0;
}

No comments:

Post a Comment