[go: up one dir, main page]

0% found this document useful (0 votes)
311 views23 pages

Unit-2 Question and Answeres

The document discusses the differences between while-do and do-while loops, provides examples of nested for loops, asks to write a program to calculate mn value using while and do-while loops, and explains counter-controlled and condition-controlled loops with examples. It also defines selection statements, discusses their necessity, and explains if, if-else, nested if, else-if ladder, switch, and conditional operators.

Uploaded by

mallajasmitha7
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)
311 views23 pages

Unit-2 Question and Answeres

The document discusses the differences between while-do and do-while loops, provides examples of nested for loops, asks to write a program to calculate mn value using while and do-while loops, and explains counter-controlled and condition-controlled loops with examples. It also defines selection statements, discusses their necessity, and explains if, if-else, nested if, else-if ladder, switch, and conditional operators.

Uploaded by

mallajasmitha7
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/ 23

Unit-2

1. Differentiate between while-do and do while.

Ans :-
While loop do-while loop

Condition is checked first then statement(s) is Statement(s) is executed atleast once,


executed. thereafter condition is checked.

It might occur statement(s) is executed zero


times, If condition is false. At least once the statement(s) is executed.

No semicolon at the end of while. Semicolon at the end of while.


while(condition) while(condition);

If there is a single statement, brackets are not


required. Brackets are always required.

Variable in condition is initialized before the variable may be initialized before or within the
execution of loop. loop.

while loop is entry controlled loop. do-while loop is exit controlled loop.

do
while(condition) {
{ statement(s);
statement(s); }
} while(condition);

2. Write about nested for loop statement with examples

C programming allows to use one loop inside another. A loop consists one or more than one loop in
the statement body is called Nested Loop.

Syntax:-

The syntax for a nested for loop statement in C is as follows −

for ( init; condition; increment ) {

for ( init; condition; increment ) {


statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows −

while(condition) {

while(condition) {
statement(s);
}
statement(s);
}

The syntax for a nested do...while loop statement in C programming language is as follows −

do {
statement(s);

do {
statement(s);
}while( condition );

}while( condition );

A final note on loop nesting is that you can put any type of loop inside any other type of loop. For
example, a 'for' loop can be inside a 'while' loop or vice versa.

Example:-

The following program uses a nested for loop to find the prime numbers from 2 to 100 −

#include <stdio.h>

void main ()
{

int i, j;

for(i = 2; i<100; i++)


{
for(j = 2; j <= (i/j); j++)
{

if(!(i%j))
break; // if factor found, not prime
if(j > (i/j))
printf("%d is prime\n", i);
}

}
3. Write a C program to calculate mn value using while and do while loop.(Program)

4. Explain counter-controlled and condition-controlled loops with examples.

Ans:-

• Count-controlled repetition requires

• control variable (or loop counter)


• initial value of the control variable
• increment (or decrement) by which the control variable is modified each iteration
through the loop
• condition that tests for the final value of the control variable

• A count-controlled repetition will exit after running a certain number of times. The count is
kept in a variable called an index or counter.
• When the index reaches a certain value (the loop bound) the loop will end.
• Count-controlled repetition is often called definite repetition because the number of repetitions is
known before the loop begins executing.

Exampl:- For loop program

Condition-controlled loops

Condition-controlled loops are also called WHILE loops A WHILE loop code is repeated
based on a certain condition. The condition could be 'true' or 'false'. The
WHILE loop executes while a condition is true. Whether the condition is met or not is
checked at the beginning of the loop.

Example :- While loop Program


5. What are selection statements? What is the necessity of selection statements?

Sol :-

Selection or Decision Making Statements:-

Decision making structures require that the programmer specifies one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.

C programming language assumes any non-zero and non- null values as true, and if it is either zero or null,
then it is assumed as false value.
In “C” language Selection statements are divided in four types . They are

1.if Statement
2.switch Statement
3.Conditional Operator
4. goto Statement

1. if Statement
In “C” language an if statement is categorized into four types
.
• simple if
• if –else
• Nested if
• else – if ladder

• simple if Statement

One of the simplest ways to control program flow is by using if selection statements. Whether a
block of code is to be executed or not to be executed can be decided by this statement. The syntax
for if selection statement in C could be as follows:

if(condition)
{
statement(s); /*to be executed, on condition being true*/
}

For example,

if (a > 1)
{
printf("a is larger than 1");
}

Where a > 1 is a condition that has to evaluate to true in order to execute the statements inside
the if block. In this example "a is larger than 1" is only printed if a > 1 is true. if selection
statements can omit the wrapping braces { and } if there is only one statement within the block.
• if-else statement

While if performs an action only when its condition evaluate to true , if / else allows you to specify the
different actions when the condition true and when the condition is false .The Syntax if-else statement is

if(condition)
{
statement(s); /*to be executed, on condition being true*/
}
else
{
statement(s); /*to be executed, on condition being false*/
}

Example:

if (a > 1)
puts("a is larger than 1");
else
puts("a is not larger than 1");

Just like the if statement, when the block within if or else is consisting of only one statement, then the
braces can be omitted (but doing so is not recommended as it can easily introduce problems involuntarily).
However if there's more than one statement within the if or else block, then the braces have to be used on
that particular block.

• Nested if statement

An if statement consists one or more than one if statements in either true block or false block called
as nested if statement. Nested if()...else statements take more execution time (they are slower) in
comparison to an if()...else ladder because the nested if()...else statements check all the inner
conditional statements once the outer conditional if() statement is satisfied, whereas
the if()..else ladder will stop condition testing once any of the if() or the else if() conditional
statements are true.

Syntax:-

if(condition-1)
{
if(condition-2)
{
statement(s); /*to be executed, on condition being true*/
}
else
{
statement(s); /*to be executed, on condition being false*/
}
.
.
}
else
{
if(condition-3)
{
statement(s); /*to be executed, on condition being true*/
}
else
{
statement(s); /*to be executed, on condition being false*/
}
.
.

• else-if ladder

if()...else Ladder Chaining two or more if () ... else statements While the if ()... else statement
allows to define only one (default) behaviour which occurs when the condition within the if () is
not met, chaining two or more if () ... else statements allow to define a couple more behaviors
before going to the last else branch acting as a "default", if any.

Syntax:-

If(condition-1)
{

}
else if (condition-2)
{

}
else if (condition-3)
{

}
.
.
else
{

2.switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case. The syntax for
a switch statement in C programming language is as follows −

Syntax

switch(expression)
{

case constant-expression :
statement(s);
break; /* optional */

case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

The following rules apply to a switch statement –

• The expression used in a switch statement must have an integral or enumerated type, or be
of a class type in which the class has a single conversion function to an integral or
enumerated type.
• You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.

3. Condtional Operator(?:)

It is also known as ternary operator. This operator is used to perform selection or branching in a
program. The conditional operator represents with a symbol “ ? :”.It can be used to
replace if...else statements. It has the following general form −

(Exp/Condition ? True Block : False Block);


• If Condtion is evaluated. If it is true, then True Block is evaluated and becomes the value
of the entire ? expression.
• If Condtion is false, then False Block is evaluated and its value becomes the value of the
expression.
4.goto Statement
“goto” is unconditional statements.This statement is also used for to perform repetition in a
program.
Syntax:-
Lable-Name:
--
--
goto lable;

6. Differentiate the conditional operator with if else statement. Explain with the help of an
example.

Refer above notes

7. Write C program to check whether the given number is even or odd without using %
(modulus) operator.
8. What are the different types of control statements available ’C’. Explain them
with an example?

Sol:-

The control statement is a combination of some conditions that direct the body of the loop to
execute until the specified condition. In looping, a program executes the sequence of
statements many times until the stated condition becomes false. A loop consists of two parts,
a body of a loop and a control statement. Depending upon the position of a control statement
in a program, a loop is classified into two types:

• Entry controlled loop

In an entry controlled loop, a condition is checked before executing the body of a loop. It is also
called as a pre-checking loop.

• Exit controlled loop

In an exit controlled loop, a condition is checked after executing the body of a loop. It is also called
as a post-checking loop

'C' programming language provides us with three types of loop constructs:

1.while loop

2. do-while loop

3.for loop

While Loop

A while loop is the most straightforward looping structure. It is an entry-controlled loop. In while
loop, a condition is evaluated before processing a body of the loop. The basic format of while loop
is as follows:

While (condition )
{
Statements;
}

Following program illustrates a while loop:

#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10

Do-While loop

A do-while loop is similar to the while loop except that the condition is always executed after the
body of a loop. It is also called an exit-controlled loop. In a while loop, the body is executed if and
only if the condition is true. In some cases, we have to execute a body of the loop at least once even
if the condition is false. This type of operation can be achieved by using a do-while loop

The Syntax of while loop is as follows:

do
{
statements
--
--
}
while (expression);

In the do-while loop, the body of a loop is always executed at least once. After the body is executed,
then it checks the condition. If the condition is true, then it will again execute the body of a loop
otherwise control is transferred out of the loop.

The following program illustrates the working of a do-while loop:

#include<stdio.h>
#include<conio.h>
void main()
{
int num=1; //initializing the variable do
do
{

}
Output: printf("%d\n",2*num);
2 num++; //incrementing operation
4 }
6 while(num<=10);
8
10
12
14
16
18
20
for loop

A for loop is a more efficient loop structure in 'C' programming. The general structure
of for loop is as follows:

for (initial value; condition; incrementation or decrementation )


{
statements;
}

The initial value of the for loop is performed only once. The condition is a Boolean expression
that tests and compares the counter to a fixed value after each iteration, stopping the for loop
when false is returned. The incrementation/decrementation increases (or decreases) the counter
by a set value.

Following program illustrates the use of a simple for loop:

#include<stdio.h>

int main()
{
int number;
for(number=1;number<=10;number++) //for loop to print 1-10 numbers
{
printf("%d\n",number); //to print the number
}
return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10
9. Write briefly about the conditional and unconditional statements.

Sol:- Refer Q-NO -5

10. Write a program to award the grad to the students using switch statements

11. Write a program that asks user an arithmetic operator('+', '-', '*' or '/') and two
operands and perform the corresponding calculation on the operands. Use a switch
statement.
12. Write a C program to check whether a number entered by user is even or odd. Use
a if else statement.

13. Explain the working of ternary Operator with example.

Sol:-

It is also known as ternary operator. This operator is used to perform selection or branching in a
program. The conditional operator represents with a symbol “ ? :”.It can be used to
replace if...else statements. It has the following general form −

(Exp/Condition ? True Block : False Block);

• If Condtion is evaluated. If it is true, then True Block is evaluated and becomes the
value of the entire ? expression.
• If Condtion is false, then False Block is evaluated and its value becomes the value of the
expression.
Example :

14. Explain Logical operators

Sol:-

An operator which combined two operands called as Logical Operators.Following table


shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then the condition
becomes true.
|| Called Logical OR Operator. If any of the (A || B) is true.
two operands is non- zero, then the
condition becomes true.
! Called Logical NOT Operator. It is used to !(A &&
reverse the logical state of its operand. If a B) is true.
condition is true, then Logical NOT
operator will make it false.
Example
#include <stdio.h>

main() {

int a = 5;
int b = 20;
int c ;

if ( a && b ) {
printf("Line 1 - Condition is true\n" );
}

if ( a || b ) {
printf("Line 2 - Condition is true\n" );
}

/* lets change the value of a and b */


a = 0;
b = 10;

if ( a && b )
{
printf("Line 3 - Condition is true\n" );
}
else
{
printf("Line 3 - Condition is not true\n" );
}

if ( !(a && b) ) {
printf("Line 4 - Condition is true\n" );
}

Output:-

Line 1 - Condition is true


Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
15. Explain if-else statement and nested if-else statement with syntaxes and suitable
examples.

Refer Q.No :5

16. Write a C program to accept an integer number and print the digits using words
(for example 356 is printed as Three Five Six)

17 .If break was not given in the switch statement, what happens? Explain with example

Sol:-

A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each switch case. The syntax
for a switch statement in C programming language is as follows −
Syntax

switch(expression)
{

case constant-expression :
statement(s);
break; /* optional */

case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

The following rules apply to a switch statement –

• The expression used in a switch statement must have an integral or enumerated type, or
be of a class type in which the class has a single conversion function to an integral or
enumerated type.
• You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases is
true. No break is needed in the default case.

If no break appears in any case block then the flow of control will fall through to subsequent
cases blocks.

Example :-

#include<stdio.h>
void main()
{
int a=15,b=6;
switch(a>b)
{
Case 1:
Pintf(“a is Largest \n”);
Case 0:
Printf(“b is Largest \n”);
}
Output :-
a is Largest
b is Largest

18. What is the importance of the break and continue? Give examples.

Difference Between break and continue


break continue
A break can appear in both switch and loop A continue can appear only in loop
(for, while, do) statements. (for, while, do) statements.
A break causes the switch or loop statements to A continue doesn't terminate the loop, it causes
terminate the moment it is executed. Loop the loop to go to the next iteration. All iterations
or switch ends abruptly when break is of the loop are executed even if continue is
encountered. encountered. The continue statement is used to
skip statements in the loop that appear after
the continue.
The break statement can be used in The continue statement can appear only in loops.
both switch and loop statements. You will get an error if this appears in switch
statement.
When a break statement is encountered, it When a continue statement is encountered, it gets
terminates the block and gets the control out of the control to the next iteration of the loop.
the switch or loop.
A break causes the innermost enclosing loop A continue inside a loop nested within
or switch to be exited immediately. a switch causes the next loop iteration.
Example :- Example :-
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i; int i;
for(i=1;i<=10;i++) for(i=1;i<=10;i++)
{ {
if (i==5) if (i==5)
break; continue;
printf(“%d \t”,i); printf(“%d \t”,i);
} }

OutPut :-1 2 3 4 OutPut :-1 2 3 4 6 7 8 9 10


19. Write a program to sum the digits in a given number.

20. Draw the flow chart for the Armstrong number and write the program.

21. What is meant by pretest and posttest loop?

Sol:-
22. .Give the differences between break and exit() statements in C language.

Difference between break and exit()


break exit()
break is a keyword in C. exit() is a standard library function.
break causes an immediate exit from exit() terminates program execution when it is
the switch or loop (for, while or do). called.
No header files needs to be included in stdlib.h needs to be included in order to
order to use break statement in a C use exit().
program.
break transfers the control to the statement exit() returns the control to the operating
follows the switch or loop system or another program that uses this one as
(for, while or do) in which break is a sub-process.
executed.
Example of break Example of exit()
// some code here before while loop // some code here before while loop
while(true) while(true)
{ {
... ...
if(condition) if(condition)
break; exit(-1);
} }
// some code here after while loop // some code here after while loop
In the above code, break terminates In the above code,
the while loop and some code here after when if(condition) returns true, exit(-1) will be
while loop will be executed after breaking executed and the program will get terminated.
the loop. Upon call of exit(-1); -1 will be returned to the
calling program that is operating system most
of the time. The some code here after while
loop will never be executed in this case.
Conclusively, break is a program control exit() is a libbrary function, which causes
statement which is used to alter the flow of immediate termination of the entire program,
control upon a specified conditions. forcing a return to the operating system.
23. Write a program to greatest common divisor (GCD) of two integers m and n

24.Explain different looping statements with syntax and examples

Refer Q.No-8

25. Write a C program to generate and print the numbers between 100 and 200 which are
divisible by 3 but not divisible by 4.
26..Write a C program to find factorial of given number using for loop.

27. Explain nested. if else and else if ladder with syntax and give examples respectively?

Refer .No-5

You might also like