Lab Report 2
Lab Report 2
Questions:
1. Write a program to demonstrate else if ladder.
2. Write a program to display the day of the week based on user input (1-7)
using switch case.
3. Write a program to print the first 10 natural numbers using a for loop.
4. Write a program to calculate the factorial of a number using a while loop.
5. Write a program to terminate a loop prematurely using break.
6. Write a program to skip specific iterations in a loop using continue.
7. Write an example program that causes an infinite loop unintentionally
(e.g., missing condition update).
8. Modify the program to fix the issue and explain what went wrong.
9. Write an example program where a misplaced conditional causes
incorrect behavior (e.g., using a semicolon after if) and correct it.
Solutions
1: Ans:
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: "); // Input marks
scanf("%d", &marks); // Evaluate marks using if-else-if ladder
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 80) {
printf("Grade: B\n");
} else if (marks >= 70) {
printf("Grade: C\n");
} else if (marks >= 60) {
printf("Grade: D\n");
} else
{
printf("Grade: F\n");
}
return 0;
}
2. Ans
#include <stdio.h>
int main() {
int day;
printf("Enter a day number (1-7): "); // Input day number
scanf("%d", &day); // Determine the day of the week
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day number. Please enter a number between 1 and 7.\
n");
}
return 0;
}
3. Ans
#include <stdio.h>
int main() {
// Print the first 10 natural numbers
printf("The first 10 natural numbers are:\n");
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
4. Ans
#include <stdio.h>
int main() {
int num, factorial = 1, i; // Input a number from the user
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n"); // Check if the number
is non-negative
} else {
i = num; // Initialize the counter
while (i > 0) {
factorial *= i; // Multiply factorial by the current value of i
i--; // Decrement the counter
}// Display the result
printf("The factorial of %d is: %d\n", num, factorial);
} return 0;
}
5. Ans
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
printf("%d\n", i);
}
return 0;
}
6. Ans
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // skip i==5 and continue
}
printf("%d\n", i);
}
return 0;
}
7. Ans
#include <stdio.h>
int main() {
int i = 1;
int main() {
int i = 1;
int main() {
int num;
return 0;
}