0% found this document useful (0 votes)
16 views29 pages

C UNIT 2 Answers TT1

The document provides a comprehensive overview of control structures in C programming, including definitions, syntax, and examples for various statements such as if-else, switch-case, loops, and nested loops. It also includes comparisons between different types of loops and control statements, along with practical programming exercises to illustrate their usage. Key concepts like entry-controlled and exit-controlled loops, as well as the roles of break, continue, and goto statements, are discussed in detail.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views29 pages

C UNIT 2 Answers TT1

The document provides a comprehensive overview of control structures in C programming, including definitions, syntax, and examples for various statements such as if-else, switch-case, loops, and nested loops. It also includes comparisons between different types of loops and control statements, along with practical programming exercises to illustrate their usage. Key concepts like entry-controlled and exit-controlled loops, as well as the roles of break, continue, and goto statements, are discussed in detail.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT – II (SHORT ANSWERS WITH QUESTIONS)

1. Define a control structure in C. Name any two types.


A control structure controls the flow of execution in a program.
Types: Selection, Looping, Jumping.

2. Write the syntax of switch-case statement.

switch(expression) {

case value: statements; break;

default: statements;

3. Write the syntax of for loop.

for(initialization; condition; increment/decrement) {

statements;

4. Write the syntax of if-else statement.

if(condition) { statements; }

else { statements; }

5. Mention any two differences between if-else and switch.

• if-else works on conditions/ranges.

• switch works on exact matching values.

6. Write a simple if statement to check whether a number is even.

if(n % 2 == 0) printf("Even");

7. Differentiate between if and if-else statements with example.

• if executes only when true.

• if-else executes true and false cases.

8. What will be the output?

int x=5;

if(x>0) printf("Positive");

Output: Positive
9. What is the purpose of default case in switch?
It executes when no case matches.

10. What is the purpose of else-if ladder?


To test multiple conditions in sequence.

11. Write one difference between continue and goto.

• continue skips current loop iteration.

• goto jumps to a labeled statement.

12. What is the role of break statement?


It terminates loops or switch.

13. What is an infinite loop? Give an example.


Loop that never ends.
Example: while(1) { }

14. Can a for loop execute without initialization?


Yes.
Example: for(; i<5; i++).

15. Mention two differences between entry-controlled and exit-controlled


loops.

• Entry-controlled: test before loop (for, while)

• Exit-controlled: test after loop (do-while)

16. What is a nested loop? Give example.


A loop inside another loop.
Example: matrix printing.

UNIT – II LONG ANSWERS (Short 8-Mark Format)

Q1) Write short notes on switch statement with example.

A switch statement is a selection control structure used when one value must be
matched against many fixed options.
It makes programs more readable than multiple if-else-if statements.

Syntax:

switch(expression) {

case value1: statements; break;


case value2: statements; break;

default: statements;

Explanation:

• switch checks the value of the expression.

• case contains possible matching values.

• break stops execution from falling to next case.

• default executes when no case matches.

Example:

int ch = 2;

switch(ch){

case 1: printf("One"); break;

case 2: printf("Two"); break;

default: printf("Invalid");

Conclusion:
Use switch when there are multiple fixed choices.

Q2) Compare while, do-while, and for loops.

A loop is used to repeat statements until a condition becomes false.

Feature for Loop while Loop do-while Loop

Condition Check Before loop Before loop After loop

Guaranteed 1
No No Yes
Execution?

Known Condition-based Must execute at least


Best Use
iterations looping once

Examples:

for(i=1;i<=5;i++) printf("%d ",i);


i=1; while(i<=5){ printf("%d ",i); i++; }

i=1; do{ printf("%d ",i); i++; } while(i<=5);

Conclusion:
for is compact, while is flexible, do-while ensures one mandatory execution.

Q3) Write a C program to find the largest of three numbers using nested if.

Program:

#include <stdio.h>

int main(){

int a,b,c;

printf("Enter three numbers: ");

scanf("%d %d %d",&a,&b,&c);

if(a>b){

if(a>c)

printf("Largest = %d",a);

else

printf("Largest = %d",c);

else {

if(b>c)

printf("Largest = %d",b);

else

printf("Largest = %d",c);

return 0;

Explanation (2 lines):
• First compare a and b

• Then compare the greater one with c to find the largest.

Q4) Explain the working of an if-else ladder with syntax and example.

The if-else ladder is used when we need to check multiple conditions one after
another.
Only the first true condition will execute, and the rest will be skipped.

Syntax:

if(condition1)

statement1;

else if(condition2)

statement2;

else if(condition3)

statement3;

else

default_statement;

Example (Grade System):

int marks;

scanf("%d",&marks);

if(marks >= 90)

printf("Grade A+");

else if(marks >= 80)

printf("Grade A");

else if(marks >= 70)

printf("Grade B");

else if(marks >= 60)

printf("Grade C");
else

printf("Fail");

Conclusion:

The if-else ladder is best when there are multiple conditions and only one should be
executed.

Q5) Compare switch and if-else statements with examples.

Both if-else and switch are selection statements but used in different situations.

Feature if-else switch

Works On Conditions & ranges Fixed constant values

Suitable For Complex logic Menu / choice based

Speed Slower when many conditions Faster due to jump table

Data Types int, float, char, expression int, char only

if-else Example:

if(x > 0) printf("Positive");

else printf("Negative");

switch Example:

switch(x){

case 1: printf("One"); break;

case 2: printf("Two"); break;

default: printf("Other");

Conclusion:

Use if-else for conditions; use switch for multiple fixed options.

Q6) Write a C program using for loop to print the multiplication table of a given
number.

Program:
#include <stdio.h>

int main(){

int n,i;

printf("Enter a number: ");

scanf("%d",&n);

for(i=1;i<=10;i++){

printf("%d x %d = %d\n", n, i, n*i);

return 0;

Explanation (2 lines):

• Loop runs from 1 to 10

• Each step prints n * i

Q7) Explain how nested loops are used to process 2D arrays with example.

A 2D array stores data in rows and columns.


To access all elements, we use one loop for rows and another loop inside it for
columns.
This is called a nested loop.

Example: Reading and Displaying a 2D Array

#include <stdio.h>

int main(){

int a[3][3];

int i, j;

// Input elements

for(i=0;i<3;i++){

for(j=0;j<3;j++){
scanf("%d",&a[i][j]);

// Display elements

for(i=0;i<3;i++){

for(j=0;j<3;j++){

printf("%d ", a[i][j]);

printf("\n");

return 0;

Explanation:

• Outer loop controls rows

• Inner loop controls columns

Conclusion:

Nested loops are required to access each element of a 2D matrix.

Q8) Predict output and explain execution of the following code:

int x=0;

while(x<3){

x++;

if(x==2)

continue;

printf("%d ", x);

Execution Step-by-Step:
Step x Value Action

Start 0 Condition true

x++ → x=1 not 2 prints 1

x++ → x=2 equals 2 continue → skips print

x++ → x=3 not 2 prints 3

Condition fails → stop

Output:

13

Conclusion:

continue skipped printing the number 2.

Q9) Evaluate a situation where switch is more suitable than multiple if-else. Justify
with example.

switch is better when:

• We have multiple fixed choices

• Each choice represents a menu or category

• No range checking is required

Example: Menu Selection

int ch;

scanf("%d",&ch);

switch(ch){

case 1: printf("Start"); break;

case 2: printf("Stop"); break;

case 3: printf("Pause"); break;

default: printf("Invalid");

}
Why switch is better than if-else here?

Point Reason

Readability Clear cases, easy to follow

Efficiency Uses jump table for faster execution

Structure Avoids long if-else-if chain

Conclusion:

Use switch when there are multiple constant options like menus, modes, days,
grades, etc.

Q10) Analyze the role of break, continue, and goto statements with examples.

These are jump control statements used to change the normal flow of execution.

Statement Meaning Effect

break Terminates loop or switch Control moves out of block

continue Skips current iteration Goes to next loop cycle

goto Jumps to a labeled statement Unconditional jump

1) break Example

for(int i=1;i<=5;i++){

if(i==3)

break;

printf("%d ",i);

Output: 1 2
Stops when i becomes 3.

2) continue Example

for(int i=1;i<=5;i++){

if(i==3)
continue;

printf("%d ",i);

Output: 1 2 4 5
Skips value 3.

3) goto Example

int i=1;

start:

printf("%d ",i);

i++;

if(i<=3) goto start;

Conclusion:

Use break and continue carefully.


Avoid goto unless necessary because it reduces readability.

Q11) Write a C program using nested loops to print Floyd’s Triangle.

Floyd’s triangle prints continuous natural numbers row by row.

Pattern Example

23

456

7 8 9 10

Program:

#include <stdio.h>

int main(){

int i, j, n, num=1;

printf("Enter number of rows: ");

scanf("%d",&n);
for(i=1;i<=n;i++){

for(j=1;j<=i;j++){

printf("%d ", num);

num++;

printf("\n");

return 0;

Explanation:

• Outer loop → controls rows

• Inner loop → prints elements in each row

Q12) Write a C program to assign grades based on marks.

Grade Conditions

Marks Grade

> 90 A+

80–89 A

70–79 B

60–69 C

< 50 F

Program:

#include <stdio.h>

int main(){

int marks;

printf("Enter marks: ");


scanf("%d",&marks);

if(marks > 90)

printf("Grade A+");

else if(marks >= 80)

printf("Grade A");

else if(marks >= 70)

printf("Grade B");

else if(marks >= 60)

printf("Grade C");

else

printf("Grade F");

return 0;

Conclusion:

Uses if-else ladder to test multiple ranges.

Q13) Write a C program to count even and odd numbers between 1 to 50.

Logic:

• Use a loop from 1 to 50

• Check each number using n % 2 == 0

• Count even and odd separately

Program:

#include <stdio.h>

int main(){

int i, even=0, odd=0;


for(i=1;i<=50;i++){

if(i%2==0)

even++;

else

odd++;

printf("Total Even Numbers = %d\n", even);

printf("Total Odd Numbers = %d\n", odd);

return 0;

Conclusion:

Modulo operator helps to classify numbers.

Q14) Explain entry-controlled and exit-controlled loops with examples.

Entry-Controlled Loop

Condition is checked before loop execution.

Examples: for, while

int i=1;

while(i<=5){

printf("%d ", i);

i++;

Exit-Controlled Loop

Condition is checked after executing the loop body once.

Example: do-while

int i=1;
do{

printf("%d ", i);

i++;

}while(i<=5);

Feature Entry-Controlled Exit-Controlled

Condition Check Before loop After loop

Minimum Execution May not run Runs at least once

Conclusion:

Use do-while when code must execute once before checking condition.

Q15) Write a C program to calculate electricity bill using slab rates.

Slab Logic:

Units Rate

1–100 ₹3 per unit

101–200 ₹4 per unit

Above 200 ₹5 per unit

Program:

#include <stdio.h>

int main(){

int units;

float bill;

printf("Enter units consumed: ");

scanf("%d",&units);

if(units <= 100)

bill = units * 3;

else if(units <= 200)


bill = (100 * 3) + ((units - 100) * 4);

else

bill = (100 * 3) + (100 * 4) + ((units - 200) * 5);

printf("Total Electricity Bill = %.2f", bill);

return 0;

Conclusion:

Uses if-else ladder to compute different slab values.

Q16) Write a C program to find the factorial of a number using a for loop.

Logic:

Factorial of a number n is:

𝑛! = 𝑛 × (𝑛 − 1) × (𝑛 − 2) … 1

Program:

#include <stdio.h>

int main(){

int n, i;

long fact = 1;

printf("Enter a number: ");

scanf("%d", &n);

for(i = 1; i <= n; i++){

fact = fact * i;

}
printf("Factorial of %d = %ld", n, fact);

return 0;

Explanation:

• Loop multiplies values from 1 to n

• fact variable stores the result

Conclusion:

Factorial can be calculated simply using a loop.

Q17) Write a C program to print Fibonacci series up to n terms.

Logic:

Fibonacci series starts with 0 and 1, and each next number is sum of previous two.

Example:
0, 1, 1, 2, 3, 5, 8, 13...

Program:

#include <stdio.h>

int main(){

int n, i, a=0, b=1, c;

printf("Enter number of terms: ");

scanf("%d",&n);

printf("%d %d ", a, b);

for(i=3; i<=n; i++){

c = a + b;

printf("%d ", c);

a = b;

b = c;
}

return 0;

Explanation:

• First two terms are printed directly

• Loop generates remaining terms

Conclusion:

This uses loop + variable shifting technique.

Q18) Write a C program using nested loops to print the following pattern.

Pattern:

**

***

****

Program:

#include <stdio.h>

int main(){

int i, j, n;

printf("Enter number of rows: ");

scanf("%d",&n);

for(i=1; i<=n; i++){

for(j=1; j<=i; j++){

printf("* ");

printf("\n");

}
return 0;

Explanation:

• Outer loop controls number of rows

• Inner loop prints stars per row

Conclusion:

Nested loops help in printing row-column based patterns.

Q19) Write a C program to print the sum of digits of a number using a do-while loop.

Logic:

• Extract the last digit using n % 10

• Add it to sum

• Remove last digit using n / 10

• Repeat until number becomes zero

Program:

#include <stdio.h>

int main(){

int n, digit, sum = 0;

printf("Enter a number: ");

scanf("%d", &n);

do{

digit = n % 10;

sum = sum + digit;

n = n / 10;

}while(n > 0);

printf("Sum of digits = %d", sum);


return 0;

Explanation:

The loop continues until all digits are processed.

Q20) Write a C program to demonstrate the use of continue statement inside a


loop.

Logic:

continue skips a particular iteration inside a loop.

Program:

#include <stdio.h>

int main(){

int i;

for(i = 1; i <= 5; i++){

if(i == 3)

continue;

printf("%d ", i);

return 0;

Output:

1245

Explanation:

• When i becomes 3 → continue skips print

• Other values are printed normally.

Q21) Write a C program to print the following pattern using nested loops.

Pattern:
1

12

123

1234

Program:

#include <stdio.h>

int main(){

int i, j, n;

printf("Enter number of rows: ");

scanf("%d", &n);

for(i=1; i<=n; i++){

for(j=1; j<=i; j++){

printf("%d ", j);

printf("\n");

return 0;

Explanation:

• Outer loop controls rows

• Inner loop prints numbers in sequence

Q22) Write a C program to check whether a given number is palindrome or not.

Logic:

A number is palindrome if reverse of number = original number.


Example: 121 → reverse = 121 → Palindrome.

Program:
#include <stdio.h>

int main(){

int n, temp, rev=0, digit;

printf("Enter a number: ");

scanf("%d",&n);

temp = n; // Store original number

while(n > 0){

digit = n % 10;

rev = rev*10 + digit;

n = n / 10;

if(temp == rev)

printf("Palindrome Number");

else

printf("Not a Palindrome");

return 0;

Explanation:

• Reversing is done digit-by-digit

• Final comparison decides palindrome

Q23) Write a C program to perform a simple calculator using switch-case.

Logic:

• Take two numbers and an operator

• Use switch to check the operator and perform operation


Program:

#include <stdio.h>

int main(){

int a, b;

char op;

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

printf("Enter operator (+, -, *, /): ");

scanf(" %c", &op);

switch(op){

case '+': printf("Result = %d", a+b); break;

case '-': printf("Result = %d", a-b); break;

case '*': printf("Result = %d", a*b); break;

case '/': printf("Result = %d", a/b); break;

default : printf("Invalid Operator");

return 0;

Conclusion:

Switch is best suited for menu-based programs like calculators.

Q24) Write a C program to reverse a number.

Logic:

Use modulo % to extract digits and / to remove digits.

Program:

#include <stdio.h>

int main(){
int n, digit, rev = 0;

printf("Enter a number: ");

scanf("%d", &n);

while(n > 0){

digit = n % 10;

rev = rev*10 + digit;

n = n / 10;

printf("Reversed Number = %d", rev);

return 0;

Explanation:

Each loop iteration adds one digit to reversed number.

Q25) Write a C program to check whether a given number is Armstrong or not.

Definition:

A number is Armstrong if the sum of cubes of digits = original number.


Example:
153 = 1³ + 5³ + 3³ = 153 → Armstrong.

Program:

#include <stdio.h>

int main(){

int n, temp, digit, sum = 0;

printf("Enter a number: ");

scanf("%d", &n);

temp = n;
while(n > 0){

digit = n % 10;

sum = sum + (digit * digit * digit);

n = n / 10;

if(sum == temp)

printf("Armstrong Number");

else

printf("Not an Armstrong Number");

return 0;

Explanation:

• Cubes of digits are added

• Compared with original number

Q26) Write a C program to find the sum of series 1 + 2 + 3 + ... + n using loop.

Logic:

Use loop to accumulate sum from 1 to n.

Program:

#include <stdio.h>

int main(){

int n, i, sum = 0;

printf("Enter n: ");

scanf("%d", &n);
for(i = 1; i <= n; i++){

sum = sum + i;

printf("Sum = %d", sum);

return 0;

Explanation:

Loop adds numbers one-by-one to sum.

Q27) Write a C program to check whether an entered character is a vowel or


consonant using switch.

Logic:

• Character is vowel if it is a, e, i, o, u (either case)

Program:

#include <stdio.h>

int main(){

char ch;

printf("Enter a character: ");

scanf("%c", &ch);

switch(ch){

case 'a': case 'e': case 'i': case 'o': case 'u':

case 'A': case 'E': case 'I': case 'O': case 'U':

printf("Vowel"); break;

default:

printf("Consonant");
}

return 0;

Conclusion:

Switch is ideal for multiple fixed comparisons like vowels.

Q28) Write a C program to print numbers from 1 to n using while loop.

Logic:

Start from 1, print and increment until it reaches n.

Program:

#include <stdio.h>

int main(){

int n, i = 1;

printf("Enter n: ");

scanf("%d", &n);

while(i <= n){

printf("%d ", i);

i++;

return 0;

Explanation:

• i starts at 1

• Loop runs until i reaches n

Q29) Write a C program to display the following pattern using loops.

Pattern:
A

AB

ABC

ABCD

Program:

#include <stdio.h>

int main(){

int i, j, n;

printf("Enter number of rows: ");

scanf("%d",&n);

for(i=1; i<=n; i++){

for(j=1; j<=i; j++){

printf("%c ", 'A' + j - 1);

printf("\n");

return 0;

Explanation:

• Characters printed using ASCII ('A' + j - 1)

Q30) Write a C program to print the reverse of a string using loop.

Logic:

Find the length of string → print characters from last to first.

Program:

#include <stdio.h>

#include <string.h>
int main(){

char str[50];

int i, len;

printf("Enter a string: ");

gets(str);

len = strlen(str);

for(i = len-1; i >= 0; i--){

printf("%c", str[i]);

return 0;

Explanation:

• strlen() finds length

• Loop prints characters in reverse order

You might also like