StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Program #15 (U2): Sum of First N using three loops
Download
  1. C Programming
  2. C Programming Practice
Program #14 (U2): Character Classifier using switch : Program #16 (U2): Prime Number Test with Early Exit
C Programming Practice

Task: Read N and compute the sum using for, then while, then do…while. Print all three results and confirm they match.

 
/* 

  Program: Sum of First N Natural Numbers using three loops (U2)

  What it does:

    - Reads N (>=0) and computes the sum using: for, while, do-while.

    - Prints all three sums and verifies they match.

*/

 
#include <stdio.h>

 
int main(void) {

    int N;

    long long s_for = 0, s_while = 0, s_do = 0;

 
    printf("Enter N (>=0): ");

    if (scanf("%d", &N) != 1 || N < 0) {

        printf("Invalid N. Use a non-negative integer.

");

        return 0;

    }

 
    /* for loop */

    for (int i = 1; i <= N; ++i) s_for += i;

 
    /* while loop */

    int j = 1;

    while (j <= N) { s_while += j; ++j; }

 
    /* do-while loop */

    int k = 1;

    if (N >= 1) {

        do { s_do += k; ++k; } while (k <= N);

    } else {

        s_do = 0;

    }

 
    printf("Sum via for   = %lld

", s_for);

    printf("Sum via while = %lld

", s_while);

    printf("Sum via do    = %lld

", s_do);

    printf("All equal? %s

", (s_for == s_while && s_for == s_do) ? "Yes" : "No");

 
    return 0;

}

 

 

Program #14 (U2): Character Classifier using switch Program #16 (U2): Prime Number Test with Early Exit
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website