Problem Solving using C Language

0 of 85 lessons complete (0%)

Loops

Lab: while Loop

Program 1: Print Numbers from 1 to N

Objective: Input a number N and print all numbers from 1 to N.

#include <stdio.h>

void main() {
  int i = 1, N;
  
  printf("Enter a number: ");
  scanf("%d", &N);
  
  while (i <= N) {
    printf("%d ", i);
    i++;
  }
}

Program 2: Sum of Digits of a Number

Objective: Calculate the sum of digits of a given number.

#include <stdio.h>

void main() {
  int num, sum = 0, remainder;
  
  printf("Enter a number: ");
  scanf("%d", &num);
  
  while (num != 0) {
    remainder = num % 10;
    sum += remainder;
    num /= 10;
  }
  
  printf("Sum of digits = %d\n", sum);
}

Program 3: Check if a Number is Prime

Objective: Input a number and check whether it is a prime number.

#include <stdio.h>

void main() {
  int num, i = 2, flag = 1;
  
  printf("Enter a number: ");
  scanf("%d", &num);
  
  if (num <= 1) {
    flag = 0; // Numbers less than or equal to 1 are not prime
  }
  
  while (i <= num / 2) {
    if (num % i == 0) {
      flag = 0;
      break;
    }
    i++;
  }
  
  if (flag == 1) {
    printf("%d is a prime number\n", num);
  } else {
    printf("%d is not a prime number\n", num);
  }
  
}

Program 4: Find the Greatest Common Divisor (GCD)

Objective: Calculate the GCD of two numbers using a while loop.

#include <stdio.h>

void main() {
  int a, b;
  
  printf("Enter two numbers: ");
  scanf("%d %d", &a, &b);
  
  while (a != b) {
    if (a > b)
      a = a - b;
    else
      b = b - a;
  }
  
  printf("GCD = %d\n", a);
}

5. Multiplication table using while loop

#include <stdio.h>

void main() {
  int num, i = 1;

  // Input from the user
  printf("Enter a number to generate its multiplication table: ");
  scanf("%d", &num);

  // While loop for multiplication table
  while (i <= 10) {
    printf("%d x %d = %d\n", num, i, num * i);
    i++; // Increment the counter
  }

}

Output:

Enter a number to generate its multiplication table: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50