Assignment 2 PF
Assignment 2 PF
ASSIGNMENT NO 2
Q1:Use ternary operator in a program to display whether the
given number is divisible by 10 or not. Take the number from
the user using scanf () function.
ANS: Here is a C program using the ternary operator to check if a
number entered by the user is divisible by 10:
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
(number % 10 == 0) ? printf("The number is divisible by 10.\n")
: printf("The number is not divisible by 10.\n");
return 0;
}
Q2. Discuss Switch statement with general syntax
ANS: Switch Statement in C
The switch statement is a multi-branch selection control structure that allows
executing one block of code among many based on the value of an expression.
It is often used as an alternative to multiple if-else statements when working
with discrete values.
General Syntax:
switch(expression) {
case constant1:
break;
case constant2:
break;
...
default:
}
Q3. Define for loop and discuss variations in for loop with
syntax.
ANS: for Loop in C
The for loop is a control structure used for iterating a block of code a specified
number of times. It is particularly useful when the number of iterations is
known in advance.
Variations of for Loop in C
#include <stdio.h>
int main() {
for(int i = 1, j = 5; i <= j; i++, j--) {
printf("i = %d, j = %d\n", i, j);
}
return 0;
}
#include <stdio.h>
int main() {
for(;;) {
printf("This is an infinite loop!\n");
break; // Use break to exit
}
return 0;
}
3. Omitting Initialization or Update:
Either the initialization or update (or both) can be moved outside the loop.
#include <stdio.h>
int main() {
int i = 1;
for(; i <= 5; ) {
printf("%d\n", i);
i++; // Update manually
}
return 0;
}
The loop logic can be executed without a body if it fits within the loop header.
#include <stdio.h>
int main() {
int sum = 0;
for(int i = 1; i <= 5; sum += i, i++);
printf("Sum = %d\n", sum);
return 0;
}
Q4. Write a program using nested for loop which displays the
following output.
1
12
123
1234
12345
123456
1234567
12345678
123456789
ANS: Here's a C program using nested for loops to display the desired
output:
#include <stdio.h>
int main() {
// Outer loop for rows
for(int i = 1; i <= 9; i++) {
// Inner loop for columns
for(int j = 1; j <= i; j++) {
printf("%d", j); // Print numbers
}
printf("\n"); // New line after each row
}
return 0;
}