Unit 2
Unit 2
Syllabus:
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 can have a positive or negative sign. In case it doesn’t have any sign it is taken as positive.
➢ The part before the ‘e’ is known as mantissa and the part after the ‘e’ is known as exponent.
• The mantissa and the exponential part should have a letter ‘e’ between them.
• It can have a positive or negative sign. In case it doesn’t have any sign it is taken as positive.
A Character Constant is a single alphabet, digit or special character enclosed within ‘single quotes’.
quotes”. Have a look at the rules that guide the construction of String Constants:
➢ There are some characters which are impossible to enter into a string from keyboard like backspace,
➢ 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.
The header file “limits.h” is used to find minimum and maximum constants of integer and character data type.
Syntax:
data_type variable_name = value; // defining single variable
or
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
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.
➢ 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 called as binary operators. Operators that operate or work with two
operands are binary operators.
Relational Operator:
➢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 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
+= 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.
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
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 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
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;
• 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
➢ 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:
➢ 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
➢ 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.
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.
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.
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.
➢ 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.
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.
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
given condition.
advance.
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
least once.
contained within. It allows the program to exit the loop or switch and
➢ The break statement shall appear only in the “switch” or “loop”. The
➢ 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
➢ 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
➢ To jump from one line to another line, the goto statement requires a label. Label is a name given to the
➢ 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
Syntax:
➢ We can only return a single value from a function using return statement. To return multiple values, we can