0% found this document useful (0 votes)
44 views36 pages

Maksks ODULE 2 - POP - Notes

Ffff

Uploaded by

deekshitar25
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)
44 views36 pages

Maksks ODULE 2 - POP - Notes

Ffff

Uploaded by

deekshitar25
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/ 36

MODULE 2

Lesson 1: Operators and Type Conversions


Expressions
• An expression is a combination of constants and variables interconnected by one or
more operators.
• An expression consists of one or more operands and one or more operators.
Examples:
1. num1 + num2 // variables num1 and num2 are operands and + is the operator used.
2. x = y // the assignment operator (=) is used to assign the value stored in y to x.
3. a = b + c // the value of the expression (b + c) is assigned to a.
4. x <= y // the lesser-than-equalTo (<=) the relational operator compares the values
of x and y and returns either 1 (true) or 0 (false).
5. a++ // the value of variable a is incremented by 1 i.e, this expression is equivalent to a = a
+ 1.
Expressions can also represent logical conditions which are either true or false. In C, the
conditions true and false are represented by the integer values 1 and 0 respectively.
Statements
• A program is a collection statements.
• A statement is an instruction given to the computer to perform an action.
There are three different types of statements in C:
1. Expression Statements
2. Compound Statements
3. Control Statements
1. Expression Statements
An expression statement or simple statement consists of an expression followed by a semicolon
(;).
Given below are few examples of expression statements:
a = 100;
b = 20;
c = a / b;
2. Compound statement
A compound statement, also called a block, consists of several individual statements enclosed
within a pair of braces { } .
For example:
{
a = 3;
b = 10;
c = a + b;
}
3. Control Statements
A single statement or a block of statements can be executed depending upon a condition
using control statements like if, if-else, etc.
Example for if control statement:
a = 10;
if (a > 5) {
b = a + 10;
}
Operators
An operator is a special symbol used to manipulate data. The data items that the operators act
upon are called operands.
The operator that works on a single operand is called a unary operator and that which works on
two operands is known as a binary operator.
Types Of Operators
1. Arithmetic operator
Arithmetic operators are applied on numeric operands. Thus, the operands can
be integers, floats or characters (Since a character is internally represented by its numeric code).

Operator Description

+ Used for addition

- Used for subtraction

* Used for multiplication

/ Used for division

% Remainder/Modulus operator for finding remainder

Example:
#include<stdio.h>
void main(){
int num1=10, num2=3;
printf("Addition Result = %d\n", (num1 + num2));
printf("Subtraction Result = %d\n", (num1 - num2));
printf("Multiplication Result = %d\n", (num1 * num2));
printf("Division Result = %d\n", (num1 / num2));
printf("Remainder = %d\n", (num1 % num2));
}
Output:
Addition Result = 13
Subtraction Result = 7
Multiplication Result = 30
Division Result = 3
Remainder = 1
Arithmetic operators -mixed data types
Arithmetic operators can be used in expressions with operands of different data types.

For example: the addition operator (+) can be used on int and float data types with the result being
a float data type.

If the same is performed on float and double data types, the result will be a double data type, i.e.,
the result will always be of the data type with the highest memory capacity.

Consider the following examples with different combinations of arithmetic operators and data
types.

Expression Result Description

2 + 2.5 4.500000 int + float = float

'A' + 10 75 char + int = int

5.9 + 4.67L 10.570000 float + long double = long double


Example:
#include <stdio.h>
void main() {
printf("Result1 = %f\n", (2 + 2.5));
printf("Result2 = %d\n", ('A' + 10));
printf("Result3 = %Lf\n", (5.9 + 4.67L));
}
Output:
Result1 = 4.500000
Result2 = 75
Result3 = 10.570000

2. Relational and equality operators


Relational and equality operators are used to test or compare two numeric values or numeric
expression.
Relational and equality operators when applied on the operands, produce an integer value which
is either 0 or 1.
There are four relational and two equality operators as given below:

Operator Description

> Checks for greater-than condition

>= Checks for greater-than-or-equals condition

< Checks for less-than condition

<= Checks for less-than-or-equals condition.

== Checks if two values are equal

!= Checks if two values are unequal

The table given below demonstrates the use of various relational and equality operators using
variables
int num1 = 7;
float num2 = 5.5;
char ch = 'w';

Expression Interpretation Result Value

(num1 > 5) true 1

((num1 + num2) <= 10) false 0

(ch == 119) true 1

(ch != ’p’) true 1

(ch >= 10 * (num1 + num2)) false 0

Example:
#include <stdio.h>
void main() {
int num1 = 7;
float num2 = 5.5;
char ch = 'w';
printf("Result1 = %d\n", (num1 > 5));
printf("Result2 = %d\n", ((num1 + num2) <= 10));
printf("Result3 = %d\n", (ch == 119));
printf("Result4 = %d\n", (ch != 'p'));
printf("Result5 = %d\n", (ch >= 10 * (num1 + num2)));
}
Output:
Result1 = 1
Result2 = 0
Result3 = 1
Result4 = 1
Result5 = 0
3. Logical Operator
Logical operators are used to perform logical operations on the given expressions.
An expression containing a logical operator returns either 0 (or) 1 depending on the evaluation of
the expression to either false or true respectively.
Given below are the three logical operators in C:

Operator Description Meaning

logical
&& It returns true when both conditions are true, else, it returns false
AND

|| logical OR It returns true if atleast one of the conditions is true

logical It returns true when the given expression is false and returns false when
!
NOT the given expression is true

The below table demonstrates the use of various relational and equality operators using variables
int num1 = 7;
float num2 = 5.5;
char ch = 'w';

Expression Interpretation Result Value

(num1 >= 6) && (ch == ’w’) true 1

(num2 < 11) && (num1 > 100) false 0

(ch != ’p’) || ((num1 + num2) <= 10) true 1

!(num1 > (num2 + 1)) false 0

!(num1 <= 3) true 1

Example:
#include <stdio.h>
void main() {
int num1 = 7;
float num2 = 5.5;
char ch = 'w';
printf("Result1 = %d\n", ((num1 >= 6) && (ch == 'w')));
printf("Result2 = %d\n", ((num2 < 11) && (num1 > 100)));
printf("Result3 = %d\n", ((ch != 'p') || ((num1 + num2) <= 10)));
printf("Result4 = %d\n", !(num1 > (num2 +1)));
printf("Result5 = %d\n", !(num1 <= 3));
}
Output:
Result1 = 1
Result2 = 0
Result3 = 1
Result4 = 0
Result5 = 1

4. Unary Operators
• no space should be provided between a unary operator and the operand.
• While using a unary minus operator, a - sign precedes a single operand. The result is a
negative value of the operand. It is the same as multiplying the operand by -1.
• While using a unary plus operator, a + sign precedes a single operand. It is the same as
multiplying the operand by the constant 1.

Operator Description

+ Unary Plus, used for indicating a positive value

- Unary Minus, used for indicating a negative value

++ Increment operator - Increments the value by one

-- Decrement operator - Decrements the value by one

A few examples of unary plus and unary minus are : -125, -a, -(a + b), +5, +x, +(a * b), +0xAB5.

Prefix operators
When the operators ++ or -- appear before the operands, they are called as the prefix operators.
Postfix operators
When the operators ++ or -- appear after the operands, they are called as the postfix operators.
Pre-increment operator
When an increment (++) is used as a prefix (i.e., applied before an operand) for example, as ++i
the value of the operand is changed first. The changed value is then substituted in the expression.
#include<stdio.h>
void main(){
int x =14; //Initialize integer variable x with a value of 14
int y = ++x; // ++x increments x by 1, making x = 15. The incremented value (15) is then. assigned
to y, so y = 15.
printf("x value : %d", x);/ / Print the current value of x, which is now 15
printf("y value : %d", y);// Print the current value of y, which is also 15
++x;// x is incremented by 1 again, making x = 16.
printf("x value : %d", x); // Print the updated value of x, which is now 16
}
Output:
x value : 15
y value : 15
x value : 16
Pre-decrement operator
When an decrement (--) operator is used as a prefix (i.e., applied before an operand) for example,-
-i, the value of the operand is changed first. The changed value is then substituted in the expression.
#include<stdio.h>
void main(){
int x = 14;//Intialize integer variable x with a value of 14
int y = --x; // --x decrements x by 1, making x = 13, the decremented value(13) is then assigned to
y, so y = 13
printf("x value : %d\n", x); //print the current value of x, which is now 13
printf("y value : %d\n", y); //print the current value of y, which is also 13
--x; // x is decremented by 1 again, making x = 12
printf("x value : %d\n", x); // print the updated value of x, which is now 12
}
Output:
x value : 13
y value : 13
x value : 12
Post-increment operator
When an increment (++) operator is used as a postfix (i.e.,applied after an operand) for example,
as, i++ the original value of the operand is first substituted in the expression and then the value
stored in the operand is changed.
#include<stdio.h>
void main(){
int x = 14; //Initialize integer variable x with declare a value 14
int y = x++; // Post-increment x (y is assigned the current value of x, then x is incremented) Here,
y = 14, and then x becomes 15
printf("x value : %d", x); );//print the current value of x, which is now 15
printf("y value : %d", y);//print the current value of y, which is 14 (value of x before incrementing)
x++; // Post-increment x again (x becomes 16)
printf("x value : %d", x); // Print the updated value of x, which is now 16
}
Output:
x value : 15
y value : 14
x value : 16

Post-decrement operator
When an a decrement (--) operator is used as a postfix (i.e.,applied after an operand) for example, i-
-, the original value of the operand is first substituted in the expression and then the value stored in
the operand is changed.
#include<stdio.h>
void main(){
int x = 14; //Initialize integer variable x with declare a value 14
int y = x--; // Post-decrement x (y is assigned the current value of x, then x is decremented) Here, y
= 14, and then x becomes 13
printf("x value : %d\n", x);//print the current value of x, which is now 13
printf("y value : %d\n", y); //print the current value of y,which is now 14
x--; // Post-decrement x again (x becomes 12)
printf("x value : %d\n", x); // Print the updated value of x, which is now 12
}
Output:
x value : 13
y value : 14
x value : 12
5. Assigment operator
LHS = RHS; (or) L-value = R-value;
The LHS (left-hand side) of the = operator has to be a variable. The RHS (right-hand side) can be a
value, a variable or an expression.
For Example:
#include<stdio.h>
void main(){
int x, y, z;
x = 10; // variable x is assigned a value 10
y = 20; // variable y is assigned a value 20
z = x + y; // variable z is assigned the result of the expression x + y
}
Compound Assignment Operators
Compound assignment operators which are a combination of various operators and a single
assignment operator as shown below:
+=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=

The format of a compound assignment operator is:


variable operator= expression;
The code given below demonstrates the usage of += and -=:
int x = 3, y = 4, z = 0;
z += x; // is same as writing z = z + x;
z -= y; // is same as writing z = z - y;
6. Ternary operator
Ternary operator needs exactly three operands to compute the result.

The syntax for using a ternary operator is:


condition? expression1: expression2;
The condition should always evaluate to 1 (true) or 0 (false). If the condition evaluates to true,
then expression1 is evaluated and its value is returned, otherwise expression2 is evaluated and its
value is returned.
Example 1:
#include <stdio.h>
int main () {
int marks = 75, pass_marks = 50;
(marks > pass_marks) ? printf("Passed C Certification") : printf("Failed C Certification");
return 0;
}
Output:
Passed C Certification
Explanation:
Use the ternary operator to check if marks are greater than pass_marks , If marks > pass_marks,
print "Passed C Certification", otherwise print "Failed C Certification"
Example 2:
#include <stdio.h>
void main() {
int num1 = 20, num2 = 25, large;
large = (num1 >num2) ?num1 :num2; \\If num1 is greater than num2, large is assigned the
value of num1, otherwise num2
printf("Largest number = %d\n", large);
}
Output:
Largest number = 25
7. Bitwise operators
Bitwise operators are used to manipulate data at bit level (binary data).
There are Six Bitwise Operators as given below:

Operator Description
& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR (XOR)

<< Bitwise Left shift

>> Bitwise Right shift

~ One's Complement

1. Bitwise AND Operator (&)

It sets a bit to 1 if and only if both the corresponding bits in its operands are 1, and to 0 if
the bits differ or both are 0.
The format for using a Bitwise AND (&) operator is:
operand1 & operand2
where operand1 and operand2 should be of integral type.
Example : 1010 & 1100 will result in 1000.
10 ⟹ 1010
&
12 ⟹ 1100
1000 ⟹ 8
2. Bitwise OR operator (|)
It sets a bit to 1 if one or both the bits in its operands are 1, and to 0 if both
The bits are 0.
The format for using a Bitwise OR (|) operator is:
operand1 | operand2
where operand1 and operand2 should be of integral type.
For example, 1010 | 1100 will result in 1110.
10 ⟹ 1010
|
12 ⟹ 1100
1110 ⟹ 14

3. Bitwise XOR operator (^)


It sets the bit to 1 where the corresponding bits in its operands are different, and to 0 if
they are the same.
The format for using a Bitwise XOR (^) operator is:
operand1 ^ operand2
where operand1 and operand2 should be of integral type.

For example, 1010 ^ 1100 will result in 0110.

10 ⟹ 1010
^
12 ⟹ 1100
0110 ⟹ 6

4. Bitwise Left Shift operator (<<)

Syntax for using a bitwise left-shift (<<) operator is:


operand1 << operand2

where operand1 should be of integral type and operand2 should also be an integral number
which indicates the number of positions that should be shifted to the left in operand1.
The value of number << bits to be shifted is number left-shifted by bits to be shifted bit
positions. This is equal to multiplying operand1 by 2bitstobeshifted .

Example: 3<<2
Binary value of 3 is 011
3 << 2 will result in 1100
i.e, 3 << 2 = 3 X 22 = 12.

5. Bitwise Right Shift operator (>>)


The syntax for using a bitwise right-shift (>>) operator is:
operand1 >> operand2
Where operand1 should be of integral type and operand2 should also be an integer which
indicates the number of bits that should be shifted to the right in operand1.
The value of number >> bits to be shifted is number right-shifted by
bits to be shifted bit positions while preserving the sign. The resulting value is equal to the
rounded up value of number / 2bitstobeshifted.
For non-negative values of number, this is equivalent integer division, i.e. number /
2bitstobeshifted.
Example: 15>>2
Binary value of 15 is 1111
15 >> 2 will result in 0011,
i.e, 15 >> 2 = 15 / 22 = 3.

Example for Bitwise AND, OR and XOR Operators


#include<stdio.h>
void main() {
int num1 = 10, num2 = 12, result;
printf("Bitwise AND result = %d\n", num1 & num2);
printf("Bitwise OR result = %d\n", num1 | num2);
printf("Bitwise XOR result = %d\n", num1 ^ num2);
}
Output:
Bitwise AND result = 8
Bitwise OR result = 14
Bitwise XOR result = 6

Example for Left-shift and Right-shift Operators


#include <stdio.h>
void main() {
int num1 = 15, num2 = 3, result1, result2;
result1 = num1 << num2; //Use bitwise Left-shift operator
result2 = num1 >> num2; //Use bitwise Right-shift operator
printf("Bitwise Left shift result = %d\n", result1);
printf("Bitwise Right shift result = %d\n", result2);
}

Output:
Bitwise Left shift result = 120
Bitwise Right shift result = 1

6. Bitwise One’s Complement operator (~)


The format for usage of one's complement (~) operator is:
~operand
where operand should be of primitive integral type.
This operator works on the binary representation of the given number.
It converts all the 1's to 0's and 0's to 1's respectively.
For example: if the ~ operator is applied to the binary number 110, the result will be 001.
Example:
#include <stdio.h>
void main() {
int num = 22, result;
result = ~num; //Use bitwise one's complement operator
printf("Bitwise one's complement result = %d\n", result);
}
Output:
Bitwise one's complement result = -23

Special Operators
Comma Operator
The Comma(,) operator is used to declare multiple expressions in a single statement.
Comma operator acts as a separator between multiple expressions, in declaring multiple
variables and in function call parameters.
In the expression result = (expression1, expression2);
expression1 is first evaluated. After that, expression2 is evaluated and the value of
expression2 is returned for the whole expression.
Example:
#include <stdio.h>
void main() {
int num1, num2, result;
result = (num1 = 5, num2 = num1 + 10, num1 + num2);
printf("Result = %d\n", result);
}
Output:
Result = 20
Sizeof Operator
sizeof operator is also called compile-time operator and when used with an operand, will
return the number of bytes that are occupied by the operand..

The operand may be a variable, a constant or a data type.

The format of sizeof operator is:


sizeof(operand)

sizeof operator will return the size as an unsigned integer.

Since sizeof returns an unsigned integer, %zu has to be used instead of %d for the format
string.
Example:
#include <stdio.h>
void main() {
float floattype;
double doubletype;
char chartype;
int inttype;
printf("Size of int: %zu bytes\n", sizeof(inttype));
printf("Size of float: %zu bytes\n", sizeof(floattype));
printf("Size of double: %zu bytes\n", sizeof(doubletype));
printf("Size of char: %zu byte\n", sizeof(chartype));
}
Output:
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte

Precedence and Associativity of operators


When several operators appear in one expression, evaluation takes place according to
certain predefined hierarchical rules.
These rules specify the order of evaluation (also called precedence) which determines the
priority of operators.
The operator with higher precedence is evaluated before others with lesser precedence.

Operator Precedence and Associativity Table

Precedence
Operator Operation Associativity
level

Functional
() cell(or)
Parentheses
[]
1 Array subscript Left to Right
.
Dot
--->
Arrow

Logical NOT
!
One's
~ compliment
- Unary minus
++ Increment
2 -- Decrement Right to Left
& Address of
* Indirection
(data_type) Cast oparator
sizeof() sizeof special
operator

* Multiplication
3 / Division Left to Right
% Modulus

+ Addition
4 Left to Right
- Subtraction

5 << Left shift Left to Right


>> Right shift

Less than
<
Greater than
>
6 Less than or Left to Right
<= equal to
>= Greater than or
equal to

== Equal to
7 Left to Right
!= Not equal to

8 & Bitwise AND Left to Right

9 ^ Bitwise XOR Left to Right

10 | Bitwise OR Left to Right

11 && Logical AND Left to Right

12 || Logical OR Left to Right

13 ?: Conditional Right to Left

= += -= *=
/= %= Simple and
14 compound Right to Left
>>= <<== assignment
&= ^= |=

15 , Comma Left to Right

Consider the following expression: a = 2 + 3 * 4 - 4 / 2 + 6. It is evaluated depending on


the precedence rules of the operators.
a=2+3*4-4/2+6 // 3 * 4 is evaluated first because * and / have the highest precedence
a = 2 + 12 - 4 / 2 + 6 // 4 / 2 is evaluated next.
a = 2 + 12 - 2 + 6 // +, - are evaluated simultaneously since both the
operators have the same precedence
a = 18

Example :
#include <stdio.h>
void main() {
int a = 2 + 3 * 4 % 8 - 5 / 4;
printf("a = %d\n", a);
}
Output:
5

Type Conversions
• Type conversion is performed to convert one or both the operands to an appropriate data
type before evaluation.
• Type conversion means converting one data type value into another data type value.

There are two types of type conversions:


1. Implicit conversion (also called type coercion)
2. Explicit conversion (also called type casting)

1. Implicit Conversion
Implicit type conversion, the compiler automatically converts one data type value into another
data type value.
Implicit type conversions can occur during assignment or while using any other operators. during
assignment, the R-value is converted to the type of L-value.
Conversion order
char ⟹ short int ⟹ int ⟹ long ⟹ float ⟹ double ⟹ long double
For example: The statement float a = 5 + 5.6; integer type value 5 is automatically converted into
a float type as 5.0 before the addition is performed.
Example:
#include <stdio.h>
void main() {
int i , intsum;
printf("i = ");
scanf("%d\n",&i);// read value of i
char ch = 'a'; // assing character 'a' to ch
float floatsum;
intsum = i+ch; // add values of i and ch
floatsum = i+ch; // add values i and ch
printf("Integer result = %d, Float result = %f\n",intsum,floatsum); // print intsum and
floatsum values and observe the output
}
Output:
i = 20
Integer result = 117, Float result = 117.000000
i = 115
Integer result = 212, Float result = 212.000000
2. Explicit Conversion
A programmer can instruct the compiler to explicitly convert a value of one type to another using
a typecast operator.

When a typecast operator is used explicitly, the type conversion process is called explicit type
conversion or type casting.

Syntax for using a typecast operator is:


(data_type) expression
where the expression is converted to the target data_type enclosed within the parentheses.
Here, the expression may contain constants or variables and the data_type must be a primitive
data type or void.

For example: The expression (float)1 / 3 is evaluated as 1.0 / 3 yielding 0.333333


where as 1 / 3 yields 0.

In the expression ((int)num)%2, if num is a float variable with value 5.5, then the expression
evaluates to 1. Given below is an example which demonstrates type casting:
Example:
#include <stdio.h>
void main() {
float x, y;
x = 7 / 5;
y = (float)7 / 5; // Convert the int value explicitly into float
printf("x = %f, y = %f\n", x, y);
}
Output:
x = 1.000000, y = 1.400000
Lesson 2: Conditional Statements

Conditional Statements
A special statement to control the execution of one or more statements depending on a
condition. Such statements are called as control statements or control-flow statements.
There are three types in control-flow statements:
1. Selection Statement - is a statement whose execution results in a choice being made as to
which of two or more paths should be followed.
1. if construct
2. if-else construct
3. if-else-if construct
4. Nested if-else-if construct
5. switch-case construct
2. Iterative / Looping Statement - is a statement which executes a set of statements repeatedly
depending on a condition.
1. while loop
2. do-while loop
3. for loop
3. Unconditional Control Statement - is a statement which transfers control-flow to some
other section of the program without the need of a condition.
1. break statement
2. continue statement
3. goto statement

1. Selection Statement
1. if construct:
The if construct is a selective statement, if statement will execute its block only
when condition evaluates to 1 (true), otherwise the control goes to the first statement
after the if construct.
Syntax:
if(condition) {
statement-1;
statement-2;
....
statement-n;
}

Example:
#include<stdio.h>
int marks, distinction_marks = 75;
printf("Enter marks : ");
scanf("%d", &marks);
if (marks > distinction_marks) {
printf("Secured distinction.\n");
}
Output:
Enter marks : 76
Secured distinction.

2. if-else construct
The if-else statement is a decision-making statement that is used to decide whether
the part of the code will be executed or not based on the specified condition or
expression.
If the given condition is true, then the code inside the if block is executed, otherwise
the code inside the else block is executed.
Syntax:
if (expression) {
statement-1;
} else {
statement-2;
}
Example:
#include<stdio.h>
void main(){
int num1, num2;
printf("Enter 2 numbers : ");
scanf("%d %d",&num1,&num2);
if(num1>num2){
printf("The largest number : %d\n",num1);
}
else{
printf("The largest number : %d\n",num2);
}
}
Output:
Enter 2 numbers : 10 20
The largest number : 20
Enter 2 numbers : 1234 243
The largest number : 1234

3. if-else-if construct
The if-else-if construct is used whenever we have multiple mutually
exclusive if conditions which work on the same input.
In a if-else-if construct the conditions are evaluated from top to bottom. Whenever a
condition evaluates to true (1), the control enters into that if-block and after that the
control comes out of the complete if-else-if construct ignoring all the
remaining if and else constructs that may exist below the currently satisfied if-block.
Syntax:
if (expression_1) {
statement_1;
} else if (expression_2) {
statement_2;
} else if (expression_3) {
statement_3;
} else if (expression_4) {
statement_4;
} else {
statement_5;
}

Example:
#include <stdio.h>
void main() {
int year;
printf("Enter a year : ");
scanf("%d", &year);
if(year % 400==0) {
printf("%d is a leap year\n", year);
} else if(year % 100==0) {
printf("%d is not a leap year\n", year);
} else if(year % 4==0) {
printf("%d is a leap year\n", year);
} else {
printf("%d is not a leap year\n", year);
}
}
Output:
Enter a year : 1900
1900 is not a leap year
Enter a year : 2013
2013 is not a leap year

4. Nested if-else construct


A nested if in C is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement.
Syntax:
if (expression_1) {
if (expression_2) {
if (expression_3) {
statement_1;
} else {
statement_2;
}
} else {
statement_3;
}
}
Example:
#include <stdio.h>
void main() {
int a, b, c;
printf("Enter three integer values : ");
scanf("%d %d %d", &a, &b, &c);
// Correct the below code
if (a>b) {
if (a>c) {
printf("%d is greater than %d and %d\n", a, b, c);
}{
printf("%d is greater than %d and %d\n", c, a, b);
}
} else{
if(b>c) {
printf("%d is greater than %d and %d\n", b, a, c);
} else{
printf("%d is greater than %d and %d\n", c, a, b);
}
}
}
Output:
Enter three integer values : 23 56 77
77 is greater than 23 and 56
Enter three integer values : 45 34 89
89 is greater than 45 and 34
5. switch-case construct
• The expression must evaluate to an int or a char value.
• The expression is evaluated first and its value is then matched against the case
labels. When a match is found, the statements following that case will be executed.
If there is no match with any of the case labels, the statements following
the default: case will be executed.
• The default part is optional. If the default part is omitted and the integer value of
the expression does not match with any of the available case labels, then no
statement with in the switch-case construct will be executed.

• If a break; statement is not included in case-statement, the execution control-flow


will fall through into the subsequent case statement until it encounters
a break statement.

Syntax:
switch (expression) {
case constant_1 :
statement_1;
break;
case constant_2 :
statement_2;
break;
case constant_3 :
statement_3;
break;
...
...

default :
statement_n;
break;
}
Example:
#include<stdio.h>
void main(){
int weekday;
printf("Enter weekday number (0-6) : ");
scanf("%d",&weekday);
switch(weekday){
case 0:
printf("Sunday\n");
break;
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
default:
printf("Invalid weekday number\n");
}
}
Output:
Enter weekday number (0-6) : 0
Sunday
Enter weekday number (0-6) : 7
Invalid weekday number
Lesson 3: Looping Statements
1. while loop
while loop provide a special construct/statement using which we can repeatedly execute
one or more statement as long as a condition is true.
Syntax :
while (condition) {
statement_1;
statement_2;
....
}
Working
The condition is an expression which should always evaluate to either true or false.

• If it evaluates to true, the body containing one or more code statements is executed.

• If the expression evaluates to false, the control skips executing the while-
loop body.

Example code which uses a while-loop to read multiple numbers from standard input
and prints their sum when the sum exceeds 100.
#include<stdio.h>
void main(){
int number;
int sum = 0;
while(sum <= 100){
printf("Enter a number : ");
scanf("%d",&number);
sum = sum+number;
}
printf("The total of given numbers is : %d\n",sum);
}

2. do-while loop
do-while loop statement is used to execute a section of code atleast once and then
repeatedly execute the same section of code as long as a certain condition is true.

Its syntax is similar to the reverse of while loop as shown below: And note the
extra ; which we have to provide at the end of while(condition)
Syntax:
do {
statement1;
statement2;
....
} while (condition);
Note: The statements inside the do-while block will be executed once before
the condition in the while is evaluated.
The condition is an expression which should always evaluate to either a true or a false value.
• If it evaluates to true, the do-while body containing one or more code statements is
executed again.

• If the expression evaluates to false, the control comes out of the do-while construct.

Example:
#include<stdio.h>
void main(){
int value = 1;
do{
printf("%d ",value);
value++;
}while(value<=5);
}
Output:
12345
3. for loop
for-loop is used to iterate over a range of values using a loop counter, which is a variable
taking a range of values in some orderly sequence (e.g., starting at 0 and ending at 10

in increments of 1). It is also called as entry-controlled loop


The value stored in a loop counter is changed with each iteration of the loop, providing a
unique value for each individual iteration. The loop counter is used to decide when to
terminate the loop.

Syntax of a for loop:


for (initialization; condition; update) {
statement(s);
}
1. The initialization expression initializes the loop counter; it is executed once at the
start of the loop.

2. The loop continues to execute as long as the condition expression evaluates to true.

3. The update expression is executed after each iteration through the loop,
to increment, decrement or change the loop counter.

Example :
#include<stdio.h>
void main(){
int i;
for (i = 1; i < 10; i++) {
printf("%d",i);
}
Output:
123456789

1. Above for loop statement initializes an integer variable i (which is the loop
counter) as part of the initialization expression.

2. In the update section, it increments the variable i by 1 using the post-


increment expression i++.

3. The expression in condition is i < 10. The for-loop keeps on executing the code
inside the loop body as long as this condition evaluates to true. And the loop
terminates when the condition evaluates to false.
3. Unconditional Control Statement

1. Break Statement:
Break terminates the execution at that point and transfers execution control to the
statement that immediately follows the loop or the switch-case statement
Example:
#include <stdio.h>
void main() {
int i;
for (i = 1; i < 10; i++) {
if (i % 5 == 0) {
break;
}
printf("i : %d\n",i );
}
}
For example, in the below code the control is terminated only from the inner loop:
#include <stdio.h>
void main() {
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {
if (i == j) {
break; // breaks from inner for-loop, if i is equal to j.
}
printf("i : %d, j : %d\n", i, j);
}
}
}
Output:
i : 2, j : 1
i : 3, j : 1
i : 3, j : 2
2. Continue Statement:
When a continue statement is encountered inside a loop, control jumps to the beginning of
the loop for next iteration, skipping the execution of statements inside the body of loop for
the current iteration. Instead of terminating the loop, it forces the next iteration of the loop
to take place.
Example Code:
#include <stdio.h>
void main() {
int i;
for (i=1;i<10;i++) {
if (i % 2 == 0) {
continue;
}
printf("i : %d\n", i);
}
}
Output:
i:5
i:7
i:9
Example 2:
For example, the below code skips printing the values of i and j using the continue;
statement whenever they are same:
#include <stdio.h>
void main() {
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {
if (i == j) {
continue; // continues next iteration of the inner for-loop, if i is equal to j.
}
printf("i : %d, j : %d\n", i, j);
}
}
Output:
i : 1, j : 2
i : 1, j : 3
i : 2, j : 1
i : 2, j : 3
i : 3, j : 1
i : 3, j : 2
3. goto Statement
The goto construct causes an unconditional transfer of execution control from the current
location to any other labelled location.

Syntax for forward goto statement is

goto Label;
.....
....
Label:
....
....

Syntax of backward goto statement is


Label:
.....
....
goto Label;
....
....
• In the above syntax Label is an identifier (meaning a name) and not a number.
• The same name used for a label should not be used for declaring an identifier of any other
type between the current label and its goto statement.
• The compiler identifies this name as a label if it is followed by a colon (:).

Example:

#include <stdio.h>
void main() {
char ch;
start:
printf("Enter a character : " );
scanf(" %c", &ch);
printf("The given character is : %c\n", ch);
if (ch != '#') {
goto start;
}
}

Output:
Enter a character : a
The given character is : a
Enter a character : @
The given character is : @

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy