0% found this document useful (0 votes)
10 views

Module 1.1 Character Set, Constants, Identifiers, Keywords, Basic Data Types, Variables

Module 1 covers the fundamentals of the C programming language, including character sets, constants, identifiers, keywords, basic data types, variables, operators, control statements, and input/output functions. It also discusses the history of C, its applications in system programming, and the structure of a C program. Key concepts such as identifiers, keywords, constants, and data types are explained in detail, along with examples and best practices for programming in C.

Uploaded by

farhanafathimaam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Module 1.1 Character Set, Constants, Identifiers, Keywords, Basic Data Types, Variables

Module 1 covers the fundamentals of the C programming language, including character sets, constants, identifiers, keywords, basic data types, variables, operators, control statements, and input/output functions. It also discusses the history of C, its applications in system programming, and the structure of a C program. Key concepts such as identifiers, keywords, constants, and data types are explained in detail, along with examples and best practices for programming in C.

Uploaded by

farhanafathimaam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Module 1

Page 2
Module 1

► C Fundamentals C - haracter Set,Constants,Identifiers,Keywords,Basic Data types,


Variables,Operators and its precedence,
Bit-wise operators,Expressions; Statements -
Input and Output statements; Structure of a C program; Simple programs.

► Control Statements - if, if-else, nested if, switch, while, do-while, for, break & continue,
nested loops.

Page 3
Module 1

Dennis Ritchie and Ken Thompson were


Bell Labs engineers who collaborated to
develop the C programming language in
1967

Page 4
C Programming

C is widely used for "system programming", including implementing


operating systems and embedded system applications

Page 5
C Programming

Libraries and Interpreters of other programming languages are


implemented in C

Page 6
C Fundamentals

Page 7
Getting Started with C

Page 8
Character Set

► The character set in C programming refers to the set of valid characters that can
be used in the source code.

► It includes alphabets (both uppercase and lowercase), digits, special characters,


and white spaces.
Type of Character Description Characters
Lowercase Alphabets a to z a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z

Uppercase Alphabets A to Z A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z

Digits 0 to 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters – `~@!$#^*%&()[]{}<>+=_–|/\;:‘“,.?

White Spaces – Blank Spaces, Carriage Return, Tab, New Line

Page 9
Character Representation in C

► In C, characters are represented as American Standard Code for Information


Interchange (ASCII)
► ASCII system provides a standardized way to encode text as numbers, which
computers can process efficiently. Here’s why this approach is used
► C was developed in the early 1970s when ASCII was already an established
standard for text encoding.
► Characters that are displayed on the screen.
► Space (32): Blank space.
► Numbers (48–57): Digits 0–9.
► Uppercase Letters (65–90): A–Z.
► Lowercase Letters (97–122): a–z.
► Special Symbols (33–47, 58–64, 91–96, 123–126):Examples: !, @, #, [, }, etc.

Page 10 Visakh MESCET


Identifiers and Keywords in C

► In C, identifiers and keywords are fundamental concepts for defining and using
various elements of the language.

Page 11 VISAKH
Identifiers

► An identifier is the name used to identify variables, functions, arrays, or other


user-defined elements in a C program.
► Rules for Naming Identifiers
► Allowed Characters
► Can consist of alphabets (A–Z and a–z), digits (0–9), and underscores (_).
► Must start with a letter or an underscore (cannot begin with a digit).
► Case-Sensitive
► C is case-sensitive, so Variable and variable are considered different identifiers.
► Length
► The length of an identifier can vary depending on the compiler, but only the first 31
characters are generally significant in modern C standards.
► Keywords Restriction: Identifiers cannot use reserved keywords (e.g., int, return).

Page 12 VISAKH
Identifiers

► Examples of Valid Identifiers ► Examples of Invalid Identifiers


► Age ► 1stPlace (starts with a digit)
► total_sum ► total-sum (contains a special character -)
► _index ► float (reserved keyword)
► count1

Page 13 VISAKH
Keywords

► Keywords are predefined, reserved words in C that have specific meanings and
purposes. They cannot be used as identifiers.
► Characteristics of Keywords
► Reserved: Cannot be used for any other purpose.
► Lowercase Only: All C keywords are in lowercase.
► Fixed Meaning: The meaning of a keyword cannot be changed by the user.

Examples of Keywords
Category Keywords
Data Types int, float, char, double, void, long, short
Control Flow if, else, switch, case, default, for, while, do, break, continue, return
Modifiers signed, unsigned, const, volatile, static, auto, extern, register
Storage Classes static, extern, auto, register
Others sizeof, typedef, goto, enum, struct, union, typedef, inline

Page 14 VISAKH
Differences Between Identifiers and Keywords

Aspect Identifiers Keywords


Names given to variables, functions, Predefined reserved words with specific
Definition
arrays, etc. meanings in the language.
Yes, they are created by the
User-defined? No, they are fixed by the language.
programmer.
Case-sensitive (e.g., int is valid, but Int is
Case Sensitivity Case-sensitive (e.g., Age ≠ age).
not).
Examples name, total_sum, _index int, return, while, float

Page 15 VISAKH
Constants in C

► Constants are fixed values assigned to variables or directly used in a program.


Their value cannot be changed once defined.
Types of Constants in C
► Integer Constants: Whole numbers without decimal points.
► Can be in decimal, octal (prefix 0), or hexadecimal (prefix 0x) formats.

10 // Decimal
012 // Octal (Decimal 10)
0xA // Hexadecimal (Decimal 10)

► Floating-point Constants: Numbers with decimal points

3.14
2.71828

Page 16 VISAKH
Constants in C

Types of Constants in C
► Character Constants: A single character enclosed in single quotes

'A'
► String Constants: A sequence of characters enclosed in double quotes.

"Hello, World!"
► Symbolic Constants: Defined using the #define preprocessor directive or the const keyword.

#define PI 3.14159
const int MAX = 100;

Page 17 VISAKH
Variables in C
IT Park - 1
► An entity that may change its value during a
program execution.
► Why variables?
#453
► In computers,the data is stored in one or many
memory locations in the primary memory.
► Each memory location has a unique address. To
refer this data a name is assigned in a program. No 453 and IT Park – 1 refers to the same building
► This name assigned to a particular memory
location is called variable.

In programming languages, constants are often called


literals, whereas, variables are called identifiers.
A variable is a place holder for some kind of data

Page 18 VISAKH
Variable Naming Conventions

► studentName
► rollNumber
► employeeName
► simpleInterest
► dateOfBirth

Page 19 VISAKH
Data Types in C

► Data type determines the type of value that can be stored in variable
► C language has some predefined set of data types to handle various kinds o
data that we can use in our program.
► C language supports 2 different type of data types:
► Primary data types:
► These are fundamental data types in C namely integer(int), floating point(float),
character(char) and void.
► Derived data types:
► Derived data types are nothing but primary datatypes but a little twisted or grouped
together like array, structure, union and pointers. These are discussed in details late

Page 20 VISAKH
Integer Types (int)

► Integers are those numbers that do not contain a decimal point and
decimal digit.
► Examples : 17, 7890
► There are 3 integer data types supported by C language
► Short Integer(short)
► Integer(int)
► Long Integer(long)
► Each integer can be signed or unsigned
► Unsigned integer can store only positive values

Page 21 VISAKH
Integer Types (int)

► Size and range of Integer type on 32-bit machine:


Type Size(bytes) Range
int or signed int 4 -2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,967,295
short int or signed short int 2 -32,768 to 32767
unsigned short int 2 0 to 65535
long int or signed long int 8 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
unsigned long int 8 0 to 4,294,967,295
► The size of long and int may vary with the operating system and hardware platform
► For portability purpose, ‘long’ should be used for variables that holds larger value

Page 22 VISAKH
Integer Types (int)
► Examples
► short number1; unsigned long employeeId; int number2; unsigned int countPurchased;

Memory (RAM)

int a;
a =12 204

00001100
1210 = 1100
203
2
202 00000000
00000000 00000000 00000000 00001100201
00000000

200 00000000
byte 4 byte 3 byte 2 byte 1

integer value in memory

Page 23 VISAKH
Floating-Point Types (float and double)

► There are two types of floating point numbers:


► Double precision floating point number(double) – 8 Byte
► Single precision floating point number(float) – 4 Byte
► These data types are always signed
► Some Examples of declaring float and double data types are
► float salary;
► double totalProfit;
► double temperature;

Page 24 VISAKH
Floating-Point Types (float and double)
► Number that can have a fractional part
► Example
► 34.5, 7856.781
► In memory, a floating point number is stored as mantissa and exponent.

Sign – 1 bit
Exponent – 8 bit
Mantissa – 23 bit

Page 25 VISAKH
Character Types (char)

► The ‘char’ datatype in C can store a single character.


► C stores integer numbers instead of characters.
► In order to represent characters, the computer has to map each integer with a
corresponding character using a numerical code.
► The most common numerical code is ASCII, which stands for American Standard Code fo
Information Interchange.
► A character data type consumes 8 bits of memory which means you can store anything
a character whose ASCII value lies in between -127 to 127
► Example
► char choice;
► char grade = ‘A’;

Page 26 VISAKH
How character is stored in Computer

Page 27 VISAKH
Escape Sequences

► Many programming languages support a concept called Escape Sequence


► When a character is preceded by a backslash (\), it is called an escape
sequence and it has a special meaning to the compiler.

Escape Sequence Description


\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\' Inserts a single quote character in the text at this point.
\" Inserts a double quote character in the text at this point.

\\ Inserts a backslash character in the text at this point.

Page 28 VISAKH
Module 1

► C Fundamentals - Character Set, Constants, Identifiers, Keywords, Basic Data types,


Variables, Operators and its precedence, Bit-wise operators, Expressions; Statements -
Input and Output statements; Structure of a C program; Simple programs.

► Control Statements - if, if-else, nested if, switch, while, do-while, for, break & continue,
nested loops.

Page 3
The First C Program

Page 4
Do you Know?

Page 5 VISAKH MESCET


The First C Program

Page 6 VISAKH MESCET


File Header

Brief summary of what the code and file does, who created it, when etc….

Page 7 VISAKH MESCET


Include Libraries

► A header file is a file with extension .h which contains C function declarations and
macro definitions to be shared between several source files

► You request to use a header file in your program by including it with the C
preprocessing directive #include

► stdio.h - file contains standard library functions for input and output operations

Page 8 VISAKH MESCET


The main function

► Every computer program has an entry point.


► In C, the function main is the entry point of the program

► Although the function main with void main() works,


it is a bad programing practice
and it should be used with the signature int main()
► At the end of the main program zeros should be returned if the program performed it’s job
successfully and non zero indicates error.

Page 9 VISAKH MESCET


The printf function

► In C programming language, printf() function is used to print the (“character,


string,
float, integer, octal and hexadecimal values”) into the output screen.

Page 10 VISAKH MESCET


How c program is compiled and executed
Text Editor Source Code Header Files
Execution

Pre-Processor

Loader
Intermediate Code

Compiler
Run time
Libraries

Developer

Object Files
(.obj)
Linker Executable File

Page 11 VISAKH MESCET


Basic Input And Output In C

Page 12
Basic Input and Output in C

► Input and output are fundamental to interact with a program in C.


► The stdio.h (Standard Input/Output) library in C provides several functions to handle
these operations.

Page 13 VISAKH MESCET


Basic Input and Output in C
► Input is the process of taking data from the user and storing it in variables.
The most
commonly used function for input is scanf().
► The scanf() function reads input from the standard input (keyboard).
► It uses format specifiers to determine the type of data to read.

Syntax:scanf("format_specifier", &variable);

► format_specifier: Specifies the type of input (e.g., %d for integers, %f for floats).
► &variable: The address-of operator (&) is used to store the input at the variable's memory location.
► Output is the process of displaying information to the user.
The most commonly used function
for output is printf().
► Using printf()
► The printf() function writes output to the standard output (console).It also uses format specifiers
to specify the type of data to print.

Syntax: printf("text and format_specifiers", variable);

Page 14 VISAKH MESCET


Basic Input and Output in C

#include <stdio.h>
int main() { Format Descriptio Example Example
int age; Specifier n Input Output
float height; Integer
%d 42 42
(decimal)
printf("Enter your age: ");
scanf("%d", &age); Float/Dou
%f 3.14 3.140000
ble
printf("Enter your height: "); Float (2
%.2f 3.14 3.14
scanf("%f", &height); decimals)
%c Character A A
printf("You are %d years old and %.2f
meters tall.\n", age, height); %s String Hello Hello
Long
%ld 123456789 123456789
return 0; integer
} %lf Double 3.14159 3.141590

Page 15 VISAKH MESCET


Basic Input and Output in C

#include <stdio.h>
► Reading and Writing Characters: For int main() {
character-level input and output, char ch;
getchar(), putchar(), gets(), and
puts() can be used. printf("Enter a character: ");
ch = getchar(); // Read a single charact
► Using getchar() and putchar()
► getchar(): Reads a single character from printf("You entered: ");
the user. putchar(ch); // Print the character
► putchar():Prints a single character to printf("\n");
the console.
return 0;
}

Page 16 VISAKH MESCET


Basic Input and Output in C

► Reading and Writing Characters: For #include <stdio.h>


character-level input and output, int main() {
getchar(), putchar(), gets(), and char name[50];
puts() can be used.
printf("Enter your name: ");
► Using gets() and puts() // Read a string
► gets():Reads a string (deprecated due to fgets(name, sizeof(name), stdin);
).
buffer overflow risk; use fgets() instead printf("Hello, ");
► puts(): Prints a string. puts(name); // Print the string

return 0;
}

Page 17 VISAKH MESCET


Module 1

► C Fundamentals - Character Set, Constants, Identifiers, Keywords, Basic Data types,


Variables, Operators and its precedence, Bit-wise operators, Expressions; Statements -
Input and Output statements; Structure of a C program; Simple programs.

► Control Statements - if, if-else, nested if, switch, while, do-while, for, break & continue,
nested loops.

Page 3
Expressions

► An expression is a combination of operators and operands which


reduces to a single value.
► An operation is performed on a data item which is called an operand.
► An operator indicates an operation to be performed on data.
► For example, z = 3+2*1
► z=5

Page 4 VISAKH MESCET


Operators

► They are symbols that instruct the compiler to carry out specific computations or
manipulations.
► C programming language supports a rich set of operators that are classified as follows.
► Arithmetic Operators
► Relational Operators
► Logical Operators
► Increment & Decrement Operators
► Assignment Operators
► Bitwise Operators
► Conditional Operator
► Special Operators

Page 5 VISAKH MESCET


Arithmetic Operators (+, -, *, /, %)

► The arithmetic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication,
division and percentage modulo.
► The following table provides information about arithmetic operators.
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Remainder of the Division 5 % 2 = 1

Page 6 VISAKH MESCET


Arithmetic Operators (+, -, *, /, %)

Output

Program
Page 7 VISAKH MESCET
Relational Operators (<, >, <=, >=, ==, !=)
► The relational operators are the symbols that are used to compare two values.
► That means the relational operators are used to check the relationship
between two values.
► Every relational operator has two results TRUE or FALSE.

Page 8 VISAKH MESCET


Relational Operators (<, >, <=, >=, ==, !=)
Operator Meaning Example
Returns TRUE if the first value is smaller than
< 10 < 5 is FALSE
second value otherwise returns FALSE

Returns TRUE if the first value is larger than


> 10 > 5 is TRUE
second value otherwise returns FALSE

Returns TRUE if the first value is smaller than or


<= 10 <= 5 is FALSE
equal to second value otherwise returns FALSE

Returns TRUE if the first value is larger than or


>= 10 >= 5 is TRUE
equal to second value otherwise returns FALSE
Returns TRUE if both values are equal otherwise
== 10 == 5 is FALSE
returns FALSE
Returns TRUE if both values are not equal
!= 10 != 5 is TRUE
otherwise returns FALSE

Page 9 VISAKH MESCET


Relational Operators (<, >, <=, >=, ==, !=)

Output

Page 10 VISAKH MESCET


Logical Operators (&&, ||, !)
► The logical operators are the symbols that are used to combine multiple
conditions into one condition.
► The following table provides information about logical operators.

Operator Meaning Example


Logical AND - Returns TRUE if all conditions
&& 10 < 5 && 12 > 10 is FALSE
are TRUE otherwise returns FALSE
Logical OR - Returns FALSE if all conditions are
|| 10 < 5 || 12 > 10 is TRUE
FALSE otherwise returns TRUE
Logical NOT - Returns TRUE if condition is
! !(10 < 5 && 12 > 10) is TRUE
FLASE and returns FALSE if it is TRUE

Page 11 VISAKH MESCET


Increment & Decrement Operators(++,--)
► C programming has two operators increment ++ and decrement -- to change
the value of an operand (constant or variable) by 1.
► Increment ++ increases the value by 1 whereas decrement -- decreases the
value by 1.
► These two operators are unary operators, meaning they only operate on a
single operand.

Page 12 VISAKH MESCET


Example : Increment and Decrement Operators

Page 13 VISAKH MESCET


Increment & Decrement Operators(++,--)
► Pre-increment and Post-increment
► Pre-increment operator: A pre-increment operator is used to increment the
value of a variable before using it in a expression.
► In the Pre-Increment,value is first incremented and then used inside the
expression.
► Syntax: a = ++x;

► Here, if the value of ‘x’


is 10 then value of ‘a’
will be 11 because the value of
‘x’gets modified before using it in the expression.

Page 14 VISAKH MESCET


Increment & Decrement Operators(++,--)
► Pre-increment and Post-increment
► Post-increment operator: A post-increment operator is used to increment the value
of variable after executing expression completely in which post increment is used.
► In the Post-Increment, value is first used in a expression and then incremented.
► Syntax: a = x++;
► Here, suppose the value of ‘x’
is 10 then value of variable ‘b’
will be 10 because old
value of ‘x’is used.

Page 15 VISAKH MESCET


Assignment Operators (=)
► An assignment operator is used for assigning a value to a variable.
► The most common assignment operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

Page 16 VISAKH MESCET


Example : Assignment Operators

Page 17 VISAKH MESCET


Bitwise Operators
► In arithmetic-logic unit (which is within the CPU), mathematical operations like:
addition, subtraction, multiplication and division are done in bit-level.
► To perform bit-level operations in C programming, bitwise operators are used.

Operators Meaning of operators

& Bitwise AND


| Bitwise OR

^ Bitwise XOR

~ Bitwise complement

<< Shift left

>> Shift right

Page 18 VISAKH MESCET


Bitwise AND operator (&)
► The output of bitwise AND is 1 if the
corresponding bits of two operands is 1.
► If either bit of an operand is 0, the result of
corresponding bit is evaluated to 0.
► Let us suppose the bitwise AND operation of two
integers 12 and 25.

Page 19 VISAKH MESCET


Bitwise OR operator (|)
► The output of bitwise OR is 1 if at least one
corresponding bit of two operands is 1.
► In C Programming, bitwise OR operator is
denoted by |.

Page 20 VISAKH MESCET


Bitwise XOR (exclusive OR) operator (^)
► The result of bitwise XOR operator is 1 if the
corresponding bits of two operands are
opposite. It is denoted by ^.

Page 21 VISAKH MESCET


Shift Operators
► There are two shift operators in C programming:
► Right shift operator
► Left shift operator.
► Right Shift Operator
► Right shift operator shifts all bits towards right by certain number of specified bits. It
is denoted by >>.

Page 22 VISAKH MESCET


Shift Operators
► There are two shift operators in C programming:
► Right shift operator
► Left shift operator.
► Left Shift Operator
► Left shift operator shifts allbits towards left by a certain number of specified bits.
The bit positions that have been vacated by the left shift operator are filled with 0.
The symbol of the left shift operator is <<.

Page 23 VISAKH MESCET


Conditional Operator in C ( ?: )
► The conditional statements are the decision-making statements that depend
upon the output of the expression.
► As a conditionaloperator works on three operands,so it is also known as the
ternary operator.
► It starts with a condition; hence it is called a conditional operator.
► Conditional operators return one value if condition is true and returns another
value is condition is false.
► Syntax
► expression1 ? expression2 : expression3;
► or for simplicity, we write it as condition ? true-statement : false-statement;

Page 24 VISAKH MESCET


Conditional Operator ( ?: ) - Example

Page 25 VISAKH MESCET


Conditional Operator in C ( ?: ) - Example
► Write a C Program to input a number from the keyboard and check whether number is
positive or negative using the conditional operator.

Page 26 VISAKH MESCET


Conditional Operator ( ?: ) - Exercises
► Find the given number is odd or even using the conditional operator in C.

► Program to Find the minimum of two numbers using the conditional operator.

► Write a C Program to find largest among three numbers using the conditional
operator.

Page 27 VISAKH MESCET


Special Operators
Comma Operator
► The comma operator in C allows multiple expressions to be evaluated in a single
statement.
► It evaluates the expressions from left to right and returns the value of the last
expression.
► The comma operator is primarily used to combine multiple expressions into one.

#include <stdio.h>
int main() {
int a, b, result;

a = (b = 5, b + 10); // Comma operator in action ► In a = (b = 5, b + 10);


printf("a = %d\n", a); // Output: a = 15 ► b = 5 is executed first.
► Then b + 10 is executed.
result = (a = 10, b = 20, a + b); ► The value of b + 10 (i.e., 15) is assigned to
printf("result = %d\n", result); // Output: result = 30

return 0;
}

Page 28 VISAKH MESCET


Special Operators
► The sizeof operator
► The sizeof is a unary operator that returns the size of data (constants,
variables, array, structure, etc).

Page 29 VISAKH MESCET


Operators Precedence

x = 34 + 12 / 4 - 45
► Operator precedence determines the grouping of terms in an
expression and decides how an expression is evaluated.
► Certain operators have higher precedence than others

Page 30 VISAKH MESCET


Operators Precedence table in C

Page 31 VISAKH MESCET


Operators Precedence in C

Page 32 VISAKH MESCET


Typecasting in C
► Typecasting is converting one data type into another one.
► It is best practice to convert lower data type to higher data type to avoid
data loss.
► Data will be truncated when the higher data type is converted to lower.
► For example,if a float is converted to int,data which is present after the decimal
point will be lost.
► C programming provides two types of type casting operations:
► Implicit type casting
► Explicit type casting

Page 33 VISAKH MESCET


Implicit Type Conversion
► Also known as ‘automatic type
conversion’.
► Done by the compiler on its own,
without any external trigger from the
user.
► Generally, takes place when in an
expression more than one data type is
present.
► In such condition type conversion (type
promotion) takes place to avoid loss of
data.
► All the data types of the variables are
upgraded to the data type of the
variable with largest data type.
Page 34 VISAKH MESCET
Implicit Type Conversion

Page 35 VISAKH MESCET


Explicit type casting
► In implicit type conversion, the data type is converted automatically.
► There are some scenarios in which we may have to force type
conversion.
► Suppose we have a variable div that stores the division of two operands
which are declared as an int data type.
► int result, var1=10, var2=3;
► result=var1/var2;
► fraction part which is normally obtained in the division of two numbers
► To force the type conversion in such situations, we use explicit type
casting.
► Syntax
► (type-name) expression

Page 36 VISAKH MESCET


Explicit type casting

Explicit Type Higher


Lower Conversion
Data Type Data Type

Page 37 VISAKH MESCET


Explicit type casting

Page 38 VISAKH MESCET


Module 1

► C Fundamentals - Character Set, Constants, Identifiers, Keywords, Basic Data types,


Variables, Operators and its precedence, Bit-wise operators, Expressions; Statements -
Input and Output statements; Structure of a C program; Simple programs.

► Control Statements - if, if-else, nested if, switch, while, do-while, for, break & continue,
nested loops.

Page 3
Control Flow Statements

Page 4
Control Structures

► The way in which the programmer specifies the order of execution of the
statements.
► Different set of statements can be executed based on a condition.
► Sequential
► Selection
► Iteration (Repetition)

Page 5
Selection Control Structures

► There are two selection control structures supported by C language


► ‘if s
’ tatement
► ‘switch’statement

Page 6
Simple If Statement

► A condition is tested, if it true, a set of statements


executed.
► Syntax of an if statement

if (Condition) { True
Condition
statement(s);
}
Next Statement; False Set of Statement(s)

Next Statement

Page 7
Simple If Statement - Example

► In a banking example,if the duration of the deposit is 3 years and above


the interest rate for the deposit is 6%

if (duration>=3) {
rateOfInterest = 6.0;
}

Page 8
Simple If Statement

► Points to Remember:
► The if statement does not end with a semicolon
► Only statements follows the if, should end with a semicolon

Amateur Code Professional Code


if(duration>=3) if(duration>=3){
printf(“Interest: 6.0%”); printf(“Interest: 6.0%”);
}

Page 9
If…… Else Statement

► If the condition returns true,the statements inside the body of


the “if” block are executed, and the statements inside the body
of the “else” block are skipped.
► If the condition returns false,
the statements inside the body of
the “if” block are skipped,and the statements inside the “else”
block are executed.
► Syntax of an if ..else statement False
Condition
True

if (Condition) {
True statement(s);
} False Statement(s) True Statement(s)
else{
False statement(s);
Next Statement
}
Next Statement;

Page 10
If…… Else Statement- Example

► In a banking example,if the duration of the deposit is 3 years and above


the interest rate for the deposit is 0.6%, otherwise it is 5.5%

if (duration>=3) {
rateOfInterest = 6.0;
}
False Duration> True
else{ =3
rateOfInterest = 5.5;
} rateOfInterest = 6.0
rateOfInterest = 5.5

Next Statement

Page 11
Else… If Statement
► The else..if statement is to check for a if (test - expression 1) {
sequence of conditions. statement1;
} else if (test - expression 2){
► When one condition is false, it checks for the Statement2;
next condition and so on. } else if (test - expression 3){
► When all conditions are false the ‘else’
block Statement3;
} else if (test - expression n){
is executed. Statement n;
} else {
default;
False False False
condition -1 condition -2 condition -n
}
Statement x;
True True
True

Statement(s) 1 Statement(s) 2 Statement(s) n Statement(s) x

This type of structure is known


Next Statement(S) as the else-if ladder.

Page 12
Else… If Statement

Always use ‘else if’ when a sequence of conditions has to b


Using only ‘if’ will make the compiler to check all the condit
increases the execution time.

Page 13
Else… If Statement

Amateur Code Professional Code


if(duration>=6){ if(duration>=6){
rateOfInterest=6.5; rateOfInterest=6.5;
} }
if((duration>=3)&& (duration<6)){ else if(duration>=3){
rateOfInterest=6.0; rateOfInterest=6.0;
} }
if(duration==2) { else if(duration==2){
rateOfInterest=5.5; rateOfInterest=5.5;
} }
if(duration==1) { else{
rateOfInterest=5.0; rateOfInterest=5.0;
} }

Page 14
Nested if
► If an ‘if’statement embedded within another statement
‘if’ is called nested if
► Syntax
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Page 15
switch case statement
► Switch statement is a controlstatement that switch(expression)
allows us to choose only one choice among {
case value-1:
the many given choices.
block-1;
► The expression in switch evaluates to return break;
an integral value,which is then compared to case value-2:
the values present in different cases. block-2;
► It executes that block of code which matches break;
case value-n:
the case value.
block-n;
► If there is no match, then default block is break;
executed(if present). The general form of default:
switch statement is, default-block;
break;
}

Page 16
Rules for using switch statement

► The expression (after switch keyword)must yield an integer value i.e the
expression should be an integer or a variable or an expression that
evaluates to an integer.
► The case label values must be unique.
► The case label must end with a colon(:)
► The next line, after the case statement, can be any valid C statement.

Page 17
switch statement Example

/*prints the roles associate with a job code*/


switch(jobCode){
case 1:
printf(“Your role is Manager”);
break;
case 2:
printf(“Your role is Relationship Manager”);
break;
case 3:
printf(“Your role is Teller”);
break;
default:
printf(“Invalid Job Code”);
break;
}

Page 18
switch case statement

► Points to Remember:
► We don't use those expressions to evaluate switch case,which may
return floating point values or strings or characters.
► break statements are used to exit the switch block.
► It isn't necessary to use break after each block, but if you do not use it,
then all the consecutive blocks of code will get executed after the
matching block.
► default case is executed when none of the mentioned case matches
the switch expression. The default case can be placed anywhere in the
switch case. Even if we don't include the default case, switch statement
works.

Page 19
switch case statement

► Points to Remember:
► if statements can evaluate float conditions.
switch statements cannot
evaluate float conditions.
► if statement can evaluate relational operators. switch statement cannot
evaluate relational operators i.e they are not allowed in switch
statement.

Page 20
switch statement

Amateur Code Professional Code


if(itemCategory==1){ switch(itemCategory){
printf(“Vegetables”); case 1:
} printf(“Vegetables”);
else if(itemCategory==2){ break;
printf(“Stationary”); case 2:
} printf(“Stationary”);
else if(itemCategory==3){ break;
printf(“Food Items”); case 3:
} printf(“Food Items”);
else{ break;
printf(“Invalid Code”); default:
} printf(“Invalid Code”);
break;
}

Page 21

You might also like