0% found this document useful (0 votes)
13 views144 pages

Unit 2

The document outlines the syllabus for a C programming course, covering topics such as program structure, data types, operators, control flow, and variable declaration. It details the components of a C program, including documentation, link, definition, global declaration, main function, and user-defined sections. Additionally, it explains tokens, keywords, identifiers, constants, and various data types, along with their sizes and ranges.
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)
13 views144 pages

Unit 2

The document outlines the syllabus for a C programming course, covering topics such as program structure, data types, operators, control flow, and variable declaration. It details the components of a C program, including documentation, link, definition, global declaration, main function, and user-defined sections. Additionally, it explains tokens, keywords, identifiers, constants, and various data types, along with their sizes and ranges.
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/ 144

Unit-2

Syllabus:

➢ Introduction, Structure of a C Program.

➢ Comments, Keywords, Identifiers, Data Types, Variables, Constants, Input/output Statements.

➢ Operators, Type Conversion. Control Flow.

➢ Relational Expressions: Conditional Branching Statements: if, if-else, if-else—if, switch.

➢ BasicLoop Structures: while, do-while loops, for loop, nested loops,

➢ The Break and Continue Statements, goto statement


General Structure of c Program:
Structure of C:
Documentation Section
• This section consists of comment lines which include the name of programmer, the author and other details like time
and date of writing the program. Documentation section helps anyone to get an overview of the program.
Link Section
• The link section consists of the header files of the functions that are used in the program. It provides instructions to the
compiler to link functions from the system library.
Definition Section
• All the symbolic constants are written in definition section. Macros are known as symbolic constants.(eg: # define pi
3.14)
Global Declaration Section
• The global variables that can be used anywhere in the program are declared in global declaration section. This section also
declares the user defined functions.
Main () Function Section
• It is necessary have one main() function section in every C program. This section contains two parts, declaration and
executable part. The declaration part declares all the variables that are used in executable part. These two parts must be
written in between the opening and closing braces. Each statement in the declaration and executable part must end with a
semicolon (;). The execution of program starts at opening braces and ends at closing braces.
Subprogram Section/user defined section
• The subprogram section contains all the user defined functions that are used to perform a specific task. These user defined
• functions are called in the main() function.
Comment:
A comment is an explanation or description of the source code of the program. It helps a developer explain logic
of the code and improves program readability. At run-time, a comment is ignored by the compiler.
There are two types of comments in C:
1) A comment that starts with a slash asterisk /* and finishes with an asterisk slash */ and you can place it
anywhere in your code, on the same line or several lines.
2) Single-line Comments which uses a double slash // dedicated to comment single lines.

Eg: #include <stdio.h>


int main() {
/* in main function
I can write my principal code
And this in several comments line */
int x = 42; //x is a integer variable
printf("%d", x);
return 0; }
Tokens in C
➢ A token in C can be defined as the smallest individual element of the C programming language that is
meaningful to the compiler.
➢ Therefore, we can say that tokens in C is the building block or the basic component for creating a program
in C language.
➢ The tokens of C language can be classified into six types
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords
➢ The keywords are pre-defined or reserved words in a programming language.
➢ Each keyword is meant to perform a specific function in a program.
➢ Since keywords are the pre-defined words used by the compiler, so they cannot be used as the
variable names.
➢ As C is a case sensitive language, all keywords must be written in lowercase.
➢ If the keywords are used as the variable names, then error messages will come
[Error] expected unqualified-id before '=' token
[Error] expected primary-expression before ‘keyword_name’
C language supports 32 keywords which are given below:

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while
2. Identifiers
➢ Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the
user-defined words.
➢ It can be composed of uppercase letters, lowercase letters, underscore, or digits. Identifiers cannot be used
as keywords.
➢ Rules for constructing identifiers in C are given below:

i. The first character of an identifier should be either an alphabet or an underscore, and then it can be followed
by any of the character, digit, or underscore.
.
ii It should not begin with any numerical digit.

iii. In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers are case
sensitive.
iv. Commas or blank spaces cannot be specified within an identifier.
v. Keywords cannot be represented as an identifier .

vi. The length of the identifiers should not be more than 31 characters.
vii. Identifiers should be written in such a way that it is meaningful, short, and easy to read.
3. Constants
➢ A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.
➢ There are two ways of declaring constant:
➢ Syntax to Define Constant
const data_type var_name = value;
Using const keyword
Using #define pre-processor
Integer Constants
There are three types of integers:
i. Decimal integer
ii. Octal integer
iii. Hexadecimal integer

i. Decimal integer:
Decimal integer should not start with 0, embedded spaces, commas and non-digit characters are not permitted.
ii. Octal integer:
Octal integer should start with 0.
printf (“%d”, ) will give you the corresponding decimal integer from octal integer.
printf (“%o”, ) will print octal integer.
iii. Hexadecimal integer:
Hexadecimal integer should start with 0x or 0X.
printf (“%d”, ) will give you the corresponding decimal integer from hexadecimal integer.
printf (“%x”, ) will print hexadecimal integer.
iv. Binary integer:
Binary integer should start with 0b or 0B.
printf (“%d”, ) will give you the corresponding decimal integer from binary integer.
printf (“%x”, ) will give you the corresponding hexadecimal integer from binary integer.
printf (“%o”, ) will give you the corresponding octal integer from binary integer.
Real Constants
Real Constants also known as Floating point Constants are numbers that have a whole number followed by a

decimal point followed by the fractional number. The real constants can be expressed in two forms:

• Fractional Form

• Exponential Form

Have a look at the rules that guide the construction of Real Constants in Fractional Form:

• It should have a floating point.

• It should have at least have one digit.

• It can have a positive or negative sign. In case it doesn’t have any sign it is taken as positive.

• No blank spaces or commas are allowed.

Eg: 546.236, +453.89, -22.564


Syntax:
float variable_name=real_constant; // Define a real constant
Printf(“%f”, variable_name); // To print real constant
➢ In case the value we are dealing with is too small like 0.00003 or too big like 300000, we can use

the exponential form to express these constants as 3.0e-5 and 3.0e5.

➢ The part before the ‘e’ is known as mantissa and the part after the ‘e’ is known as exponent.

Rules for construction of Real Constants in Exponential Form:

• The mantissa and the exponential part should have a letter ‘e’ between them.

• The exponent should have at least one digit.

• It can have a positive or negative sign. In case it doesn’t have any sign it is taken as positive.

Eg: 5.6e9, +2.0e-7, -5.6e+8, -7.8e-5.


Character Constants

A Character Constant is a single alphabet, digit or special character enclosed within ‘single quotes’.

Rules for construction of Character Constants :

• Should be enclosed within single quotes.

• The inverted commas should point to the left.

• It can have only one character, digit or special character.

Eg: ‘A’, ‘f’, ‘4’


Syntax:
char variable_name=‘character’; // Define a character constant
Printf(“%c”, variable_name); // To print real constant
➢ ASCII stands for American Standard Code for Information Interchange.
➢ This ASCII value represents the character variable in numbers, and each character variable is
assigned with some number range from 0 to 127.
String constant
A string constant is a combination of alphabets, digits and special characters enclosed within “double

quotes”. Have a look at the rules that guide the construction of String Constants:

• Should be enclosed within double quotes.

• It can be of any length.

• It ends with a null character assigned to it by the compiler.

Eg: “Welcome to VIIT”, “Good to see you”, “8 apples”, “learning is fun”.


Syntax:
char variable_name[]=“string”; // Define a string constant
Printf(“%s”, variable_name); // To print string constant
Backslash Character Constants

➢ There are some characters which are impossible to enter into a string from keyboard like backspace,

vertical tab etc.

➢ Because of this reason, C includes a set of backslash character which have special meaning in C

language.

➢ The backslash character ('\') changes the interpretation of the characters by compiler.
Escape Sequence Description Remarks
\” Double quote(") It is used to display double quotation marks.
\' Single quote(') It is used to display a single quotation mark.
\\ Backslash Character(\) Use to insert backslash character.
\b Backspace It is used to move the cursor one place backward.
\f Form feed It is used to move the cursor to the start of the next
logical page.
\n New line It moves the cursor to the start of the next line.
\r Carriage return It moves the cursor to the start of the current line.
\t Horizontal tab It inserts some whitespace to the left of the cursor
and moves the cursor accordingly.
\v Vertical tab It is used to insert vertical space.
\a Alert or bell It is used to generate a bell sound in the C program.
\? Question mark It is used to display a question mark.
\0 Null character It represents the NULL character.
Data Types:

➢ A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

➢ Primary Data Types


➢ User Defined Data Types
➢ Derived data Types

Primary Data Types:


Primitive data types are the most basic data types that are used for representing simple
values such as integers float, characters, etc.
Data Type Size Description

int 2 or 4 bytes Stores whole numbers, without decimals

float 4 bytes Stores fractional numbers, containing one or more


decimals. Sufficient for
storing 6-7 decimal digits

char 1 byte Stores a single character/letter/number, or ASCII


values
Size and Range of the data types
➢ A signed data type can store both positive and negative values. Range of signed data type -2bits/2 to 2bits/2 – 1
➢ An unsigned data type can store positive values. Range of unsigned data type 0 to 2bits – 1
➢ int occupies four bytes of memory while short int occupies only two bytes of memory.
➢ float stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7 decimal digits.
➢ Double stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits.
➢ Long stores fractional numbers, containing one or more decimals. Sufficient for storing 19 decimal digits.
➢ A dot (.) followed by a number that specifies how many digits that should be shown after the decimal point
Eg:
#include <stdio.h>
int main() {
float myFloatNum = 3.5;
printf("%f\n", myFloatNum); // 3.500000
printf("%.1f\n", myFloatNum); // 3.5
printf("%.2f\n", myFloatNum); // 3.50
return 0; }
Data Types Memory Size Format Specifier Literal Range

char 1 byte %c −128 to 127


signed char 1 byte %c −128 to 127
unsigned char 1 byte %c 0 to 255
Short int 1 byte or 2 byte %hd −128 to 127 or −32,768 to 32,767
signed short int 1 byte or 2 byte %hd −128 to 127 or −32,768 to 32,767
unsigned short int 1 byte or 2 byte %hu 0 to 255 or 0 to 65,535
int 2 byte or 4 byte %d -124 −32768 to 32767 or 2147483648 to 2147483647

signed int 2 byte or 4 byte %d -124 −32768 to 32767 or 2147483648 to 214748364

unsigned int 2 byte or 4 byte %u 45678U 0 to 65535 or 0 to 4294967295


long int 4 byte or 8 byte %ld -545445L -2147483648 to 2147483647
signed long int 4 byte or 8 byte %ld -545445L -2147483648 to 2147483647
unsigned long int 4 byte or 8 byte %lu 987654UL 0 to 4294967295
float 4 byte %f -1.2f 1.2E-38 to 3.4E+38
double 8 byte %lf 1.234 2.3E-308 to 1.7E+308
long double 10 byte %Lf 1.23456786L 3.4E-4932 to 1.1E+4932
Program Explanation

The header file “limits.h” is used to find minimum and maximum constants of integer and character data type.

INT_MIN = represents minimum integer value i.e. (-2147483648)


INT_MAX = represents maximum integer value i.e. (2147483647)
UINT_MAX = represents maximum integer value of unsigned numbers i.e. (0 to 4294967295)
SCHAR_MIN = represents minimum character value i.e. (-128)
SCHAR_MAX = represents maximum character value i.e. (127)
UCHAR_MAX = represents maximum character value of unsigned characters i.e. (0 to 255)
SHRT_MIN = represents minimum value for an object of type short int i.e (-32768)
SHRT_MAX = represents maximum value for an object of type short int i.e. (32767)
USHRT_MAX = represents maximum value for an object of type unsigned short int i.e. (0 to 65535)
LONG_MIN = represents minimum value for an object of type long int i.e. (-2147483648)
LONG_MAX = represents maximum value for an object of type long int i.e. (2147483647)
ULONG_MAX = represents maximum value for an object of type unsigned long int i.e. (0 to
4294967295)
Derived Data Types
➢ Derived data types are primary data types that are grouped together. You can group many
elements of similar data types. These data types are defined by the user. The following are
the derived data
types in C:
• Array
• Pointers
• Structure
• Union
User-defined data types
The data types that are defined by the user depending upon the use case of the programmer
are termed user-defined data types.
Variables
➢ A variable in C language is the name associated with some memory location to store data of different types.

Syntax:
data_type variable_name = value; // defining single variable
or

data_type variable_name1, variable_name2; // defining multiple variable

Rules for naming a variable:


i. A variable name can only have letters (both uppercase and lowercase letters), digits and underscore.
ii. The first letter of a variable should be either a letter or an underscore.
iii. There is no rule on how long a variable name (identifier) can be. However, you may run into problems in
some compilers if the variable name is longer than 31 characters.
There are 3 aspects of defining a variable:
1. Variable Declaration
2. Variable Definition
3. Variable Initialization
1. Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with the given name and data
type. When the variable is declared compiler automatically allocates the memory for it.
2. Variable Definition
In the definition of a C variable, the compiler allocates some memory and some value to it. A defined variable
will contain some random garbage value till it is not initialized.

3. Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to the variable.
int var; // variable definition or declaration
var = 10; // initialization
or

int var = 10; // variable declaration and definition

Variable Types

1. Local Variables

2. Global Variables

3. Static Variables

4. Automatic Variables

5. Extern Variables

6. Register Variables
Input/output statements

➢ Input and output statements are used to read and write the data in C programming language.

➢These are included in header file stdio.h (standard input and output).

➢There are mainly two of Input/Output functions are used for this purpose.

• Formatted I/O functions


• Unformatted I/O functions
➢Formatted I/O functions
Formatted functions allow the input read from keyboard or output to screen to be formatted
as per our requirements.
scanf()
printf()
➢The scanf() function is an input function.
Syntax: scanf(“%X”, &variable of XType);
➢ The printf() function is an output function.
Syntax: printf(“%X”, variable of XType);
➢%X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable
➢ & is the address operator in C, which tells the compiler to change the real value of this
variable, stored at this address in the memory.
Unformatted I/O functions :
• There are mainly six unformatted I/O functions discussed as follows:

➢ getchar()
➢putchar()
➢ gets()
➢puts()
➢getch()
➢getche()
getchar() :
➢This function is an Input function.
➢It is used for reading a single character from the keyboard.
➢It is a buffered function.
Syntax: char n;
n = getchar();
putchar():
➢ This function is an output function.
➢ It is used to display a single character on the screen.
Syntax: char n;
putchar();
gets()
➢This function is an input function.
➢ It is used to read a string from the keyboard.
➢It will read a string when you type the string from the keyboard and ends only when press
the Enter key from the keyboard.
Syntax: char n[20];
gets(n);
puts()
➢This is an output function.
➢It is used to display a string inputted by gets() function.
➢This function appends a newline (“\n”) character to the output.
Syntax: puts(v);
getch()
➢This is also an input function.
➢ This is used to read a single character from the keyboard like getchar() function.
➢But getchar() function is a buffered is function, getch() function is a non-buffered
function.
➢The character data read by this function is directly assigned to a variable rather it goes to
the memory buffer, the character data is directly assigned to a variable without the need to
press the Enter key.
➢Another use of this function is to maintain the output on the screen till you have not press
the Enter Key.
Syntax
v = getch();
getche()
➢getche() function reads a single character from the keyboard and displays immediately on
the output screen without waiting for enter key.
Syntax:
p = getche();
Operators in C
➢An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions.
➢C has many built-in operators and can be classified into 8 types.
▪ Arithmetic Operators
▪ Relational Operators
▪ Logical Operators
▪ Assignment Operators
▪ Bitwise Operators
▪ Increment and Decrement Operators
▪ Conditional Operators
▪ Special Operators
Arithmetic Operators

• These operators are used to perform arithmetic/mathematical operations on operands.


Examples: (+, -, *, /, %).

Operator Name Description Example

+ Addition Adds together two value x+y

- Subtraction Subtracts one value from x - y


another
* Multiplication Multiplies two values x*y

/ Division Divides one value by x/y


another
% Modulus Returns the division x%y
remainder

These operators are called as binary operators. Operators that operate or work with two
operands are binary operators.
Relational Operator:

➢A relational operator checks the relationship between two operands.


➢If the relation is true, it returns 1; if the relation is false, it returns value 0.
➢Relational operators are used in decision making and loops.

Operator A Meaning of Operator Example


== Equal to 8 == 3 is evaluated to 0 and 8 == 8 is evaluated to 1 .
> Greater than 8 > 3 is evaluated to 1 and 8 > 8 is evaluated to 0.
< Less than 8 < 3 is evaluated to 0 and 8 < 8 is evaluated to 0.
!= Not equal to 8 != 3 is evaluated to 1 and 8 != 8 is evaluated to 0.
>= Greater than or equal to 8 >= 3 is evaluated to 1 and 8 >= 8 is evaluated to 1
<= Less than or equal to 8 <= 3 is evaluated to 0 and 8 <= 8 is evaluated to 1
Logical Operators:

➢An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false respectively.

Operator Meaning

&& or and Logical AND. True only if all operands are true

|| or or Logical OR. True only if either one operand is true

! Logical NOT. True only if the operand is 0

^ or xor Logical XOR. True only if one operand is true and other is false
Assignment operators:

➢The assignment operator is used to assign the value, variable and function to another
variable.
Operator Meaning Of Operator Example Example

= assignment operator x=y x=y

+= Add left operand to right operand then assign result to left x+=y x=x+y
operand
-= subtract right operand from left operand then assign result x-=y x=x-y
to left operand
*= multiply left operand with right operand then assign result x*=y x=x*y
to left operand
/= divide left operand with right operand then assign result to x/=y x=x/y
left operand
%= take modulus left operand with right operand then x%=y x=x%y
assigned result in left operand
v. Bitwise Operators
The bitwise operators are the operators used to perform the operations on the data at the bit-level.

Operator Meaning Of Operator Example Same as


Left Shift Assignment Operator means the left operand is left shifted by right
<<= x<<=y x=x<<y
operand value and assigned value to left operand
Right shift Assignment Operator means the left operand is right shifted by right
>>= x>>=y x=x>>y
operand value and assigned value to left operand
Bitwise AND Assignment Operator means does AND on every bit of left
&= x&=y x=x&y
operand and right operand and assigned value to left operand
Bitwise inclusive OR Assignment Operator means does OR on every bit of left
|= x|=y x=x|y
operand and right operand and assigned value to left operand
Bitwise exclusive OR Assignment Operator means does XOR on every bit of left
^= x^=y x=x^y
operand and right operand and assigned value to left operand
Left Shift(<<)
It is a binary operator that takes two numbers, left shifts the bits of the first operand, and the second operand
decides the number of places to shift.
Right Shift(>>)
It is a binary operator that takes two numbers, right shifts the bits of the first operand, and the second operand
decides the number of places to shift.
Truth table of the bitwise operators.

X Y X&Y X|Y X^Y


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Bitwise AND (&=)


x =6; y=4;
The binary representation of the above two variables are
given below:

x= 0110
y= 0100
x&y = 0100
Bitwise OR (|=)
x =6; y=4;
The binary representation of the above two variables are given below:

x= 0110
y= 0100
x|y = 0110

Bitwise exclusive OR (^=)


x =6; y=4;
The binary representation of the above two variables are given below:

x= 0110
y= 0100
~ Binary Ones Complement (~A ) = -61, i.e,.1100 0011 in 2's
x|y = 0010 complementform
Increment and Decrement Operators :

➢ The increment ( ++ ) and decrement ( -- ) operators in C are unary operators for


incrementing and decrementing the numeric values by 1 respectively
Conditional Operators

The conditional operator in C is kind of similar to the if-else statement as it follows the
same algorithm as of if-else statement but the conditional operator takes less space and
helps to write the if-else statements in the shortest way possible.
➢ Itis also known as the ternary operator in C as it operates on three operands.
Syntax:
variable = Expression1 ? Expression2 : Expression3;
Or
variable = (condition) ? Expression2 : Expression3;
Or
(condition) ? (variable = Expression2) : (variable = Expression3)
viii.Special Operators

➢ Apart from the above operators, there are some other operators available in C used to
perform some specific tasks.

a. Comma Operator

b. Type Cast Operator

c. Reference Operator

d. Dereference Operator

e. sizeof
a. Comma Operator
➢ The comma operator is type of special operators in C which evaluates first operand and then
discards the result of the same, then the second operand is evaluated and result of same is
returned.
➢ The comma operator has the lowest precedence of any C operator.
Example: int val= (10, 30);
In this example 10 is discarded and 30 is assigned to val variable.
Example: int val= 10, 30;
In this example 10 is assigned to val variable because assignment operator is having higher
precedence.
➢ Comma acts as both operator and separator. In C, comma ( , ) can be used in three contexts:
▪ Comma as an operator
▪ Comma as a separator
▪ Comma operator in place of a semicolon
b. Type Cast Operator
➢ Typecasting in C is the process of converting one data type to another data type by the
programmer using the casting operator during program design.

Syntax:
(type)value;

➢ In C there are two major types to perform type casting.

✓ Implicit type casting

✓ Explicit type casting


Implicit type casting
• When the type conversion is performed automatically by the compiler
without programmers intervention, such type of conversion is known
as implicit type conversion or type promotion.

• Implicit type conversion happens automatically when a value is copied


to its compatible data type.

• If the operands are of two different data types, then an operand having
lower data type is automatically converted into a higher datatype.
It is automatically done by the compiler by converting smaller
data type into a larger data type.
✓ Explicit type casting
➢ In this conversion, the user can define the type to which the expression is to be converted. It can be a larger or
smaller data type.
➢ Explicit type conversion can be achieved by using the cast operator in C.
.
c Reference Operator & Dereference Operator
➢ Referencing means taking the address of an existing variable (using &) to set a pointer variable. In

order to be valid, a pointer has to be set to the address of a variable of the same type as the pointer.

➢ For e.g., if we write “&x”, it will return the address of the variable “x’.

➢ Dereferencing a pointer means using the * operator (asterisk character) to retrieve the value from the

memory address that is pointed by the pointer.

➢ For e.g., if we write “*p”, it will return the value of the variable pointed by the pointer “p”.
.
e sizeof

➢ It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable.
➢ When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.
Flow Control Statements:
➢ By default, statements in a C program are executed in a sequential order.
➢ The order in which the program statements are executed is known as ‘flow of program control’ or just ‘flow
of control’. By default, the program control flows sequentially from top to bottom.
➢ All the programs that we have developed till now have default flow of control. Many practical situations like
decision making, repetitive execution of a certain task, etc. require deviation or alteration from the default flow
of program control.
➢ The default flow of control can be altered by using flow control statements. Flow control statements are of
two types:

1. Branching statements
i. Selection statements
ii. Jump statements
2. Iteration statements
1. Branching Statements
➢ Branching statements are used to transfer the program control from one point to another.
They are categorized as:
a. Conditional branching: In conditional branching, also known as selection, program control is transferred
from one point to another based upon the outcome of a certain condition. The selection statements are:

if statement
if-else statement
switch statement
b. Unconditional branching: In unconditional branching, also known as jumping, program control is
transferred from one point to another without checking any condition. The jump statements are:

goto statement
break statement
continue statement
return statement
i. Selection Statements
Based upon the outcome of a particular condition, selection statements transfer control from one point to
another. Selection statements select a statement to be executed among a set of various statements. The selection
statements available in C are as follows:

1. if statement
2. if-else statement
3. switch statement
1. if statement
➢ Use if statement to specify a block of code to be executed if a condition is true.
Syntax
if (condition)
{
// block of code to be executed if the condition is true;
}
➢ If the if controlling expression evaluates to true, the statement constituting if body is executed.
➢ If the if controlling expression evaluates to false, if body is skipped and the execution continues from the
statement following the if statement.
2. if-else statement
➢ Most of the problems require one set of actions to be performed if a particular condition is true, and another
set of actions to be performed if the condition is false. To implement such a decision, C language provides
an if-else statement.

Syntax
if (condition)
{
// block of code to be executed if the condition is true;
}
else
{
// block of code to be executed if the condition is false;
}
➢ If the if-else controlling expression evaluates to true, the statement constituting the if body is executed and
the else body is skipped.

➢ If the if-else controlling expression evaluates to false, the if body is skipped and the else body is executed.
➢ After the execution of the if body or the else body, the execution continues from the statement following
the if-else statement.
Questions of if-else statement.
1. Write a C program that takes two integers as input and uses an if-else statement to determine which one is
larger.
2. How can you use if-else statements in C to check if a number is even or odd? Provide an example.
3. How would you create a C program to check if a year is a leap year or not, using if-else conditions?
4. Create a C program that determines whether a character entered by the user is a vowel or a consonant
using if-else statements.
5. How can you use if-else logic in C to check if a number is positive, negative, or zero? Provide a code
example.

6. Explain how you can use if-else statements in C to implement a simple calculator that performs addition,
subtraction, multiplication, and division based on user input.
7. Write a C program that checks if a user-provided number is prime or not using if-else statements.
3. Nested if statement
➢ It is always legal in C programming to nest if-else statements, which means you can use one if statement
inside another if statement(s).
Syntax
if (condition)
{
if (condition)
{
// block of code to be executed if the condition
is true;
}
}
To find greatest number among 3 numbers
//Program to find greatest number among 3 numbers
#include<stdio.h>
int main()
{ if (a<b)
int a, b, c; {
printf("Enter three integer numbers:"); if (b>c)
scanf("%d%d%d", &a, &b, &c); {
if (a>b) printf("% d is greater number", b);
{ }
if (a>c) if (b<c)
{ {
printf("% d is greater number", a); printf("% d is greater number", c);
} }
if (a<c) }
{ return 0;
printf("% d is greater number", c); }
}
}
4. If...else if...else Statement/ Else if ladder

➢ An if statement can be followed by an optional else if...else statement, which is very useful to test various
conditions using single if...else if statement.
➢ Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Else if ladder: flow chart
#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if (year % 400 == 0)
{
printf("%d is a leap year.", year);
}
else if (year % 100 == 0)
{
printf("%d is not a leap year.", year);
}
else if (year % 4 == 0)
{
printf("%d is a leap year.", year);
}
else
{
printf("%d is not a leap year.", year);
}
return 0;
}
3 Switch-case statement:

➢ A switch statement is used to control complex branching operations.

➢ The switch statement allows us to execute one code block among many alternatives.

➢ You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is

much easier to read and write.

➢ If there is a match, the corresponding statements after the matching label are executed. For example, if

the value of the expression is equal to constant2, statements after case constant2: are executed until break

is encountered.

➢ If there is no match, the default statements are executed.

➢ The default clause inside the switch statement is optional.


Syntax:

switch(expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

}
Rules for switch statement :
1. The switch expression must be of an integer or character type.

2. The case value must be an integer or character constant.

3. The case value can be used only inside the switch statement.

4. The break statement in switch case is not must. It is optional. If there is no break statement found in the

case, all the cases will be executed present after the matched case. It is known as fall through the state of C

switch statement.
Dr. J. R. Nayak
ii. Jump Statements
➢ In C, jump statements are used to jump from one part of the code to another altering the normal flow of the

program. They are used to transfer the program control to somewhere else in the program.

➢ There are 4 types of jump statements in C:

a. break

b. continue

c. goto

d. exit

e. return
2. Iteration/Loop statements
➢ Iteration is a process of repeating the same set of statements again and again until the specified condition

holds true.

➢ In C, every loop has a controlling expression.

➢ Each time the loop body is executed (an iteration of the loop), the controlling expression is evaluated.

➢ If the expression is true (has a value that’s not zero) the loop continues to execute.

➢ There are three types of iteration statements:

a. for

b. while

c. do-while
a. for Loop
➢ The for loop in C language is used to iterate the statements or a part of the program several times.
➢ When you know exactly how many times you want to loop through a block of code, use for loop.
➢ It is an entry controlled loop.
Syntax:
for loop Flow chart:
Initialization is executed (one time) before the execution of the code block. It is optional.

Condition defines the condition for executing the code block.

Increment/decrement is executed (every time) after the code block has been executed.

Examples:

int i; int i = 0;
for (i = 0; i < 5; i++) for (i; i < 5; i++)
{ {
printf("%d\n", i); printf("%d\n", i);
} }

Dr. J. R. Nayak
Write a program in C to display the first 10 natural numbers and their

summation .
Write a program in C to display a pattern like a right angle triangle using an asterisk. The pattern like :
*
**
***
****
Write a C program to make such a pattern as a pyramid with asterisk:
Write a C program to make such a pattern as a pyramid with asterisk:
b. while:
➢ In general, a while loop allows a part of the code

to be executed multiple times depending upon a

given condition.

➢ It can be viewed as a repeating if statement.

➢ The while loop is mostly used in the case where

the number of iterations is not known in

advance.

➢ Running a while loop without a body is possible.

➢ It is an entry controlled loop.


While loop flowchart:
Use of while statement to find the factorial of a number

Input-1

Input-2
Program to print table for the given number using while loop in C
b. do while:
➢ The do/while loop is a variant of the while

loop. This loop will execute the code block

once, before checking if the condition is

true, then it will repeat the loop as long as

the condition is true.

➢ The do-while loop is mainly used in the

case where we need to execute the loop at

least once.

➢ It is an exit controlled loop.


Flow chart:
Program to add numbers until the user enters zero
Program to print table for the given number using do while loop in C
1. Write a program in C to display the first 10 natural numbers.
2. Write a C program to compute the sum of the first 10 natural numbers.
3. Write a program in C to display n terms of natural numbers and their sum.
4. Write a program in C to display the multiplication table for a given integer.
5. Write a program in C to display a pattern like a right angle triangle using an asterisk. The pattern like :
*
**
***
****
6. Write a C program to display a pattern like a right angle triangle with a number. The pattern like :
1
12
123
1234
7.Write a program in C to make a pyramid pattern with numbers increased by 1. 1
23
456
7 8 9 10
8. Write a C program to make such a pattern as a pyramid with an asterisk.
9. Write a C program to check whether a given number is an Armstrong number or not.
10. Write a C program to display Pascal's triangle.
11. Write a C program to check whether a number is a palindrome or not.
12. Write a C program to find the HCF (Highest Common FDra. cJ. tRo. Nr)ayoakf two numbers.
a. break

➢ The break statement is used to terminate the loop or switch statement it is

contained within. It allows the program to exit the loop or switch and

continue executing the next statement after the loop or switch.

➢ The break statement shall appear only in the “switch” or “loop”. The

statements appearing after the break in the loop will be skipped.

➢ If we use the break statement inside of a nested loop, the break statement

will first break the inner loop. So, it won’t break all the loops.
Example-1
Example-2
Program to print table for the given number using do while loop and break in C
b. Continue

➢ The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues

with the next iteration in the loop.

➢ We can use the continue statement in the while loop, for loop, or do..while loop to alter the normal flow of

the program execution. Unlike break, it cannot be used with a C switch case.
Example-1 Example-2
Program to print table for the given number using do while loop and continue in C
c. goto
➢ The goto statement is used to jump from one line to another line in the program. Using goto statement we

can jump from top to bottom or bottom to top.

➢ To jump from one line to another line, the goto statement requires a label. Label is a name given to the

instruction or line in the program.

➢ When we use a goto statement in the program, the execution control directly jumps to the line with the

specified label.

➢ The goto statement can be used with any statement like if, switch, while, do-while, and for, etc.
Example-2
Example-1
d. exit
➢ In C, exit() terminates the calling process without executing the rest code which is after the exit() function

call. It is defined in the <stdlib.h> header file.

Syntax:

void exit(int exit_code);


Example-1
Example-2
e. return
➢ A return statement ends the execution of a function, and returns control to the calling function.

➢ We can only return a single value from a function using return statement. To return multiple values, we can

use pointers, structures, classes, etc.


Thank You

You might also like