Week4: Looping Statements in C (for, while, do-while)
Q1. Check Prime Number
Question:
Write a program to check if a number is prime or not using a for loop.
Program:
#include <stdio.h>
int main() {
int num, i, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &num);
if (num <= 1) {
isPrime = 0;
} else {
for (i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
}
if (isPrime) {
printf("%d is prime.\n", num);
} else {
printf("%d is not prime.\n", num);
}
return 0;
}
````
---
## Q2. Magic Number Using `do-while`
**Question:**
Write a program to check if a number is a magic number using a `do-while` loop.
**Hint:**
* Find the sum of the digits of the given number.
* If the product of the sum and the reverse of the sum equals the given number, then it is a magic number.
Example:
Number: 1729 Sum of digits: 1+7+2+9 = 19 Reverse of sum: 91 Product: 19 * 91 = 1729 → Magic number
**Program:**
```c
#include <stdio.h>
int reverse(int num) {
int rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
return rev;
}
int main() {
int num, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
int temp = num;
do {
sum += temp % 10;
temp = temp / 10;
} while (temp != 0);
int revSum = reverse(sum);
if (num == sum * revSum) {
printf("%d is a magic number.\n", num);
} else {
printf("%d is not a magic number.\n", num);
}
return 0;
}
Q3. Factorial of Numbers from 1 to n
Question:
Write a program to print factorials of all numbers from 1 to n using nested loops.
Example:
If user input is 5, output should be:
Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120
Program:
#include <stdio.h>
int main() {
int n, i, j, factorial;
printf("Enter a number: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
factorial = 1;
for (j = 1; j <= i; j++) {
factorial *= j;
}
printf("Factorial of %d = %d\n", i, factorial);
}
return 0;
}
Q4. Fibonacci Series Using Loop
Question: Write a program to print the Fibonacci series using a loop.
Program:
#include <stdio.h>
int main() {
int n, i, first = 0, second = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 0; i < n; i++) {
if (i <= 1) {
next = i;
} else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
printf("\n");
return 0;
}