m
Shrichakradhar.com 1
MCS-011 : PROBLEM SOLVING ANDPROGRAMMING
Guess Paper-I
706 .co
Q. Critically analyze the switch statement with example.
Ans. switch statement
Ans. 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.
894 har
Syntax
Example:
#include <stdio.h>
0
int main () {
/* local variable definition */
char grade = 'B';
995 rad
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
k
printf("Well done\n" );
break;
case 'D' :
ha
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
ric
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
Sh
return 0;
}
https://www.shrichakradhar.com
m
2 Problem Solvining and Programming (MCS-011)
Q. Write a program read a file and count the number of lines in the file, assuming
that a line can contain at most 80 characters.
706 .co
Ans. #include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fp;
894 har
int cnt=0;
char str[80];
/* open a file in read mode */
0
if ((fp=fopen("lines.dat","r"))== NULL)
{ printf("File does not exist\n");
exit(0);
995 rad
}
/* read the file till end of file is encountered */
while(!(feof(fp)))
{ fgets(str,80,fp); /*reads at most 80 characters in str */
cnt++; /* increment the counter after reading a line */
}
}/* print the number of lines */
k
printf(“The number of lines in the file is :%d\n”,cnt);
fclose(fp);
}
ha
OUTPUT
Let us assume that the contents of the file “lines.dat” are as follows:
This is C programming.
I love C programming.
ric
Q. Write a macro to demonstrate #define, #if, #else preprocessor commands.
Ans.#include <stdio.h>
#define CHOICE 100
int my_int = 0;
Sh
#undef CHOICE
#ifdef CHOICE
void set_my_int()
{
https://www.shrichakradhar.com
m
Shrichakradhar.com 3
my_int = 35;
}
#else
706 .co
void set_my_int()
{
my_int = 27;
}
894 har
#endif
main ()
{
0
set_my_int();
printf("%d\n", my_int);
}
995 rad
OUTPUT
27
Q. Write a macro to display the string COBOL in the following fashion
C
k
CO
COB
COBO
ha
COBOL
COBOL
COBO
COB
ric
CO
C
Ans. # include<stdio.h>
# define LOOP for(x=0; x<5; x++) \
Sh
{ y=x+1; \
printf(“%-5.*s\n”, y, string); } \
for(x=4; x>=0; x--) \
{ y=x+1; \
https://www.shrichakradhar.com
m
4 Problem Solvining and Programming (MCS-011)
printf(“%-5.*s \n”, y, string); }
main()
{
706 .co
int x, y;
static char string[ ] = “COBOL”;
printf(“\n”);
LOOP;
894 har
}
When the above program is executed the reference to macro (loop) is replaced by the
set of statements contained within the macro definition.
0
Q . Define a macro to find maximum of 3 or 2 numbers using #ifdef , #else
Ans.#include<stdio.h>
995 rad
#define TWO
main()
{
int a, b, c;
clrscr();
#ifdef TWO
{
k
printf("\n Enter two numbers: \n");
scanf("%d %d", &a,&b);
ha
if(a>b)
printf("\n Maximum of two numbers is %d", a);
else
printf("\n Maximum is of two numbers is %d", b);
}
ric
#endif
} /* end of main*/
OUTPUT
Enter two numbers:
33
Sh
22
Q. Write a program to find out square and cube of any given number using
macros.
Ans.# include<stdio.h>
https://www.shrichakradhar.com
m
Shrichakradhar.com 5
# define sqr(x) (x * x)
# define cub(x) (sqr(x) * x)
main()
706 .co
{
int num;
printf(“Enter a number: ”);
scanf(“%d”, &num);
printf(“ \n Square of the number is %d”, sqr(num));
printf(“ \n Cube of the number is %d\n”, cub(num));
894 har
}
OUTPUT
Enter a number: 5
0
Square of the number is 25
Cube of the number is 125
995 rad
k
ha
ric
Sh
https://www.shrichakradhar.com
m
6 Problem Solvining and Programming (MCS-011)
MCS-011 : PROBLEM SOLVING ANDPROGRAMMING
Guess Paper-II
706 .co
Q. Write a program to search an element in a given list of elements using Linear
Search.
Ans. /* Linear Search.*/
# include<stdio.h>
894 har
# defineSIZE 05
main()
{
0
int i = 0;
int j;
int num_list[SIZE]; /* array declaration */
995 rad
/* enter elements in the following loop */
printf(“Enter any 5 numbers: \n”);
for(i = 0;i<SIZE;i ++)
{
printf(“Element no.=%d Value of the element=”,i+1);
scanf(“%d”,&num_list[i]);
k
}
printf (“Enter the element to be searched:”);
scanf (“%d”,&j);
ha
/* search using linear search */
for(i=0;i<SIZE;i++)
{
if(j == num_list[i])
ric
{
printf(“The number exists in the list at position: %d\n”,i+1);
break;
}
}
Sh
}
OUTPUT
Enter any 5 numbers:
Element no.=1 Value of the element=23
https://www.shrichakradhar.com
m
Shrichakradhar.com 7
Element no.=2 Value of the element=43
Element no.=3 Value of the element=12
Element no.=4 Value of the element=8
706 .co
Element no.=5 Value of the element=5
Enter the element to be searched: 8
The number exists in the list at position: 4
Q. Write a program to display the average marks of each student, given the marks
894 har
in 2 subjects for 3 students.
Ans. Write a program to display the average marks of each student, given the marks
in 2
0
subjects for 3 students.
/* Program to display the average marks of 3 students */
# include < stdio.h >
995 rad
# defineSIZE 3
main()
{
int i = 0;
float stud_marks1[SIZE]; /* subject 1array declaration */
float stud_marks2[SIZE]; /*subject 2 array declaration */
k
float total_marks[SIZE];
float avg[SIZE];
printf(“\n Enter the marks in subject-1 out of 50 marks: \n”);
ha
for( i = 0;i<SIZE;i++)
{
printf(“Student no. =%d”,i+1);
printf(“ Enter the marks= “);
ric
scanf(“%f”,&stud_marks1[i]);
}
printf(“\n Enter the marks in subject-2 out of 50 marks \n”);
for(i=0;i<SIZE;i++)
{
Sh
printf(“Student no. =%d”,i+1);
printf(“ Please enter the marks= “);
scanf(“%f”,&stud_marks2[i]);
}
https://www.shrichakradhar.com
m
8 Problem Solvining and Programming (MCS-011)
for(i=0;i<SIZE;i++)
{
total_marks[i]=stud_marks1[i]+ stud_marks2[i];
706 .co
avg[i]=total_marks[i]/2;
printf(“Student no.=%d, Average= %f\n”,i+1, avg[i]);
}
}
OUTPUT
894 har
Enter the marks in subject-1out of 50 marks:
Student no. = 1 Enter the marks= 23
Student no. = 2 Enter the marks= 35
0
Student no. = 3 Enter the marks= 42
Enter the marks in subject-2 out of 50 marks:
Student no. = 1 Enter the marks= 31
995 rad
Student no. = 2 Enter the marks= 35
Student no. = 3 Enter the marks= 40
Student no. = 1 Average= 27.000000
Student no. = 2 Average= 35.000000
Student no. = 3 Average= 41.000000
k
Q. Critically examine the While Loop.
Ans. When in a program a single statement or a certain group of statements are to be
executed repeatedly depending upon certain test condition, then while statement is
ha
used.
The syntax is as follows:
while (test condition)
{
ric
body_of_the_loop;
}
Here, test condition is an expression that controls how long the loop keeps running.
Body of the loop is a statement or group of statements enclosed in braces and are
repeatedly executed till the value of test condition evaluates to true. As soon as the
Sh
condition evaluates to false, the control jumps to the first statement following the
while statement. If condition initially itself is false, the body of the loop will never be
executed. While loop is sometimes called as entry-control loop, as it controls the
https://www.shrichakradhar.com
m
Shrichakradhar.com 9
execution of the body of the loop depending upon the value of the test condition.
This is shown in the figure 5.5 given below:
706 .co
894 har
0
995 rad
Let us consider a program to illustrate while loop,
k
Example
/* Program to calculate factorial of given number */
ha
#include <stdio.h>
#include <math.h>
#include <stdio.h>
main( )
{
ric
int x;
long int fact = 1;
printf(“Enter any number to find factorial:\n”); /*read the number*/
scanf(“%d”,&x);
while (x > 0)
{
Sh
fact = fact * x; /* factorial calculation*/
x=x-1;
}
printf(“Factorial is %ld”,fact);
https://www.shrichakradhar.com
m
10 Problem Solvining and Programming (MCS-011)
Q. Describe Decision control statement.
Ans. In a C program, a decision causes a one-time jump to a different part of the
706 .co
program, depending on the value of an expression. Decisions in C can be made in
several ways. The most important is with the if...else statement, which chooses
between two alternatives. This statement can be used without the else, as a simple if
statement. Another decision control statement, switch, creates branches for multiple
alternative sections of code, depending on the value of a single variable.
894 har
The if Statement: It is used to execute an instruction or sequence/block of
instructions only if a condition is fulfilled. In if statements, expression is evaluated
first and then, depending on whether the value of the expression (relation or
0
condition) is “true” or “false”, it transfers the control to a particular statement or a
group of statements.
Different forms of implementation if-statement are:
995 rad
• Simple if statement
• If-else statement
• Nested if-else statement
• Else if statement
Simple if statement: It is used to execute an instruction or block of instructions only
if a condition is fulfilled.
k
The syntax is as follows:
if (condition)
ha
statement;
where condition is the expression that is to be evaluated. If this condition is true,
statement is executed. If it is false, statement is ignored (not executed) and the
program continues on the next instruction after the conditional statement.
If we want more than one statement to be executed, then we can specify a block of
ric
statements within the curly bracets { }. The syntax is as follows:
if (condition)
{
block of statements;
}
Sh
Example: Write a program to calculate the net salary of an employee, if a tax of 15%
is levied on his gross-salary if it exceeds Rs. 10,000/- per month.
/*Program to calculate the net salary of an employee */
#include <stdio.h>
https://www.shrichakradhar.com
m
Shrichakradhar.com 11
main( )
{
float gross_salary, net_salary;
706 .co
printf(“Enter gross salary of an employee\n”);
scanf(“%f ”,&gross_salary );
if (gross_salary <10000)
net_salary= gross_salary;
if (gross_salary >= 10000)
894 har
net_salary = gross_salary- 0.15*gross_salary;
printf(“\nNet salary is Rs.%.2f\n”, net_salary);
}
0
If … else statement: If…else statement is used when a different sequence of
instructions is to be executed depending on the logical value (True / False) of the
condition evaluated.
995 rad
Its form used in conjunction with if and the syntax is as follows:
if (condition)
Statement _1;
else
Statement_ 2;
statement_3;
k
Or
if (condition)
ha
{
Statements_1_Block;
}
else
{
ric
Statements_2_Block;
}
Statements _3_Block;
If the condition is true, then the sequence of statements (Statements_1_Block)
Sh
executes; otherwise the Statements_2_Block following the else part of if-else
statement will get executed. In both the cases, the control is then transferred to
Statements_3 to follow sequential execution of the program. This is shown in figure
5.2 given below:
https://www.shrichakradhar.com
m
12 Problem Solvining and Programming (MCS-011)
706 .co
894 har
0
995 rad
k
ha
/* Program to print whether the given number is even or odd*/
#include <stdio.h>
ric
main ( )
{
int x;
printf(“Enter a number:\n”);
Sh
scanf("%d",&x);
if (x % 2 == 0)
printf(“\nGiven number is even\n”);
else
https://www.shrichakradhar.com
m
Shrichakradhar.com 13
printf(“\nGiven number is odd\n”);
}
Nested if…else statement:In nested if… else statement, an entire if…else construct is
706 .co
written within either the body of the if statement or the body of an else statement.
The syntax is as follows:
if (condition_1)
{
894 har
if (condition_2)
{
Statements_1_Block;
0
}
else
{
995 rad
Statements_2_Block;
}
}
else
{
k
Statements_3_Block;
}
Statement_4_Block;
ha
Here, condition_1 is evaluated. If it is false then Statements_3_Block is executed and
is followed by the execution of Statements_4_Block, otherwise if condition_1 is true,
then condition_2 is evaluated. Statements_1_Block is executed when condition_2 is
true otherwise Statements_2_Block is executed and then the control is transferred to
ric
Statements_4_Block.
Q9. What is relational operator?
Ans.Executable C statements either perform actions (such as calculations or input or
output of data) or make decision. Using relational operators we can compare two
Sh
variables in the program. The C relational operators are summarized below, with
their meanings. Pay particular attention to the equality operator; it consists of two
equal signs, not just one. This section introduces a simple version of C’s if control
structure that allows a program to make a decision based on the result of some
https://www.shrichakradhar.com
m
14 Problem Solvining and Programming (MCS-011)
condition. If the condition is true then the statement in the body of if statement is
executed else if the condition is false, the statement is not executed. Whether the
body statement is executed or not, after the if structure completes, execution
706 .co
proceeds with the next statement after the if structure. Conditions in the if structure
are formed with the relational operators which are summarized in the Table.
894 har
0
Relational operators usually appear in statements which are inquiring about the
truth of some particular relationship between variables. Normally, the relational
operators in C are the operators in the expressions that appear between the
995 rad
parentheses. For example,
(i) if (thisNum < minimumSoFar) minimumSoFar = thisNum
(ii) if (job == Teacher) salary == minimumWage
(iii) if (numberOfLegs != 8) thisBug = insect
(iv) if (degreeOfPolynomial < 2) polynomial = linear
/*Program to find relationship between two numbers*/
#include <stdio.h>
k
main ( )
{
ha
int a, b;
printf ( “Please enter two integers: ”);
scanf (“%d%d”, &a, &b);
if (a <= b)
printf (“ %d <= %d\n”,a,b);
ric
else
printf (“%d > %d\n”,a,b);
}
Sh
https://www.shrichakradhar.com
m
Shrichakradhar.com 15
MCS-011 : PROBLEM SOLVING ANDPROGRAMMING
Guess Paper-III
706 .co
Q. Describe variables.
Ans. Variable is an identifier whose value changes from time to time during
execution. It is a named data storage location in your computer’s memory. By using
a variable’s name in your program, you are, in effect, referring to the data stored
there. A variable represents a single data item i.e. a numeric quantity or a character
894 har
constant or a string constant. Note that a value must be assigned to the variables at
some point of time in the program which is termed as assignment statement. The
variable can then be accessed later in the program. If the variable is accessed before it
0
is assigned a value, it may give garbage value. The data type of a variable doesn’t
change whereas the value assigned to can change. All variables have three essential
attributes:
995 rad
• The name
• The value
• The memory, where the value is stored.
For example, in the following C program a, b, c, d are the variables but variable e is
not declared and is used before declaration. After compiling the source code and
look what gives?
main( )
k
{
int a, b, c;
char d;
ha
a = 3;
b = 5;
c = a + b;
d = ‘a’;
e=d;
ric
……….
……….
}
After compiling the code, this will generate the message that variable e not defined.
Sh
Q. Explain identifiers and keywords.
Ans. Identifiers are defined according to the following rules:
1. It consists of letters and digits.
2. First character must be an alphabet or underscore.
https://www.shrichakradhar.com
m
16 Problem Solvining and Programming (MCS-011)
3. Both upper and lower cases are allowed. Same text of different case is not
equivalent, for example: TEXT is not same as text.
4. Except the special character underscore ( _ ), no other special symbols can be used.
706 .co
For example, some valid identifiers are shown below:
X
X123
_XI
temp
tax_rate
894 har
For example, some invalid identifiers are shown below:
123 First character to be alphabet.
“X.” Not allowed.
0
order-no Hyphen allowed.
error flag Blankspace allowed.
Keywords
995 rad
Keywords are reserved words which have standard, predefined meaning in C. They
cannot be used as program-defined identifiers.
The lists of C keywords are as follows:
k
ha
Q. Write a C program to compute the average of three numbers
Ans. /* Program to compute average of three numbers *?
#include<stdio.h>
main( )
ric
{
int a,b,c,sum,avg;
a=10;
b=5;
c=20;
Sh
sum = a+b+c;
avg = sum / 3;
printf(“The average is %d\n”, avg);
}
https://www.shrichakradhar.com
m
Shrichakradhar.com 17
OUTPUT
The average is 8.
Q5. Write a program to divide a sum of two numbers by their difference
706 .co
Ans. /* Program to divide a sum of two numbers by their difference*/
#include <stdio.h>
main( )
{
int a,b;
float c;
894 har
a=10;
b=10;
c = (a+b) / (a-b);
0
printf(“The value of the result is %f\n”,c);
}
995 rad
Q. Develop an algorithm, flowchart and program to add two numbers.
Ans. Algorithm
1. Start
2. Input the two numbers a and b
3. Calculate the sum as a+b
4. Store the result in sum
5. Display the result
k
6. Stop.
ha
ric
Sh
https://www.shrichakradhar.com
m
18 Problem Solvining and Programming (MCS-011)
Program
#include <stdio.h>
main()
706 .co
{
int a,b,sum; /* variables declaration*/
printf(“\n Enter the values for a and b: \n”);
scanf(“%d, %d”, &a, &b);
sum=a+b;
printf("\nThe sum is %d",sum); /*output statement*/
894 har
}
OUTPUT
Enter the values of a and b:
0
23
The sum is 5
995 rad
Q. What is a Program and a Programming Language?
Ans. In practice it is necessary to express an algorithm using a programming
language. A procedure expressed in a programming language is known as a
computer program.
Computer programming languages are developed with the primary objective of
facilitating a large number of people to use computers without the need for them to
know in detail the internal structure of the computer. Languages are designed to be
k
machine-independent. Most of the programming languages ideally designed, to
execute a program on any computer regardless of who manufactured it or what
model it is. Programming languages can be divided into two categories:
ha
(i) Low Level Languages or Machine Oriented Languages: The language whose
design is governed by the circuitry and the structure of the machine is known
as the Machine language. This language is difficult to learn and use. It is
specific to a given computer and is different for different computers i.e. these
languages are machine-dependent. These languages have been designed to
ric
give a better machine efficiency, i.e. faster program execution. Such languages
are also known as Low Level Languages. Another type of Low-Level
Language is the Assembly Language. We will code the assembly language
program in the form of mnemonics. Every machine provides a different set of
mnemonics to be used for that machine only depending upon the processor
Sh
that the machine is using.
(ii) High Level Languages or Problem Oriented Languages: These languages are
particularly oriented towards describing the procedures for solving the
problem in a concise, precise and unambiguous manner. Every high level
language follows a precise set of rules. They are developed to allow
https://www.shrichakradhar.com
m
Shrichakradhar.com 19
application programs to be run on a variety of computers. These languages
are machineindependent. Languages falling in this category are FORTRAN,
BASIC, PASCAL etc. They are easy to learn and programs may be written in
706 .co
these languages with much less effort. However, the computer cannot
understand them and they need to be translated into machine language with
the help of other programs known as Compilers or Translators.
Q. Using structures, write a C program to calculate the Gross salary and Net
salary, if Basic pay, Grade pay, TA and DA and other allowances and deductions
894 har
are given as inputs.
Ans. #include
#include
0
#include
/* structure to store employee salary details */
struct employee {
995 rad
int empId;
char name[32];
int basic, hra, da, ma;
int pf, insurance;
float gross, net;
};
k
/* prints payslip for the requested employee */
void printSalary(struct employee e1) {
printf(“Salary Slip of %s:\n”, e1.name);
ha
printf(“Employee ID: %d\n”, e1.empId);
printf(“Basic Salary: %d\n”, e1.basic);
printf(“House Rent Allowance: %d\n”, e1.hra);
printf(“Dearness Allowance: %d\n”, e1.da);
printf(“Medical Allowance: %d\n”, e1.ma);
ric
printf(“Gross Salary: %.2f Rupees\n”, e1.gross);
printf(“\nDeductions: \n”);
printf(“Provident fund: %d\n”, e1.pf);
printf(“Insurance: %d\n”, e1.insurance);
Sh
printf(“\nNet Salary: %.2f Rupees\n\n”, e1.net);
return;
}
int main() {
https://www.shrichakradhar.com
m
20 Problem Solvining and Programming (MCS-011)
int i, ch, num, flag, empID;
struct employee *e1;
/* get the number of employees from the user */
706 .co
printf(“Enter the number of employees:”);
scanf(“%d”, &num);
/* dynamically allocate memory to store employee salary details */
e1 = (struct employee *)malloc(sizeof(struct employee) * num);
/* get the employee salary details from the customer */
printf(“Enter your input for every employee:\n”);
894 har
for (i = 0; i < num; i++) {
printf(“Employee ID:”);
scanf(“%d”, &(e1[i].empId));
0
getchar();
printf(“Employee Name:”);
fgets(e1[i].name, 32, stdin);
995 rad
e1[i].name[strlen(e1[i].name) – 1] = ‘\0’;
printf(“Basic Salary, HRA:”);
scanf(“%d%d”, &(e1[i].basic), &(e1[i].hra));
printf(“DA, Medical Allowance:”);
scanf(“%d%d”, &(e1[i].da), &(e1[i].ma));
printf(“PF and Insurance:”);
scanf(“%d%d”, &(e1[i].pf), &(e1[i].insurance));
k
printf(“\n”);
}
/* gross and net salary calculation */
ha
for (i = 0; i < num; i++) {
e1[i].gross = e1[i].basic +
(e1[i].hra * e1[i].basic) / 100 +
(e1[i].da * e1[i].basic) / 100 +
(e1[i].ma * e1[i].basic) / 100;
ric
e1[i].net = e1[i].gross – (e1[i].pf + e1[i].insurance);
}
/* printing payslip for the given employee ID */
while (1) {
printf(“Enter employee ID to get payslip:”);
Sh
scanf(“%d”, &empID);
flag = 0;
for (i = 0; i < num; i++) {
if (empID == e1[i].empId) {
printSalary(e1[i]);
https://www.shrichakradhar.com
m
Shrichakradhar.com 21
flag = 1;
}
}
706 .co
if (!flag) {
printf(“No Record Found!!\n”);
}
printf(“Do You Want To Continue(1/0):”);
scanf(“%d”, &ch);
if (!ch) {
894 har
break;
}
}
0
return 0;
}
/**
995 rad
* C program to calculate gross salary of an employee
*/
#include <stdio.h>
int main()
{
float basic, gross, da, hra;
/* Input basic salary of employee */
k
printf("Enter basic salary of an employee: ");
scanf("%f", &basic);
/* Calculate D.A and H.R.A according to specified conditions */
ha
if(basic <= 10000)
{
da = basic * 0.8;
hra = basic * 0.2;
}
ric
else if(basic <= 20000)
{
da = basic * 0.9;
hra = basic * 0.25;
}
Sh
else
{
da = basic * 0.95;
hra = basic * 0.3;
}
https://www.shrichakradhar.com
m
22 Problem Solvining and Programming (MCS-011)
/* Calculate gross salary */
gross = basic + hra + da;
printf("GROSS SALARY OF EMPLOYEE = %.2f", gross);
706 .co
return 0;
}
(b) Explain the following with the help of a suitable example for each:
(i) if statement
Ans. The syntax of the if statement in C programming is:
894 har
if (test expression)
{
// statements to be executed if the test expression is true
0
}
Example:
// Program to display a number if it is negative
995 rad
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
k
// true if number is less than 0
if (number < 0) {
ha
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
ric
return 0;
}
(ii) nested if statement
Ans. A nested if in C is an if statement that is the target of another if statement.
Nested if statements means an if statement inside another if statement. Yes, both C
Sh
and C++ allows us to nested if statements within if statements, i.e, we can place an if
statement inside another if statement.
Syntax:
if (condition1)
https://www.shrichakradhar.com
m
Shrichakradhar.com 23
{
// Executes when condition1 is true
if (condition2)
706 .co
{
// Executes when condition2 is true
}
}
Example:
// C program to illustrate nested-if statement
894 har
#include <stdio.h>
int main() {
int i = 10;
0
if (i == 10)
{
995 rad
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
// Nested - if statement
// Will only be executed if statement above
// is true
k
if (i < 12)
printf("i is smaller than 12 too\n");
else
ha
printf("i is greater than 15");
}
return 0;
}
ric
(iii) switch statement
Ans. 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.
Syntax
Sh
The syntax for a switch statement in C programming language is as follows −
switch(expression) {
case constant-expression:
statement(s);
break; /* optional */
https://www.shrichakradhar.com
m
24 Problem Solvining and Programming (MCS-011)
case constant-expression:
statement(s);
break; /* optional */
706 .co
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
Example:
#include <stdio.h>
894 har
int main () {
/* local variable definition */
char grade = 'B';
0
switch(grade) {
case 'A' :
995 rad
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
k
printf("You passed\n" );
break;
case 'F' :
ha
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
ric
printf("Your grade is %c\n", grade );
return 0;
}
Sh
(iv) for loop
Ans. The syntax of the for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
https://www.shrichakradhar.com
m
Shrichakradhar.com 25
}
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression is evaluated to false,
706 .co
the for loop is terminated.
• However, if the test expression is evaluated to true, statements inside the body of
for loop are executed, and the update expression is updated.
• Again the test expression is evaluated.
• This process goes on until the test expression is false. When the test expression is
false, the loop terminates.
894 har
Example:
// Print numbers from 1 to 10
#include <stdio.h>
0
int main() {
int i;
995 rad
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
k
ha
ric
Sh
https://www.shrichakradhar.com