PPS Unit 1 Question Bank
1. a) Differentiate between compiler and interpreter.
Ans: The difference between an interpreter and a compiler is given below:
Interpreter Compiler
Scans the entire program and translates it as
Translates program one statement at a time.
a whole into machine code.
It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time is source code but the overall execution time
slower. is comparatively faster.
Generates intermediate object code which
No intermediate object code is generated,
further requires linking, hence requires
hence are memory efficient.
more memory.
Continues translating the program until the It generates the error message only after
first error is met, in which case it stops. scanning the whole program. Hence
Hence debugging is easy. debugging is comparatively hard.
Programming language like Python, Ruby Programming language like C, C++ use
use interpreters. compilers.
1 b) Distinguish between variables and constants with example.
Ans:
Constants Variables
Constants are quantities with Variables are quantities with changing
unchanging values, and used to magnitude, hence can assume different
represent numbers with significance. values based on the application
Constants are used to represent the variables are used to represent
quantities in nature which are fixed unknowns.
Use constant when you want to
Use variable to store data that may or
declare something that won’t be
will change during the running of the
changed midway in your program
program.
execution.
Ex: const double PI = 3.14; Ex: int playerScore = 95;
1 c) What is an Identifier? List the rules required to form variable names in C.
Ans:
Identifier: An Identifier is a sequence of letters and digits, but must start with a letter. Identifiers are
case sensitive. Identifiers specifies the names to the particular entity such as name of variables, functions
etc.
Valid identifiers: Root, _getchar, __sin, x1, x2, x3, x_1, If
Invalid identifiers: 324, short, price$, My Name
Variable indicates the name of the data value. We can store data in a memory space and name it, so that
it becomes easier to access memory space. The naming of an address is known as variable. Unlike
constant, variables are changeable; we can change value of a variable during execution of a program.
Rules to name a variable:
• The name of a variable can be composed of letters, digits, and the underscore character.
• Variable name must not start with a digit.
• Blank spaces are not allowed in variable name.
• Keywords are not allowed as variable name.
• C is case-sensitive, so it is suggested to keep the variable names in lower case.
2. a) What is a flowchart? Explain with one example.
Ans: Flow chart
A flowchart is a schematic representation of an algorithm or the diagrammatic representation of way to
solve the given problem.
Flowcharts are drawn using certain special purpose symbols such as Rectangles, Diamonds, Ovals and
small circles. These symbols are connected by arrows called flow lines.
Flowcharts can be used to describe all sorts of processes: business, educational, personal and of course
algorithms.
So, flowcharts are often used as a program planning tool to visually organize step-by-step process of a
program.
The following are the most common symbols used in drawing flowcharts:
Example 1: Flow chart for printing 1 to 20:
2 b) What is an algorithm. Give an example.
Ans:
Algorithm is a systematic logical approach which is a well-defined, step-by-step procedure that allows
a computer to solve a problem. This is the first step to solve a mathematical or computer problem. A
sequence of activities to be processed for getting desired output from a given input. A
computer program can be viewed as an elaborate algorithm.
While writing algorithms we will use following symbol for different operations:
o ‘+’ for Addition
o ‘-’ for Subtraction
o ‘*’ for Multiplication
o ‘/’ for Division and
o ‘←’ for assignment
The properties of an algorithm are:
1. Input: Algorithm should be accepting 0 or more inputs supplied externally.
2. Output: Algorithm should be generating at least one output.
3. Definiteness: Each step of an algorithm must be precisely defined. Meaning the step should perform
a clearly defined task without much complication.
4. Finiteness: An algorithm must always terminate after a finite number of steps.
5. Effectiveness: The efficiency of the steps and the accuracy of the output determine the effectiveness
of the algorithm.
6. Correctness: Each step of the algorithm must generate a correct output.
Example: Algorithm to add two numbers
Step 1: Start
Step 2: Read values num1 and num2.
Step 3: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 4: Write/ Display sum
Step 5: Stop.
3. a) Draw the flow chart to find the roots of the given equation ax2+bx+c=0.
Ans:
3 b) Draw a flow chart to find average of 10 numbers.
Ans:
4. Explain the following operators with suitable examples
a) Arithmetic Operators
Ans: Arithmetic Operators are used to performing mathematical calculations.
Example: C program to find sum of 2 numbers
#include <stdio.h>
void main()
{
int i=3,j=7,k;
k=i+j;
printf("sum of two numbers is %d\n", k);
}
Output: sum of two numbers is 10
4 b) Logical operators
Ans: LOGICAL OPERATORS: An expression of this kind which combines two or more relational
expressions is termed as a logical expressions or a compound relational expression. The operators and
truth values are
op-1 !op-1 op-1
non-zero Zero non-zero
zero non-zero zero
op-1 || op-
op-1 op-2 op-1 && op-2
2
non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0 0 0 0
Example: C program to demonstrate working of logical operators
#include <stdio.h>
int main()
{
int a=10, b=4, c = 10, d = 20;
// logical AND example
if (a>b && c==d)
printf("a is greater than b AND c is equal to d\n");
else
printf("AND condition not satisfied\n");
// logical AND example
if (a>b || c==d)
printf("a is greater than b OR c is equal to d\n");
else
printf("Neither a is greater than b nor c is equal to d\n");
// logical NOT example
if (!a)
printf("a is zero\n");
else
printf("a is not zero");
return 0;
}
Output:
AND condition not satisfied
a is greater than b OR c is equal to d
a is not zero
4 c) Relational operators
Ans: RELATIONAL OPERATORS: We often compare two quantities and depending on their relation
take certain decisions for that comparison we use relational operators.
Operator meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
Example: C program to find largest among three numbers
#include<stdio.h>
main()
{
int i, j, k;
printf("Enter any three numbers ");
scanf("%d%d%d", &i, &j, &k);
if(i>j)
{
if(i>k)
printf(“%d is greater\n”,i);
else
printf(“%d is greater\n”, k);
}
else if(j>i)
{
if(j>k)
printf(“%d is greater\n”, j);
else
printf(“%d is greater\n”, k);
}
else
printf(“All are equal”);
}
4 d) Bit wise operators
Ans: Bitwise Operators: Thisoperators perform bit level operations. The operations are performed
based on the binary values.
For example: A = 25 (11001) and B = 20 (10100)
5. a) What are unary operators supported in C
Ans: Increment & Decrement Operators
• The increment and decrement operators are called as unary operators.
• Increment and Decrement Operators are useful operators generally used to minimize the calculation,
i.e. ++x and x++ means x=x+1 or --x and x−−means x=x-1.
• But there is a slight difference between ++ or −− written before or after the operand.
• pre-increment: first add one to the operand and then the result is assigned to the variable on the left.
Ex: ++x
• post-increment: first assigns the value to the variable on the left and then increment the operand. Ex:
x++
• pre-decrement: first substract one to the operand and then the result is assigned to the variable on the
left. Ex: --x
• post-decrement: first assigns the value to the variable on the left and then decrement the operand.
Ex: x--
Example: program to perform Pre-Increment and Pre-Decrement
#include <stdio.h>
void main()
{
int i = 5,j=5;
printf(“++i = %d, --j = %d",++i,--j);
}
Output:
++i = 6, --j = 4
Example 2: program for Post-Increment or Post-Decrement
#include <stdio.h>
void main()
{
int i = 5,j=5;
printf("i++ = %d, j-- = %d\n",i++,j--);
printf(“i = %d, j = %d\n” ,i,j);
}
Output:
i++ = 5, j-- = 5
i = 6, j = 4
5 b) What is ternary operator? Explain.
Ans:
Conditional Operator/ Ternary operator: A ternary operator pair "?:" is available in C to construct
conditional expressions of the form
Syntax: exp1 ? exp2 : exp3;
It work as
if exp1 is true then exp2 else exp3
Example: C program using ternary operator and assignment
#include<stdio.h>
main()
{
int i,j,large;
printf("Enter two numbers ");
scanf("%d%d",&i,&j);
large=(i>j)?i:j;
printf("largest of two is %d",large);
}
Output:
Enter two numbers 25 31
Largest of two is 31
6. a) Explain the different types of data types used in C language.
Ans: DATA TYPES:
To represent different types of data in C program we need different data types. A data type is essential to
identify the storage representation and the type of operations that can be performed on that data. C
supports four different classes of data types namely
• Basic Data types
• Derives data types
• User defined data types
• Pointer data types
BASIC DATA TYPES:
All arithmetic operations such as Addition, subtraction, etc are possible on basic data types.
E.g.: int a,b;
Char c;
The following table shows the Storage size and Range of basic data types:
TYPE LENGTH RANGE
Unsigned char 8 bits 0 to 255
Char 8 bits -128 to 127
Short int 16 bits -32768 to 32767
Unsigned int 32 bits 0 to 4,294,967,295
Int 32 bits -2,147,483,648 to 2,147,483,648
Unsigned long 32 bits 0 to 4,294,967,295
Enum 16 bits -2,147,483,648 to 2,147,483,648
Long 32 bits -2,147,483,648 to 2,147,483,648
Float 32 bits 3.4*10E-38 to 3.4*10E38
Double 64 bits 1.7*10E-308 to 1.7*10E308
Long double 80 bits 3.4*10E-4932 to 1.1*10E4932
DERIVED DATA TYPES:
Derived data types are used in ‘C’ to store a set of data values. Arrays and Structures are examples for
derived data types.
Ex: int a[10];
Char name[20];
USER DEFINED DATATYPES:
C Provides a facility called typedef for creating new data type names defined by the user. For Example ,
the declaration :
typedef int Integer;
makes the name Integer a synonym of int.Now the type Integer can be used in declarations ,casts, etc,
like,
Integer num1,num2;
Which will be treated by the C compiler as the declaration of num1,num2as int variables. “typedef” ia
more useful with structures and pointers.
POINTER DATA TYPES:
Pointer data type is necessary to store the address of a variable.
6 b) Describe type-casting with an example.
Ans:
TYPE CONVERSION:
In an expression that involves two different data types, such as multiplying an integer and a floating
point number to perform these evaluations, one of the types must be converted.
We have two types of conversions
1. Implicit Type Conversion
2. Explicit Type Conversion
IMPLICIT TYPE CONVERSION:
When the types of the two operands in a binary expression are different automatically converts one type
to another .This automatic or internal type conversion is known as implicit type conversion.
Example: A character is internally converted to integer as shown below.
#include <stdio.h>
main() {
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}
Output: Value of sum : 116
EXPLICIT TYPE CONVERSION:
Explicit type conversion uses the unary cast operator, to convert data from one type to another. To cast
data from one type to another, we specify the new type in parentheses before the value we want
converted.
For example, to convert an integer, sum, to a float, we code the expression like (float) sum as shown
below:
#include <stdio.h>
main() {
int sum = 17, count = 5;
float mean;
mean = (float) sum / count;
printf("Value of mean : %f\n", mean );
}
Output: Value of mean: 3.4
7. (a) Differentiate between for loop and while loop
Ans:
The difference between for loop and while loop is that in for loop the number of iterations to be done is
already known and is used to obtain a certain result whereas in while loop the command runs until a
certain condition is reached and the statement is proved to be false.
Comparison Table Between For loop and While loop (in Tabular Form)
Parameter of
For loop While loop
Comparison
The structure of for loop is – Structure of while loop is-
for(initial condition; number of iterations) While(condition)
{ {
Command
//body of the loop statements;
} //body
}
Iterations Iterates for a preset number of times. Iterates till a condition is met.
In the absence of a condition, the loop iterates
In the absence of a condition, while
Condition for an infinite number of times till it reaches
loop shows an error.
break command.
Initialization in for loop is done only once when Initialization is done every time the
Initialization
the program starts. loop is iterated.
Used to obtain the result only when the number Used to satisfy the condition when
Use
of iterations is known. the number of iterations is unknown.
7 (b) Differentiate between ‘break’ and ‘continue’ statements.
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
terminate the moment it is executed. Loop causes the loop to go to the next iteration.
or switch ends abruptly when break is All iterations of the loop are executed
encountered. even if continue is 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
both switch and loop statements. in loops. You will get an error if this
appears in switch statement.
When a break statement is encountered, it When a continue statement is
terminates the block and gets the control out of encountered, it gets the control to the
the switch or loop. next iteration of the 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.
8. Discuss about selection statements with examples.
Ans:
if statement
The if statement checks whether the text expression inside parenthesis () is true or not. If the test
expression is true, statement/s inside the body of if statement is executed but if test is false, statement/s
inside body of if is ignored.
Syntax is,
if (test_expression)
{
Staements to be executed if test expression is true;
}
Flow of if statement
Example: Program to check whether the given number is lessthan 0 or not
#include<stdio..h>
void main()
{
int num;;
printf(“\n enter a number to check : ”);
scanf(“%d”,&num);
if(num<0) /* checking whether number is less than 0 or not. */
{
printf(“\n Number =%d”,num);
}
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
printf(“The if statement in C programing is easy “);
}
Output 1
Enter a number to check.
-2
Number = -2
Explanation: When user enters -2 then, the test expression (num<0) becomes true. Hence, Number = -2
is displayed in the screen.
Output 2
Enter a number to check. 5
The if statement in C
programming is easy.
Explanation: When the user enters 5 then, the test expression (num<0) becomes false. So, the
statement/s inside body of if is skipped and only the statement below it is executed.
if – else statement
The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false.
Syntax is,
if (test expression)
{
statements to be executed if test expression is true;
}
else
{
statements to be executed if test expression is false;
}
Flow chart of if-else statement
Example: Write a C program to check whether a number entered by user is even or odd
#include<stdio.h>
int main()
{
int num;
printf("Enter a number you want to check.\n");
scanf("%d",&num);
if((num%2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return0;
}
Output 1
Enter a number you want to check. 25
25 is odd
Output 2
Enter a number you want to check. 2
2 is even.
Nested if –else statement (if – else if )
The nested if...else statement is used when program requires more than one test expression.
Syntax is
if (test expression1)
{
statement/s to be executed if test expression1 is true;
}
else if(test expression2)
{
statement/s to be executed if test expression1 is false and 2 is true;
}
.
.
.
else
{
statements to be executed if all test expressions are false;
}
How nested if...else works?
The nested if...else statement has more than one test expression. If the first test expression is true, it
executes the code inside the braces{ } just below it. But if the first test expression is false, it checks the
second test expression. If the second test expression is true, it executes the statement/s inside the
braces{ } just below it. This process continues. If all the test expression are false, code/s inside else is
executed and the control of program jumps below the nested if...else
The ANSI standard specifies that 15 levels of nesting may be continued.
Example: Write a C program to relate two integers entered by user using = or > or < sign.
#include<stdio.h>
int main()
{
int numb1, numb2;
printf("Enter two integers to check\n");
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d = %d",numb1,numb2);
else if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d > %d",numb1,numb2);
else
printf("Result: %d > %d",numb2,numb1);
return0;
}
Output 1
Enter two integers to check. 5
3
Result: 5 > 3
Output 2
Enter two integers to check.
-4
-4
Result: -4 = -4
switch Statement
Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. If a programmer has to choose one block of statement among many
alternatives, nested if...else can be used but, this makes programming logic complex. This type of
problem can be handled in C programming using switch statement.
Syntax of switch statement is,
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches constant in
case, the relevant codes are executed and control moves out of the switch statement. If the n doesn't
matches any of the constant in case, then the default codes are executed and control moves out of
switch statement. The break statement at the end of each case cause switch statement to exit. If break
statement is not used, all statements below that case statement are also executed.
Example: Write a program that asks user an arithmetic operator ('+','-','*' or '/') and two
operands and perform the corresponding calculation on the operands.
# include <stdio.h>
int main()
{
char o;
float num1,num2;
printf("Select an operator either + or - or * or / \n");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o)
{
case'+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case'-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case'*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case'/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
}
return0;
}
Output
Enter operator either + or - or * or /
*
Enter two operands: 2.3 4.5
2.3 * 4.5 = 10.3
9. (a) Write a program to print the following series on the screen
1
12
123
1234
12345
Ans:
#include <stdio.h>
int main()
{
int i, j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
return 0;
}
9 (b) Write a C program to convert the given decimal number into binary number.
Ans:
#include <stdio.h>
int main()
{
int a[10], number, i, j;
printf("\n Please Enter the Number You want to Convert : ");
scanf("%d", &number);
for(i = 0; number > 0; i++)
{
a[i] = number % 2;
number = number / 2;
}
printf("\n Binary Number of a Given Number = ");
for(j = i - 1; j >= 0; j--) {
printf(" %d ", a[j]);
}
printf("\n");
return 0;
}
Output:
Please Enter the Number You want to Convert : 25
Binary Number of a Given Number = 1 1 0 0 1
10. Explain the for loop in detail.
Ans:
for loop
For loop is also used for the similar purpose like while & do-while. It has three statements. (i)
initialization statements (ii) condition statements (iii) update statements.
The initialization statement is executed only once at the beginning of the ‘for’ loop. Then the test
expression is checked by the program. If the test expression is false, for loop is terminated. But if test
expression is true then the code/s inside body of for loop is executed and then update expression is
updated. This process repeats until test expression is false. Initial, test and update expressions are
separated by semicolon(;).
Syntax of for loop is,
for(initialization statement; test expression; update statement)
{
code/s to be executed;
}
Example: Write a program to find the sum of first n natural numbers where n is entered by user.
Note: 1,2,3... are called natural numbers.
#include<stdio.h>
int main()
{
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
return0;
}
Output
Enter the value of n. 19
Sum=190
Explanation: In this program, the user is asked to enter the value of n. Suppose you entered 19 then,
count is initialized to 1 at first. Then, the test expression in the for loop,i.e., (count<= n)
becomes true. So, the code in the body of for loop is executed which makes sum to 1. Then, the
expression ++count is executed and again the test expression is checked, which becomes true. Again, the
body of for loop is executed which makes sum to 3 and this process continues. When count is 20, the test
condition becomes false and the for loop is terminated.
11 a) Write a C program to find the sum of first and last digit of a number.
Ans:
#include <stdio.h>
int main()
{
int num, sum=0, firstDigit, lastDigit;
/* Input a number from user */
printf("Enter any number to find sum of first and last digit: ");
scanf("%d", &num);
/* Find last digit to sum */
lastDigit = num % 10;
/* Copy num to first digit */
firstDigit = num;
/* Find the first digit by dividing num by 10 until first digit is left */
while(num >= 10)
{
num = num / 10;
}
firstDigit = num;
/* Find sum of first and last digit*/
sum = firstDigit + lastDigit;
printf("Sum of first and last digit = %d", sum);
return 0;
}
Output:
Enter any number to find sum of first and last digit: 12345
Sum of first and last digit = 6
11 b) Write a C program to print all the prime numbers between 1 to 100
Ans:
#include <stdio.h>
int main()
{
int i, a = 1, count;
while(a <= 100)
{
count = 0;
i = 2;
while(i <= a/2)
{
if(a%i == 0)
{
count++;
break;
}
i++;
}
if(count == 0 && a != 1 )
{
printf(" %d ", a);
}
a++;
}
return 0;
}
Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
12 (a) Write about nested for loop statement with examples.
Ans:
Using a for loop within another for loop is said to be nested for loop. In nested for loop one or more
statements can be included in the body of the loop. In nested for loop, the number of iterations will be
equal to the number of iterations in the outer loop multiplies by the number of iterations in the inner
loop.
Syntax
for (initialize counter; test condition; ++ or --)
{
for (initialize counter; test condition; ++ or --)
{
.// inner for loop
}
.// outer for loop
}
Example: C program to print all the composite numbers from 2 to a certain number entered by
user.
#include<stdio.h>
#include<math.h>
int main()
{
int i,j,n;
printf("Enter a number:");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
for(j=2;j<=(int)pow(i,0.5);j++)
{
if(i%j==0)
{
printf("%d is compositen",i);
break;
}
}
}
return 0;
}
Output
Enter a number:15
4 is composite
6 is composite
8 is composite
9 is composite
10 is composite
12 is composite
14 is composite
15 is composite
12 (b) Differentiate between else-if and switch. Illustrate
Ans:
IF-ELSE SWITCH
The switch statement is used to select among
If statement is used to select among two alternatives
multiple alternatives.
If can have values based on constraints. Switch can have values based on user choice.
If implements Linear search. Switch implements Binary search.
Only int and char data types can be used in
Float, double, char, int and other data types can
switch
be used in if condition.
block.
It is difficult to edit the if-else statement, if the nested It is easy to edit switch cases as, they are
if-else statement is used. recognized easily.
Syntax for if else:
if(expression)
{
// statements;
}
else
{
// statements;
}
Syntax for switch:
switch(expression)
{
case constant 1:
// statements;
break;
case constant 2:
// statements;
break;
case constant n:
// statements;
break;
default:
// statements;
}
13 a) write a c program to find factorial of a given number N by using “while loop” and “do while
loop”
Ans:
Program using while loop:
#include<stdio.h>
#include<stdio.h>
int main()
{
int num =5;
int i=1;
int factorial =1;
while(i <= num){
factorial = factorial * i;
++i;
}
printf("Factorial of %d = %d",num,factorial);
return 0;
}
Output:
Factorial of 5 = 120
Program using do while loop:
#include<stdio.h>
int main()
{
int num =5;
int i=1;
int factorial =1;
do{
factorial = factorial * i;
++i;
}while(i <= num);
printf("Factorial of %d = %d",num, factorial);
return 0;
}
Output:
Factorial of 5 = 120
13 b) Write ‘C’ program to print the Fibonacci sequence.
Ans:
#include <stdio.h>
int main() {
int i, n;
// initialize first and second terms
int t1 = 0, t2 = 1;
// initialize the next term (3rd term)
int nextTerm = t1 + t2;
// get no. of terms from user
printf("Enter the number of terms: ");
scanf("%d", &n);
// print the first two terms t1 and t2
printf("Fibonacci Series: %d, %d, ", t1, t2);
// print 3rd to nth terms
for (i = 3; i <= n; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Output:
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
14 a) Write a program to demonstrate ‘goto’ statement
Ans:
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the control
of the program will jump to the label: and executes the code below it.
Example: C program to demonstrate the working of goto statement.
/* This program calculates the average of numbers entered by user. */
/* If user enters negative number, it ignores that number and calculates the average of number entered
before it.*/
# include <stdio.h>
int main()
{
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump; /* control of the program moves to label jump */
sum=sum+num;
}
jump:
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
Output
Maximum no. of inputs: 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average: 7.07
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced as
much as possible in a program.
14 b) Explain the difference between ‘while’ and ‘do-while’ statements with suitable examples.
Ans:
Basis For
while do-while
Comparison
do{
while ( condition) { .
General Form statements; //body of loop statements; // body of loop.
} .
} while( Condition );
In 'while' loop the controlling In 'do-while' loop the controlling
Controlling
condition appears at the start of the condition appears at the end of the
Condition
loop. loop.
The iterations do not occur if, the The iteration occurs at least once even
Iterations condition at the first iteration, if the condition is false at the first
appears false. iteration.
Key Differences Between while and do-while Loop
1. The while loop checks the condition at the starting of the loop and if the condition is satisfied
statement inside the loop, is executed. In do-while loop, the condition is checked after the
execution of all statements in the body of the loop.
2. If the condition in a while loop is false not a single statement inside the loop is executed, and if
the condition in ‘do-while’ loop is false then also the body of the loop is executed at least once
then the condition is tested.
While loop Do..While Loop
Syntax:,while(condition),{ Syntax:,do,{
} }while(condition);
Semicolon (;) is not used Semicolon (;) is used
Condition is checked first. Condition is checked later.
Since condition is checked first, statements may or Since condition is checked later, the body statements
may not get executed. will execute at least once.
The main feature of the while loop is,its an entry The main feature of the do while loops is it is an exit
controlled loop. controlled loop
This example prints all even numbers from 1 to
50.
15. Describe the various control statements available in C.
Ans: Control statements in C
Note: Explain each statement with syntax, flowchart and example program