Lab 3
Lab 3
Faculty of Engineering
Department of Computer Engineering
COMP 124
COMPUER PROGRAMING
#include <stdio.h>
int main() {
scanf("%d", &lower);
scanf("%d", &upper);
lower = upper;
upper = temp;
printf("%d\n", i);
return 0;
}
b) Here's a C program that uses a do-while loop to keep asking the user for integer values and calculates
the summation of all values until a zero value is entered
#include <stdio.h>
int main() {
int value;
int sum = 0;
do {
scanf("%d", &value);
return 0;
In this program, we use a do-while loop because we want to ensure that the loop runs at least once,
even if the user enters zero as the first value. The loop continues to ask the user for integer values using
scanf until a zero value is entered. The sum variable keeps track of the summation of all values entered
by the user. Once the loop is exited, the program prints the total sum of all values.
c) Here's a C program that asks the user to enter a positive number and checks if the entered number
has a good friend using a loop and mathematical calculations without using any library functions like
power or square root.
#include <stdio.h>
int main() {
int num;
scanf("%d", &num);
int sum_of_divisors = 0;
if (num % i == 0) {
sum_of_divisors += i;
if (square(sum_of_divisors) == num) {
} else {
return 0;
In this program, we use a loop to calculate the sum of divisors of the entered number num by iterating
from 1 to num-1 and checking if num is divisible by the current iteration value i. If it is, we add i to the
sum_of_divisors variable. Finally, we check if the square of the sum_of_divisors is equal to num, and if
so, we print that num is a good friend of sum_of_divisors. Otherwise, we print that num does not have a
good friend.
d) Here's a C program that prints the given pattern using nested do-while loops.
#include <stdio.h>
int main() {
int num = 1;
int i = 1;
do {
int j = 1;
do {
num += 2;
j++;
printf("\n");
i++;
return 0;
In this program, we use nested do-while loops to print the pattern. The outer loop runs 4 times, and the
inner loop runs 5 times. Inside the inner loop, we print the value of num which starts from 1 and is
incremented by 2 in each iteration to generate the sequence of odd numbers. After each row is printed,
a newline character is printed to move to the next row.
e) Here's a C program that prints the given pattern based on the user input n using nested while loops.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int num = n;
int i = 1;
while (i <= n) {
int j = 1;
while (j <= i) {
j++;
printf("\n");
num = num - 1;
i++;
return 0;
In this program, we use nested while loops to print the pattern based on the user input n. The outer
loop runs n times, and the inner loop runs i times in each iteration of the outer loop. Inside the inner
loop, we print the value of num which starts from n and is decremented by 1 in each iteration to
generate the desired pattern. After each row is printed, a newline character is printed to move to the
next row.