Sri Manakula Vinayagar Engineering College Unit - 2: U23CSTC01 - Programming in C
Sri Manakula Vinayagar Engineering College Unit - 2: U23CSTC01 - Programming in C
Unit II
1
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
(1) C Language:
C is a popular general purpose programming language. We can write the codes for operating
system, application programs and assembly language programs in C language
(2) PASCAL:
Pascal is an influential imperative and procedural programming language, designed in 1968–
1969 and published in 1970 by Niklaus Wirth as a small and efficient language intended to
encourage good programming practices using structured programming and data structuring.
2
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
{
----
----
}
Logical Operators
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).
These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).
9. What is expression?
An expression represents a combination of variables, constants, and operators arranged as per
the syntax of the language.
Expressions are evaluated using an assignment statement of the form
3
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
variable = expression;
Example : 3.14 * r * r
s * (s - a) * (s - b) * (s - c)
11. What is the difference between the two operators = and ==? (APRIL 2010)
The Assignment Operator evaluates an expression on the right of the expression and
substitutes it to the value or variable on the left of the expression. The general form is
Syntax: identifier = expression
Eg: x = a + b;
Equality operator ( == ) is used together with condition. The value of the expression is one or
zero. If the expression is true the result is one, if false result is zero.
Increment Operators
It is used to increase the value of the Operand by 1. There are two types of Increment Operators
in C Language. They are pre Increment operator and post Increment operator.
Eg: ++g -> pre increment
g++ -> post increment
Decrement Operators
It is used to decrease the value of the Operand by 1. There are two types of Decrement Operators
in C Language. They are pre decrement operator and post decrement operator.
Eg: --g ----> pre decrement
g-- ----> post Decrement
Syntax :
(type-name) expression;
4
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
18. What is identifier? Give any two examples for an identifier. ( JAN 2009)
Or
What is a Variable ? illustrate with an example ( NOV/DEC 2014)
Identifiers are names given to various program elements such as variables, functions and
arrays etc.
Eg: STDNAME, sub , TOT_MARKS.
22. What is operator? What are the different types of operators in C? (Jan-2014)
An operator is a symbol that specifies an operations to the performed on operands
operators are used in programs to manipulate data and variables.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and decrement operators
Conditional operators
Bitwise operators
Special operators
5
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
It is used to manipulate the data at bit level .It operates only integers
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One’s complement
Increment ( ++ )
Decrement ( -- )
These operators are generally known as unary operators.
Operator Meaning
++a Pre increment
--a Pre decrement
a++ Post increment
a-- Post decrement
6
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Syntax :
scanf( control string” , &var1, &var2,….&varn) ;
E.g: int n;
scanf(“%d”,&n);
34. Give a note about printf() function?
Output data can be displayed from the computer using standard output ‘C’ library function
called printf( ). This function is used to display any combinations of data.
printf( ) function is mainly used to display information from the standard output device
Monitor.
Syntax:
printf( “control string “ , &var1,&var2,…&varn);
E.g:
int n;
printf(“%d”,&n);
7
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
38. List the Various input and output statements in C ( APR/MAY 2015)
Scanf() Printf()
It is standard input ‘C’ library function. It is standard output’C’ library function.
It is a function used to read information It is a function used to display the
from the keyboard. information through monitor.
Scanf() function starts with string Printf() function starts with string
arguments and may contains additional arguments and may contains additional
arguments. arguments
E.g: int n ; E.g: int n ;
Scanf(“%d”,&n); printf(“Result is……%d”,&n);
41. Difference between high level language and low level language ?
Low Level High level
It is representing in 0’s and 1’s at bit It is represent in terms of normal
level. English.
Programmers can carry out operations at Programmers are design in such a way
bit level for better efficiency.
8
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
46. Write the limitations of using getchar() and scanf() functions for reading strings.
[Jan-2009 ]
getchar(): It is written in standard I/O library. It reads a single character only from a
standard input device. This function is not use for reading strings.
scanf(): It is use for reading single string at a time. When there is a blank was typed, the
scanf() assumes that it is an end.
47. What is compilation Process?(Nov/Dec 2015)
Compilation translates the source program into assembly instructions, which are then
converted to machine instructions. Finally, the linking process establishes a connection to the
operating system for primitive
The modulo operation finds the remainder after division of one number by another
(sometimes called modulus).
Example
15%2=1;
9
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
A variable is the reference of the memory location. A variable may change in value at the
time of program execution. Depending on conditions or on information passed to the program.
Example
int m1,m2,tot;
float avg;
The ability of some compilers to automatically insert type conversion functions where an
expression of one type is used in a context where another type is expected.
Syntax :
enum identifier { value 1,value 2, …value n } ;
enumday w_st, w_end;
w_st = mon ;
w_ end = sun;
10
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
The identifier follows with keyword enum is used to declare the variable.
Label ;
…………
…………
11
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Goto label;
Part-B
1. PROGRAM
required to perform the instructions, and the process of defining those instructions and
data.
CHARACTERISTICS OF A PROGRAM
Accuracy of calculations: Any calculation made in the program should be correct and
accurate.
Clarity: It refers to the overall readability of the program which helps the user to
understand the underlying program logic easily without much difficulty.
Modularity: When developing any program, the task is sub divided into several modules
or subtasks. These modules are developed independently (i.e.) each task does not depend
on the other task.
Portability: Portability is defined as the ability to run the application program on different
platforms.
Flexibility: Any program written should be flexible (i.e.) the program should be developed
in such a way that it can handle the most of the changes without rewriting the entire
program.
12
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Efficiency: Any program needs certain memory and processing time to process the data.
This memory and processing unit should be of least amount. This is the efficiency of the
program.
Generality: The program should be in general. If a program is developed for a specific
task then it can be used for all the similar tasks in the same domain.
Documentation: any application program developed should be well documented such that
even in the absence of the developer and the author, the programmers could be able to
understand the concept behind it.
2. Program Development Life Cycle [Univ. Ques.May-2016,Jan-2016, May 2015, Jan 2015, Jan
2014 ]
Problem Definition
Problem Analysis
Algorithm Development
Coding & Documentation
Testing & Debugging
Maintenance
1. Problem Definition
13
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
In this phase, we define the problem statement and we decide the boundaries of the problem. In
this phase we need to understand the problem statement, what is our requirment, what should be
the output of the problem solution. These are defined in this first phase of the program
development life cycle.
2. Problem Analysis
In phase 2, we determine the requirements like variables, functions, etc. to solve the problem.
That means we gather the required resources to solve the problem defined in the problem
definition phase. We also determine the bounds of the solution.
3. Algorithm Development
During this phase, we develop a step by step procedure to solve the problem using the
specification given in the previous phase. This phase is very important for program development.
That means we write the solution in step by step statements.
This phase uses a programming language to write or implement actual programming instructions
for the steps defined in the previous phase. In this phase, we construct actual program. That
means we write the program to solve the given problem using programming languages like C,
C++, Java etc.,
During this phase, we check whether the code written in previous step is solving the specified
problem or not. That means we test the program whether it is solving the problem for various
input data values or not. We also test that whether it is providing the desired output or not.
6. Maintenance
During this phase, the program is actively used by the users. If any enhancements found in this
phase, all the phases are to be repeated again to make the enhancements. That means in this
phase, the solution (program) is used by the end user. If the user encounters any problem or
wants any enhancement,then we need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.
3) INTRODUCTION TO C
C is a general-purpose high level language that was originally developed by Dennis
Ritchie at AT & T’s Bell Laboratories in 1972. Many of the important ideas of C stem from the
language BCPL(Basic Combined Programming Language), developed by Martin Richards.
STRUCTURE OF A C PROGRAM
Every C program contains a no. of building blocks. These building blocks should be written in a
correct order and procedure, to execute without any errors. The structure of C is given below.
DOCUMENTATION SECTION
PREPROCESSOR SECTION
main()
{
DECLARATION PART
EXECUTEABLE PART
}
SUB PROGRAM SECTION
{
BODY OF THE SUB
PROGRAM
15
}
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
i) Documentation Section
The general comments are included in this section.
The comments are not a part of executable programs.
The comments are placed between delimiters (/* and */).
Example:
/* Factorial of a given number */
Example:
#define PI 3.14
#define TRUE 1
#define FALSE 0
v) main() function
Each and every C program should have only one main() function.
Without main() function, the program cannot be executed.
The main function should be written in lowercase only.
It should not be terminated with semicolon.
16
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Example Program
void main()
{
float r; /*declaration part*/
Execution is the process of running the program, to execute a ‘c’ program, we need to
follow the steps given below.
1. Creating the program
2. Compiling the program
3. Linking the program with system library.
4. Executing the program.
17
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
C CHARACTER SET
Alphabets digits special Char. White space Character spaces Escape sequence
ESCAPE
CHARACTER RESULT
SEQUENCE
18
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
C TOKENS
C-Tokens otherwise known as ‘lexical elements’
The smallest individual units of a C program are known as tokens.
In C program, tokens are categorized into six, they are given below.
C Tokens
i) Keywords
Keywords are reserved words whose meaning cannot be changed. They are used to
construct the program. They are written in lower case. There are 32 keywords are available.
ii) Identifiers
Example
iii) Constants (7. Write about Constants and its types with example.)
(AU-APR/MAY 2015
The items whose values cannot be changed during the execution of program are called
constants. ’C’ constants can be classified as follows.
19
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
‘C’ constants
1. Integer constants
2. Real or floating-point constants
1. Integer constants.
An integer constant refers to a sequence of digits without a decimal point.
2. Real Constant
A Real constant is made up of a sequence of numeric digits with presence of a decimal
point.
Rules for defining real constants
It must have at least one digit.
It must have a decimal point which may be positive or negative.
If it is negative, the sign is must or if it is positive, sign is not necessary.
Use of blank space and comma is not allowed between real constants.
Example: distance =126.0; Height = 5.6;
b) Character Constant
There are two types, they are given below.
i) Single Character constants
ii) String constants
Variable declaration:
Syntax:
datatype v1,v2,v3,….,vn;
Description:
data_type - It is the type of data.
V1, v2, v3 ,…, vn - list of variables.
Example 1:
int regno;
float cgpa;
char name[10];
Example 2:
Declaration of multiple variables of the same data types can be done in one statement.
int mark1;
int mark2;
int mark3;
int mark4;
21
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Initializing variables:
Initialization of variables can be done using the assignment operator(==).
Syntax:
Variable = constant;
Or
Datatype variable = constant;
Example:
A=5;
B=8;
int i =23;
float s=3.14;
Scope of variables
Scope of a variable implies the availability of variables within the program.
Two types:
Local variables
Global variables
Example:
func()
{
int i=10; /* Local definition */
i++; /* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}
Example:
int i=4; /* Global definition */
main()
{
i++; /* Global variable */
func();
22
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
1) Explain different data types in ‘C’ with examples. (May 2015, May 2014, Jan 2013]
DATA TYPES
Data type is the type of the data, that are going to access within the program. C
supports different data types, each data may have predefined memory requirement and storage
representation.
‘C’ supports the following 4 classes of data types.
Int (Integer)
Integer data type is used to store numeric values without any decimal point e.g. 7, -101,
107, etc.
Syntax:
int variable name;
Example:
int roll, marks, age;
Float
23
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Float data type is used to store numeric values with decimal point. In other words, float
data type is used to store real values, e.g. 3.14, 7.67 etc. e.g. percentage, price, pi, area etc.
may contain real values.
Syntax:
float variable name;
Example:
float per, area;
Char (Character)
Char (Character) data type is used to store single character, within single quotes e.g. 'a',
'z','e' etc. e.g. Yes or No Choice requires only 'y' or 'n' as an answer.
Syntax:
char variable name;
Example:
char chi='a', cha;
Double
Double is used to define BIG floating point numbers. It reserves twice the storage for
the number. It contains 8 bytes.
Syntax:
double variable name;
Example:
double Atoms;
Typedef:
The 'typedef' allows the user to define new data-types that are equivalent to existing
data types. Once a user defined data type has been established, then new variables, array,
structures, etc. can be declared in terms of this new data type.
Syntax:
24
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Example:
typedef int number;
Array
An array is a collection of variables of same type i.e. collection of homogeneous data referred
by a common name. In memory, array elements are stored in a continuous location.
Syntax:
Datatype arrayname[ ];
Example:
int a[10];
char chi [20];
Pointer
A pointer is a special variable that holds a memory address (location in memory) of
another variable.
Syntax:
datatype *var_name;
* is a pointer variable.
'var_ name' is the name where the variable is to be stored.
Example:
int a,*b;
Struct
A struct is a user defined data type that stores multiple values of same or different data
types under a single name. In memory, the entire structure variable is stored in sequence.
Syntax:
struct < structure name>
{
member1;
member2;
-----
-----
};
Structure name is the name of structure e.g. store details of a student as- name, roll, marks.
struct student
{
char name [20];
int roll,
float marks;
};
25
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Union
A union is a user defined data type that stores multiple values of same or different data
types under a single name. In memory, union variables are stored in a common memory location.
Syntax:
union < tag name>
{
var1;
var2;
-----
----
};
Tag name is the name of union, e.g, store details of a student as- name, roll, marks.
Union student
{
char name [20];
int roll,
float marks;
};
Void
Void data type is used to represent an empty value (or) null value. It is used as a return
type if a function does not return any value.
2.) What are the different types of operators available in C? Explain with examples.
[ May 2017, Nov 2016, May 2016, Jan 2015, Jan 2014, May 2013,May-2019 ]
a) Arithmetic operators
Example:
#include<stdio.h>
#include<conio.h>
main ( )
{
int i,j,k;
clrscr( );
i=10;
j=20;
k=i+j;
printf(“values of k is %d”,k);
getch( );
}
Output:
Value of k is 30
b) Relational operator
A relational operator is mainly used to compare two or more operands.
OPERATOR MEANING EXAMPLE RETURN
< Less than 2<9 VALUE
1
> Greater than 2>9 0
== Equal to 2==2 0
!= Not equal to 2!=3 0
Example:
#include<stdio.h>
#include<coio.h>
main( )
{
clrscr( );
printf(“\n Condition: Return values\n”);
printf(“\n 5!=5 :%5d”,5!=5);
printf(“\n 5==5: %5d”,5==5);
}
Output:
Condition : Return Values
5! =5 0
5==5 1
c) Logical operator:
Logical operators are used to combine the results of two or more conditions.
Example:
27
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
#include<stdio.h>
main()
{
printf("\n Condition : return values\n");
printf("\n5>3 && 5<10: %5d",5>3 && 5<10);
printf("\n8>5||8<2 : %5d",8>5||8<2):
printf("\n!(8==8) : %5d",!(8==8));
}
Output:
Condition : Return Values
5>3 && 5>10: 1
8>5 II 8<2 : 0
!(8==8) : 0
d) Assignment operator
Assignment operators are mainly used to assign a value or expression or value of a
variable to another variable.
Example:
#include<stdio.h>
#include<Conio.h>
main( )
{
int i,j,k;
clrscr( );
k=(i=4,j=5);
printf(“k=%d”,k);
getch( );
}
Output:
K=5
e) Increment and Decrement operator
‘C’ languages have two useful operators generally not found in any other programming
languages. They are,
1. Increment (++)
2. Decrement (--)
These operators are generally known as Unary operators
OPERATOR MEANING
++a Pre increment
--a Pre decrement
a++ Post increment
a-- Post decrement
Example:
#include<stdio.h>
#include<conio.h>
main( )
{
int a=10;
printf(“a++=%d\n”,a++);
printf(“++a=%d\n”,++a);
printf(“a--=%d\n”,a--);
printf(“--a=%d\n”,--a);
}
Output:
28
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
a++=10
++a=12
a--=11
--a=11
f) Conditional operators
Conditional operators itself check the condition and executes the statement depending upon
the condition.
Syntax:
Description:
“? :” operator acts as a ternary operator.
It first evaluates the condition
If it is true then ‘exp1’ is evaluated.
If it is false yhen’exp2’ is evaluated.
Example:
main( )
{
int a=5,b=3,big;
big=a>b?a:b;
printf(“Big is……%d”,big);
}
Output:
Big is 5
f) Bitwise operator:
It is used to manipulate the data at-bit level. It operates only integers.
OPERATOR MEANING
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One’s Complement
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
#include <stdio.h>
main()
{
29
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
int a=12,b=39;
printf("Output=%d",a&b);
}
Output
Output=4
g) Special operator:
‘C’ language supports some of the special operators they are
OPERATORS MEANING
, Comma operators
Size of Size of operators
& and * Pointer operators
. and -> Member section operators
Comma operators:
It is used to operate the statement such as variables, constants,expressin etc.
Example: val= (a=3,b=9,c=77);
Sizeof( ) operator:
IT is Unary operator.It returns the length in bytes of specified variable.It returns the
length in bytes of specified variable. It is very useful to find the bytes occupied by specified
variables in the memory.
Pointer operator:
&-> this symbol is used to specify the ADDRESS of the variables.
*-> this symbol is used to specify the VALUE if a variable.
3) Explain briefly the formatted & unformatted I/O functions in ‘C’. (May- 2014)
MANAGING INPUT AND OUTPUT OPERATIONS
In C language there are 2 types of I/P & O/P statements are available. They are : several
functions are available for input/output operations in C. These functions are collectively
known as standard I/O library.
gets() puts()
INPUT OUTPUT
30
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
getchar() putchar()
getc() putc()
gets() puts()
This getchar() function is written in standard I/O library. It reads a single character from a
standard input device.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf(“Enter any character/digit…”);
ch=getchar();
if(isalpha(ch)>0)
printf(“It is a alphabet”);
else
if(isdigit(ch)>0)
printf(“It is a digit”);
else
printf(“It is alphanumeric”);
}
Output:
1.Enter any character/digit…a
It is alphabet
2.Enter any character/digit…1
It is a digit
3.Enter any character/digit…#
It is alphanumeric
Program:
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf(“Enter any alphabet either in lower or uppercase..”)
31
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
ch=getchar();
if(islower(ch))
{
putchar(toupper(ch));
}
else
{
putchar(tolower(ch));
}
}
Output:
Enter any alphabet either in lower or uppercase…s
S
Enter any alphabet either in lower or uppercase…M
m
getc() function:
This is used to accept a single character from the standard input to a character variable.
Syntax:
character variable=getc();
Eg:
char c;
c = getc();
putc() function:
This is used to display a single character in a character variable to standard output device.This
function is mainly used in file processing.
Syntax:
putc(character variable);
Eg:
char c;
putc(c);
gets() function:
The gets() function is used to read the string from the standard input device(keyboard).
Syntax:
puts(char type of array variable);
Eg:
puts(s);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
char scientist[40];
puts(“Enter name:”);
gets(scientist);
puts(“print the name”);
puts(scientist);
}
OUTPUT:
Enter name: Risha
print the name: Risha
32
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
INPUT OUTPUT
scanf() printf()
fscanf fprintf()
scanf() function:
Input data can be entered into the computer using standard input C library function called
scanf().This function is used to enter any combinations of input.
scanf() function is mainly used to read information from the standard input device keyboard.
Syntax:
scanf(“control string”,&var1,&var2,…&varn);
Eg:
int n;
scanf(“%d”,&n);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int m,n,a;
clrscr();
printf(“Enter the 2 numbers:”);
scanf(“%d%d”,&m,&n);
if(m>n)
{
a=m;
m=n;
n=a;
}
printf(“the interchanged values are: “%d%d”,m,n);
getch();
}
printf() function:
Output data can be displayed from the computer using standard output C
library function called printf().This function is used to display any combinations of
data.
prints() function is mainly used to display information from the standard
output device(monitor).
Syntax:
printf(“control string”,&var1,&var2,…&varn);
Eg:
int n;
printf(“%d”,n);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf(“Engineering Students \n”);
getch();
}
33
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Syntax: Flowchart
if(condition 1)
{
if(condition 2)
{
True statement 2
}
else
{
False statement 2;
}
}
else
{
False statement 1;
}
Next Statement;
Program:
#include<stdio.h>
main()
{
int a b c;
printf(“Enter the value for A, B and C:”);
scanf(“%d%d%d”,&a,&b,&c);
if((a>b)&&(a>c))
{
printf(“A is largest”);
}
else
{
if(b>c)
{
printf(“B is largest”);
}
else
{
printf(“C is largest”);
}
}
}
Output:
Enter the value for A,B and C:12 13 5
B is largest
Syntax Flowchart
switch(expression)
{
case label1:
block 1;
break;
case label2:
block 2;
break;
……..
……..
default:
Default
block;
break;
}
Program:
#include<stdio.h>
main()
{
int a=1;
switch(a)
{
case 1:
printf(“I am in case 1 \n”);
break;
case 2:
printf(“I am in case 2 \n”);
break;
35
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
default:
printf(“I am in case default\n”);
break;
}
}
Output:
I am in case 1
3. if – else ladder
It is otherwise known as Multi-way decisions. Each and every else block will have if
statement. Last else block cannot have if block. Last else will have default statement.
Syntax Flowchart
if(condition1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
--------
--------
else
default
statement;
Example:
--------
--------
if(per >= 60)
printf(" You got 1st Class");
else if( per >= 45)
printf(" You got 2nd Class ");
else if(per>=27)
printf("\n You got 3rd Class ");
else
printf("\n NO Class ");
--------
--------
C has some kinds of statements that permit the execution of a single statement, or a block
of statements, based on the value of a conditional expression or selection among several
statements based on the value of a conditional expression or a control variable.
36
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
(i) if statement
(ii) if-else statement
(iii) Nested if-else statement
(iv) if-else ladder (else if ladder)
(i)if statement:
It is otherwise known as One-way decisions. It is used to control the flow of execution of
the statements. The decision is based on a ‘test expression or condition’ that evaluates to either
true or false.
If the test condition is true, the corresponding statement is executed.
If the test condition is false, control goes to the next executable statement.
Syntax: Flowchart
if(condition is true)
{
Statement 1;
------------
------------
Statement n;
}
Next Statement;
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int m,n,a;
clrscr();
printf(“Enter 2 numbers:”);
scanf(“%d%d”,&m,&n);
if(m>n)
{
a=m;
m=n;
n=a;
}
printf(“The interchanged values are: “%d%d”,m,n);
getch();
}
(ii)if-else statement:
It is otherwise known as Two-way decisions. It is handled with if-else statements. The
decision is based on a ‘test expression or condition’ that evaluates to either true or false.
If the test condition is true, the true block will be executed then control goes to the next
executable statement.
If the test condition is false, the false block will be executed control goes to the next
executable statement.
37
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Syntax: Flowchart
if(condition is true)
{
True block;
}
else
{
false block;
}
Next statement;
Program:
#include<stdio.h>
main()
{
int a,b;
printf(“Enter two numbers:”);
scanf(“%d%d”,&a,&b);
if(a>b)
{
printf(“A is largest”);
}
else
{
printf(“B is largest”);
}
getch();
}
OUTPUT:
Enter two numbers:12 5
A is largest
Syntax: Flowchart
if(condition 1)
{
if(condition 2)
{
True statement 2
}
else
{
False statement 2;
}
}
else
{
False statement 1;
}
Next Statement;
38
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Program:
#include<stdio.h>
main()
{
int a b c;
printf(“Enter the value for A, B and C:”);
scanf(“%d%d%d”,&a,&b,&c);
if((a>b)&&(a>c))
{
printf(“A is largest”);
}
else
{
if(b>c)
{
printf(“B is largest”);
}
else
{
printf(“C is largest”);
}
}
}
Output:
Enter the value for A,B and C:12 13 5
B is largest
Syntax Flowchart
if(condition1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
--------
--------
else
default
statement;
Example:
--------
--------
if(per >= 60)
printf(" You got 1st Class");
else if( per >= 45)
39
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Syntax Flowchart
switch(expression)
{
case label1:
block 1;
break;
case label2:
block 2;
break;
……..
……..
default:
Default
block;
break;
}
40
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Program:
#include<stdio.h>
main()
{
int a=1;
switch(a)
{
case 1:
printf(“I am in case 1 \n”);
break;
case 2:
printf(“I am in case 2 \n”);
break;
default:
printf(“I am in case default\n”);
break;
}
}
Output:
I am in case 1
break statement:
1.It is used to terminate the loop. When the keyword break is used inside any ‘C’
loop,control automatically transferred to first statement after the loop.
2. A break is usually associated with an if statement.
Syntax:
break;
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
break;
printf(“%d”,i);
}
}
Output:
12345
41
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Continue statement
It is mainly used to take the control to the beginning of the loop, for these purposes
continue statement is used.
When the statements continue is used inside any ‘C’ loop, control automatically passes to
the beginning of the loop.
It is also associated with if statement.
Syntax:
continue;
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int i,n,sum==0;
for(i=1;i<=5;i++)
{
print(“Enter any number…\n”);
scanf(“%d”,&n);
if(n<0)
continue;
else
sum=sum+n;
}
printf(“sum is…%d”,sum);
}
Output:
Enter any number…10
Enter any number…15
Enter any number…25
Enter any number…10
Enter any number…50
Sum is …100
Goto statement
It is used to transfer control unconditionally from one place to another place.
A goto statement can cause program control almost anywhere in the program
unconditionally.
It requires a label to identify the place to move the execution.
A label is a valid variable name and must be ended with colon (:).
42
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
Syntax:
goto label;
………
………
label:
label:
…….
…….
goto label;
Program:
#include<stdio.h>
main()
{
int a,b;
printf(“Enter the numbers”);
scanf(“%%d”,&a,&b);
if(a==b)
goto equal;
else
{
printf(“\n A and B are not equal”);
exit(0);
}
equal:
printf(“A and B are equal”);
}
Output:
1. Enter the numbers 3 3
A and B are equal
2. Enter the numbers 3 4
A and B are not equal
43
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
11. How does an array definition differ from an ordinary variable? (MAY-2012)
12. Define array and write its type. (MAY-2015)
13. Write any four features of arrays. (MAY 2016)
15. Explain any two string functions with example. (NOV 2016,JAN 2011)
16. List any five built in string functions. (MAY 2017)
17.Write the syntax of else-if statements.[Apr/May-2018]
Part-B
1. Write a C Program to count the letter in sequence of characters.(May-2017)
2. Explain recursion by finding factorial of 5 using recursion.(May-2017,Apr/May-2016)
6. Write a C Program to find the addition and subtraction of two matrix (Apr/May-2016)
7. Discuss about the different looping statement used in C.(Jan-2016)
8. Write a Program to find the sum of n numbers using recursion(Jan-2016,May-2015)
9. Explain in detail about the break, continue and goto statements with an example program(Jan-2016)
10. Write a C Program to find whether a given number is odd or even.(May-2015)
11. Write a C program to print the sum of digits of the given numbers(May-2015)
12. Write a C Program to check whether the given string is palindrome or not(May-2015)
13. Discuss the different storage classes by identifying its scope and life time of variables(Jan-
2015,Jan-2013)
14. Explain about passing an array to function (Apr/may-2014 )
15. Write a C Program to determine whether a given numbers is Prime number or not(Apr/May-
2014)
16. Explain the string library functions with an example.(Apr/May-2014,2018,Jan-2014)
17. Write in detail about jumps in loops with neat example.(Jan-2014)
44
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C
45