PSUC
PSUC
PSUC
Educational Qualification
B.Tech.[1998]:IET Lucknow, Lucknow University
M.Tech.[2009]:School of IT, JNU New Delhi
Ph.D [2019]: The NorthCap University, Gurugram
Exp.:
(i) Sep 1999-Aug 2003, UPTEC Computer Consultancy Ltd. Allahabad
(ii) Sep 2003 - Nov 2005 Dronacharya College of Engineering, Gurugram
(iii) Dec 2005 - Aug 2007 Dept. of CSE, ITM Gurugram
(iv) Jul-2009 – Jun 2015, Dept. of CSE, ITM University, Gurugram
(v) Jul-2015 - Aug 2023, Dept. of CSE, The NorthCap University, Gurugram
(vi) Sep 2023 - Dept. of CCE, MUJ, Jaipur
Syllabus
Digital computer fundamentals: Algorithms and flowcharts, the von
Neumann architecture, programs, assembly language, high level
programming languages; Imperative programming (Using C): data
types, variables, Storage Classes, enumerated data types, operators,
expressions, statements, control structures, functions, arrays and pointers,
recursion, records (structures), files, input/output, some standard library
functions and some elementary data structures.
TEXT BOOKS
1. TE. Balagurusamy, Programming in ANSI C, 8th Edition, McGraw Hill Publication,
2019.
2. Y. P. Kanetkar, Let us C, 19th Edition, BPB Publication, 2022.
REFERENCE BOOKS
• Control Unit – A control unit (CU) handles all processor control signals. It directs all
input and output flow, fetches code for instructions, and controls how data moves
around the system.
• Arithmetic and Logic Unit (ALU) – The arithmetic logic unit is that part of the CPU that
handles all the calculations the CPU may need, e.g. Addition, Subtraction, Comparisons.
It performs Logical Operations, Bit Shifting Operations, and Arithmetic operations.
Basic CPU structure, illustrating ALU
Registers
1.Registers – Registers refer to high-speed storage areas in the CPU. The data
processed by the CPU are fetched from the registers. There are different types of
registers used in architecture :-Accumulator: Stores the results of calculations
made by ALU. It holds the intermediate of arithmetic and logical operatoins.it act
as a temporary storage location or device.
2.Program Counter (PC): Keeps track of the memory location of the next
instructions to be dealt with. The PC then passes this next address to the Memory
Address Register (MAR).
3.Memory Address Register (MAR): It stores the memory locations of instructions
that need to be fetched from memory or stored in memory.
4.Memory Data Register (MDR): It stores instructions fetched from memory or
any data that is to be transferred to, and stored in, memory.
5.Current Instruction Register (CIR): It stores the most recently fetched
instructions while it is waiting to be coded and executed.
6.Instruction Buffer Register (IBR): The instruction that is not to be executed
immediately is placed in the instruction buffer register IBR.
Input and Output Unit
• Input: Computer accept coded information through input unit. The most
common device is Keyboard. Whenever key is pressed, the corresponding
letter or digit is automatically translated into its corresponding binary code
and transmitted over a cable to either memory or the processor.
• Output: The output unit is the counterpart of the input unit. Its function is
to send processed results to the outside world. The most familiar device is a
printer. Some units, such as graphical displays, provide both an input and
output function.
Memory
• The function of the memory unit is to store programs and data. There are two
classes of storage, called as Primary and Secondary.
• Memory in which any location can be accessed in short and fixed amount of time
after specifying address is called Random Access Memory (RAM). CPU is known as
RAM because CPU can access any locations at any point of time.
Memory Con’d
• The smaller and fasted unit is called Cache. The largest and slowest unit
is referred to as main memory.
5
Secondary memory
➢Non-volatile memory
➢Low speed
6
Cache memory
➢ High speed memory placed between CPU and main memory
➢ Stores data and instructions currently to be executed
➢ More costlier but less capacity than main memory
➢ Users can not access this memory
7
Buses – Data is transmitted from one part of a computer to
another, connecting all major internal components to the CPU
and memory.
Types:
• Data Bus: It carries data among the memory unit, the I/O devices, and
the processor.
• Address Bus: It carries the address of data (not the actual data)
between memory and processor.
• Control Bus: It carries control commands from the CPU (and status
signals from other devices) in order to control and coordinate all the
activities within the computer.
High level Programming Languages
▪ In computer science, a high-level programming language is
a programming language with strong abstraction from the
details of the computer.
• Both High level language and low level language are the
programming languages’s types.
• The main difference between high level language and low
level language is that programmers can easily understand or
interpret or compile the high level language in comparison of
machine.
• On the other hand, Machine can easily understand the low
level language in comparison of human beings. Examples of
high level languages are C, C++, Java, Python, etc.
Difference between High Level and Low-level language
High Level Language Low-level language
1. It is programmer friendly language. It is a machine friendly language.
2. High level language is less memory efficient. Low level language is high memory efficient.
6. It is portable. It is non-portable.
2
Introduction to problem solving
3
Skill set required for Software Engineers
4
What is a problem?
• A problem is a puzzle that requires logical thought or mathematics to solve
• A puzzle could be a set of questions on a scenario which consists of
description of reality and a set of constraints about the scenario
• Eg: Scenario- Infosys Mysore campus has a library. The librarian issues book
only to Infosys employees.
Description of reality: There is a library in Infosys Mysore campus . There is a
librarian in the library
Constraints: librarian issues book only to Infosys employees.
Questions about the scenario: How many books are there in the library? How
many books can be issues to an employee?
Does the librarian issue book to himself? Etc.
5
Logic
• A method of human thought that involves thinking in a linear, step by
step manner about how a problem can be solved
• Logic is a language for reasoning. It is a collection of rules we use when
doing reasoning.
Eg: John’s mother has four children.
First child is April
Second child is May
Third child is June
What is the name of fourth child?
6
Importance of logic in problem solving
• Solution for any problem(eg: summation of two numbers) requires three
things.
Input: Input values(Eg: 3 and 2)
Process: Process of summation
Output: Output after process (Eg: sum of
numbers,5)
7
Importance of logic in problem solving
• For solving a problem, there may be multiple valid logics, some may be
simple and some may be complex.
Eg: To determine whether the number is prime or not.
Logic 1- divide the number by all the numbers starting from 2 to one less
than the number and if for all the division operations, the reminder is non
zero, the number is prime. Else the number is not prime.
Logic 2 – same as logic 1 but divide the number from 2 to number/2
Logic 3 - same as logic 1 but divide the number from 2 to square root of
the number
8
Types of problems
9
Computational Problems
• Definition: Computation is a process of evolution from one state to
another in accordance with some rules.
10
Broad applications of Computational Problem
11
Classification of computational problems
12
Computer Organization
13
Central Processing Unit
➢Data and instructions are processed in CPU
14
Arithmetic and Logical unit
▪ Performs arithmetic and logical operations:
• Example:
• arithmetic(+,-,*,/ etc..) and
• logical (AND, OR, NOT, <,= etc..) operations
15
Control unit
• Controls the order in which your program instructions are executed.
• Functions of CU:
▪ Fetches data and instructions to main memory
▪ Interprets these instructions
▪ Controls the transfer of data and instructions to and from main memory
▪ Controls input and output devices.
▪ Overall supervision of computer system
16
Memory unit
➢Storage device where the data and instructions fed by the user are stored
➢An ordered sequence of storage cells, each capable of holding a piece of information
➢The information held can be input data, computed values, or your program
instructions.
17
Memory unit
The computer starts using the memory from the moment the computer is switched on, till the time
it is switched off. The list of steps are—
1. Turn the computer on.
2. The computer loads data from ROM. It makes sure that all the major components of the
computer are functioning properly. The computer loads the BIOS from ROM. The BIOS provides the
most basic information about storage devices, boot sequence, security, plug and play capability and
other items.
3. The computer loads the OS from the hard drive into the system’s RAM. CPU has immediate access
to the OS as the critical parts of the OS are maintained in RAM as long as the computer is on. This
enhances the performance and functionality of the overall system.
4. Now the system is ready for use.
5. When you load or open an application it is loaded in the RAM. Since the CPU looks for
information in the RAM, any data and instructions that are required for processing (read, write or
update) is brought into RAM. To conserve RAM usage, many applications load only the essential
parts of the program initially and then load other pieces as needed. Any files that are opened for
use in that application are also loaded into RAM.
18
Memory unit
6. The CPU requests the data it needs from RAM, processes it and writes new data back to RAM in a
continuous cycle. The shuffling of data between the CPU and RAM happens millions of times every
second.
7. When you save a file and close the application, the file is written to the secondary memory as
specified by you. The application and any accompanying files usually get deleted from RAM to make
space for new data.
8. If the files are not saved to a storage device before being closed, they are lost.
The memory unit is the part of the computer that holds data and instructions for processing. Although it
is closely associated with the CPU, in actual fact it is separate from it. Memory associated with the CPU is
also called primary storage, primary memory, main storage, internal storage and main memory. When
we load software from a floppy disk, hard disk or CD-ROM, it is stored in the memory unit.
19
Memory unit
➢The computer memory is measured in terms of bits, bytes and words.
20
Computer memory classifications
• Main memory-Primary storage
• Secondary memory-Auxiliary storage
• Cache memory
21
Main memory
➢Memory where the data and instructions, currently being executed are
stored
➢ Located outside CPU
➢ High speed
➢ Data and instructions stored get erased when the power goes off
➢Also referred as primary / temporary memory
➢ Semiconductor memory
➢ Measured in terms of megabytes and gigabytes
22
Primary storage: RAM & ROM
• RAM stands for Random Access Memory
➢ Read and write memory
➢ Information typed by the user are stored in this memory
➢ Any memory location can be accessed directly without scanning it sequentially
(random access memory)
➢ During power failure the information stored in it will be erased → volatile
memory
• ROM stands for Read Only Memory
➢Permanent memory and non volatile
➢Contents in locations in ROM can not be changed
➢Stores mainly stored program and basic input output system programs
23
Secondary memory
24
Secondary memory
➢Non-volatile memory
➢Low speed
25
Cache memory
➢ High speed memory placed between CPU and main memory
➢ Stores data and instructions currently to be executed
➢ More costlier but less capacity than main memory
➢ Users can not access this memory
26
Computer languages
Operating System
➢OS is an integrated collection of programs which make the computer
operational and help in executing user programs.
2
Computer Languages
• Machine Language- The only programming language available in earlier days
• Consists of only 0’s and 1’s; e.g.:- 10101011
• Symbolic language or Assembly language-
• symbols or mnemonics are used to represent instructions
• hardware specific
• e.g. ADD X,Y; Add the contents of y to x
• High-level languages- English like language using which the programmer can write
programs to solve a problem.
• more concerned with the problem specification
• not oriented towards the details of computer
• e.g.: C, C++, C#, Fortran, BASIC, Pascal etc.
3
Language Translator
• Compiler : Program that translates entire high level language program
into machine language at a time. e.g.:- C, C++ compilers.
• Interpreter : Program which translates one statement of a high level
language program into machine language at a time and executes it.
e.g.:- Basic Interpreters, Java Interpreters.
• Assembler : Program which translates an assembly language program
into machine language.
e.g.:- TASM(Turbo ASseMbler), MASM(Macro ASseMbler).
4
History of C
➢The C language was evolved by Dennis Ritchie at Bell Laboratories and
was originally implemented on a DEC PDP(Digital Equipment
Corporation-Programmed Data Processor)-11 computer in 1972.
➢C initially became widely known as the development language of the
UNIX operating system.
➢Today, virtually all new major operating systems are written in C and/or
C++.
➢C is available for most computers.
➢C is mostly hardware independent.
5
Typical C program development environment
6
Typical C program development environment
➢C programs typically go through six phases to be executed. These are:
edit, preprocess, compile, link, load and execute
➢ Phase 1 : creating a program
➢Phases 2 and 3: Preprocessing and Compiling a C Program
➢Phase 4: Linking
➢Phase 5: Loading
➢Phase 6: Execution
7
Structure of C Program,
Character Set, Tokens
C Character set
➢C character set
consists of letters,
digits, special Special characters → ;, ?, >, <, &,{, }, [, ]……
characters, white
spaces.
White spaces → New line (\n), Tab(\t), Vertical
Tab(\v) etc.
2
C Tokens
Tokens
“hello” {
3
Simple C program
4
5
Hello world program
6
Structure of C program
#incude<stdio.h>
void main()
{
printf(“I love programming\n”); /*new line*/
printf(“easily\n”);
}
7
Input: Scanf()
#incude<stdio.h>
scanf(“%d”, &num);
Eg: scanf(“%d”, &integer1);
printf(“The number is = %d”, num);
}
8
Data Types and its Storage Requirements and its Range
Format
Specifier
%c
%c
%d
%u
%h
%hu
%ld
%lu
%f
%lf
%Lf
9
Character Meaning
Group
12
Output: Printf()
It is included in stdio.h
Examples are:
• Printf(“programming is an art”;
• Printf(“%d”, number);
• Printf(“%f%f”, p,q);
13
#include <stdio.h>
Adding two int main( void )
integers {
int sum; /* variable in which sum will be stored */
int integer1; /* first number to be input by user */
int integer2; /* second number to be input by user */
printf( "Enter first integer\n" );
scanf( "%d", &integer1 ); /* read an integer */
printf( "Enter second integer\n" );
scanf( "%d", &integer2 ); /* read an integer */
sum = integer1 + integer2; /* assign total to sum */
printf( "Sum is %d\n", sum ); /* print sum */
return 0; /* indicate that program ended successfully */
} /* end function main */
14
Syntax and Logical errors
15
C Compiler:
• For Window, you need to install MinGW for GCC or you can use Turbo C
compiler.
• The most frequently used and free available compiler is the GNU C/C++
compiler for Linux
• For MAC, the easiest way to obtain GCC is to download the Xcode
development environment from Apple's web site and follow the simple
installation instructions.
What to do when a C program produces different results in two different
compilers? → Your program must follow C standard i.e. ISO/IEC
9899:2011 (also known as C11)
16
Compilation Process
• The compilation is a process of converting the source code into object
code.
• The compilation process can be divided into four steps, i.e., Pre-
processing, Compiling, Assembling, and Linking.
The extension of the object file in DOS is '.obj,' and in UNIX, the extension is
'o'.
17
Compilation Process Example
18
Thank You!!
19
A program for Finding an Even and Odd
#include<stdio.h>
main()
{
int a,x;
printf("Enter a number\n");
scanf("%d",&a);
x=a%2;
if(x==0)
printf("Number a=%d is even\n",a);
else
printf("Number a=%d is odd\n",a);
}
20
Swap of Two Numbers, Using Two Variables
#include<stdio.h>
main()
{
int a=5, b=6;
printf("Swap of Numbers\n");
a=a+b; printf("a=%d\n",a);
b=a-b; printf("b=%d\n",b);
a=a-b; printf("a=%d\n",a);
///b=c;
printf("Final a=%d and b=%d",a,b);
}
21
Interest Calculation Program
#include<stdio.h>
#define PERIOD 10
#define PRINCIPAL 5000.00
void main()
{
int year;
float amount, value, Inrate;
amount=PRINCIPAL;
inrate=0.11;
year=0;
while(year<=PERIOD)
{
printf("year=%2d and amount=%8.2f\n",year, amount);
value=amount=amount+inrate*amount;
year=year+1;
amount=value;
}
}
22
Subroutine Call Program
#include<stdio.h>
main()
{
int a, b, c;
a=5; b=6;
c=mul(a,b);
printf("multplcaton of a=%d and b=%d is = %d",a,b,c);
}
int mul(int x,int y)
{
int p;
{
p=x*y;
return p;
}
} 23
Keywords
Constants(integer, real, character, string)
Literals
Variables
Keywords
2
Compiler specific keywords (32)
3
Constants
4
Note
A character constant is enclosed in single quotes.
5
Examples of Constant
Constant Example
6
Examples of Integer Constants
7
Examples of Real Constants
8
Examples of String Constants
9
Null Characters and Null Strings?
11
Two ways to define constant
1. const keyword
2. #define preprocessor
12
EXAMPLE PROGRAM
13
Literals
Literals are the constant values assigned to the constant
variables. We can say that the literals represent the fixed
values that cannot be modified.
◼ Float literal
◼ Character literal
◼ String literal
14
Variables
A variable is a container (storage area) to hold data
Variables are data storage locations in the
computer’s memory.
To indicate the storage area, each variable should be
given a unique name (identifier).
Example: float f=20.8; Here, f is variable
15
Variables
17
Variable Names- Identifiers
Putting all the variables in one place makes it easier for a reader
to understand the program.
21
Variables - Examples
L-value R-value
22
Data types
Comes under the category
2
Primary (built-in or Basic)Data types
INTEGER CHARACTER
3
Data types
Basic data types: int, float, double, char, and void.
4
Integer Types
short int or
signed short int 8 -128 to 127
short
unsigned int
8 0 to 255
6
The character type char
There are other escape sequences like, \t for tab, \v for vertical tab, \n
for new line etc.
7
Character Types
letter = ‘A'; /* OK */
9
Floating-Point Types
Floating-point constants can also be expressed in scientific notation. The value 1.7e4
represents the value 1.7 × 104.
The value before the letter e is known as the mantissa, whereas the value that follows
e is called the exponent.
Type Size
32 bits
Single Precision Float
4 bytes
64 bits
Double Precision double 8 bytes
11
void
➢2 uses of void are
▪To specify the return type of a function when it is not
returning any value.
▪To indicate an empty argument list to a function.
12
Summary of Memory Used
13
Summary of Memory Used
Data Types Memory Size Range
short int 2 byte −32,768 to 32,767
signed short int 2 byte −32,768 to 32,767
unsigned short 2 byte 0 to 65,535
int
long int 4 byte -2,147,483,648 to
2,147,483,647
signed long int 4 byte -2,147,483,648 to
2,147,483,647
unsigned long int 4 byte 0 to 4,294,967,295
float 4 byte
double 8 byte
long double 10 byte
14
Important
You can always check the size of a variable using
the sizeof() operator.
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;
15
Best Practices for Programming
Naming Variables According to Standards
17
Operators: Arithmetic,
Relational, Logical,
Assignment
Operators
The different operators are:
Increment and
Bitwise Assignment
Decrement
Conditional
2
Arithmetic Operators
The binary arithmetic operators are +, -, *, / and the modulus
operator %.
3
The unary minus operator
#include <stdio.h>
int main ()
{
int a = 25;
int b = -2;
printf(“%d\n”,-a); Output ?
printf(“%d\n”,-b);
return 0;
}
4
The unary minus operator
#include <stdio.h>
int main ()
{
int a = 25;
int b = -2;
printf(“%d\n”,-a); Output:
printf(“%d\n”,-b);
-25
return 0;
} 2
5
Working with arithmetic expressions
6
Working with arithmetic expressions
7
Working with arithmetic expressions
8
Summary of Operators
9
Working with arithmetic expressions
#include <stdio.h>
int main ()
Output:
{ 300
int a = 100; 102
int b = 2;
int c = 25;
int d = 4;
int result;
result = a * b + c * d; //Precedence
printf(“%d\n”,result);
result = a = (b + c * d);//Associativity
printf(“%d\n”,result);
return 0;
} 10
Increment and Decrement Operators
• ++ and -- operator as prefix and postfix
• If you use the ++ operator as a prefix like: ++var, the value of var is incremented by 1;
then it returns the value.
• If you use the ++ operator as a postfix like: var++, the original value of var is returned
first; then var is incremented by 1.
return 0;
}
12
Increment and Decrement Operators: Example
• What will be the output of the following C code?
#include <stdio.h>
int main()
{
Output:
int a = 1, b = 1, c; a = 2, b = 1, c=2
c = a++ + b;
printf(“a=%d, b=%d, c=%d", a, b,c);
}
13
Increment and Decrement operators
14
Increment and Decrement operators
Don’ts:
Attempting to use the increment or decrement operator
on an expression other than a modifiable variable name
or reference.
Example:
++(5) is a syntax error
15
Relational operators
Operator Meaning
== Is equal to
!= Is not equal to
ATTENTION !
the “is equal to” operator == and the “assignment” operator =
ATTENTION !
When comparing floating-point values, Only < and >
comparisons make sense !
16
Relational operators
➢ An expression such as a < b containing a relational operator is called a
relational expression.
➢ The value of a relational expression is one, if the specified relation is true and
zero if the relation is false.
E.g.:
10 < 20 is TRUE
20 < 10 is FALSE
➢ A simple relational expression contains only one relational operator and takes
the following form.
18
Logical operators
Truth Table
op-1 op-2 value of expression
op-1&&op-2 op-1||op-2
Non-zero Non-zero 1 1
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0
19
Logical operators
Expressions Evaluates As
!(FALSE) = TRUE
!(TRUE) = FALSE
20
Logical operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
Output
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result); (a == b) && (c > b) is 1
result = (a == b) && (c < b); (a == b) && (c < b) is 0
printf("(a == b) && (c < b) is %d \n", result); (a == b) || (c < b) is 1
result = (a == b) || (c < b); (a != b) || (c < b) is 0
printf("(a == b) || (c < b) is %d \n", result); !(a != b) is 1
result = (a != b) || (c < b); !(a == b) is 0
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}
21
The assignment operators
• The C language permits you to join the arithmetic operators
with the assignment operator using the following general
format: op=, where op is an arithmetic operator, including +,
–, *, /, and %.
• Example:
count += 10;
• Equivalent to:
count=count+10;
23
Bitwise Operators Examples
12 = 00001100 (In Binary) 12 = 00001100 (In Binary)
25 = 00011001 (In Binary) 25 = 00011001 (In Binary)
Bit Operation of 12 and 25
Bitwise OR Operation of 12 and 25
00001100
00001100
& 00011001 | 00011001
______ ________
00001000 = 8 (In decimal) 00011101 = 29 (In decimal)
25
Conditional Operator
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting"));
return 0;
}
26
Conditional Operator
#include <stdio.h>
int main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}
27
Thank You!!
28
Bitwise, Conditional,
Comma, Size-of
Bitwise Operators
2
Bitwise Logical operators
&(AND),|(OR),^(EXOR)
op1 op2 & | ^
1 1 1 1 0
These are binary operators
and require two integer 1 0 0 1 1
operands.
0 1 0 1 1
These work on their operands bit
by bit starting from LSB (rightmost 0 0 0 0 0
bit).
3
Example
Suppose x = 10, y = 15
z = x & y sets z=10 like this
0000000000001010 x
0000000000001111 y
0000000000001010 z = x & y
4
Bitwise Shift operators
<< ,>>
• op<<n or op>>n
• Here, op is the operand to be shifted and n is number of
positions to shift.
5
Bitwise Shift operator: <<
<< causes all the bits in the operand
op to be shifted to the left by n
positions.
6
Bitwise Shift operator: >>
7
Examples
Suppose X is an unsigned integer whose bit pattern is 0000
0000 0000 1011
8
Examples
▪Suppose X is an unsigned integer whose bit pattern is
0000 0000 0000 1011 whose equivalent value in
decimal number system is 11.
✓x<<3 0000 0000 0101 1000 Add ZEROS = 88
✓x>>2 Add Z EROS 0000 0000 0000 0010 =2
Note:
✓x=y<<1; same as x=y*2 (Multiplication)
✓x=y>>1; same as x=y/2 (Division)
9
Bitwise Shift operators
• n cannot be –ve
• n should not be greater than number of bits used
to represent Op.(E.g.: suppose op is int and size is 2
bytes then n cannot be greater than 16).
10
Bitwise complement operator
▪The complement operator(~) is an unary
operator and inverts all the bits represented
by its operand.
▪Suppose x=1001100010001111
~x=0110011101110000 (complement)
11
Bitwise Operator Examples
#include <stdio.h> Output:
6
int main() 31
{ 6
int a=6, b=14; // variable declarations -9
int x=23,y=10; // variable declarations
int m=12, n=10; // variable declarations
int k=8;
printf("The output of the Bitwise AND operator a&b is %d",a&b);
printf("The output of the Bitwise OR operator x|y is %d",x|y);
printf("The output of the Bitwise ExOR operator m^n is %d",m^n);
printf("The output of the Bitwise Comp operator k is %d",~k);
return 0;
}
12
Bitwise Operator Examples
// C Program to demonstrate use of bitwise operators
#include <stdio.h>
int main() Output:
{
// a = 5(00000101), b = 9(00001001) a = 5, b = 9
unsigned char a = 5, b = 9; a&b = 1
// The result is 00000001 a|b = 13
printf("a = %d, b = %d\n", a, b); a^b = 12
printf("a&b = %d\n", a & b);
~a = -6
// The result is 00001101 b<<1 = 18
printf("a|b = %d\n", a | b);
b>>1 = 4
// The result is 00001100
printf("a^b = %d\n", a ^ b);
return 0;
13
}
Important::
The bitwise operators should not be used in place of logical
operators. The result of logical operators (&&, || and !) is either 0 or 1,
but bitwise operators return an integer value. Also, the logical operators
consider any non-zero operand as 1. For example:
int main()
{ Output:
int x = 2, y = 5; False True
(x & y) ? printf("True ") : printf("False ");
(x && y) ? printf("True ") : printf("False ");
return 0;
}
14
Important::
int main()
{ Output:
unsigned int x = 1; Signed Result -2
printf("Signed Result %d \n", ~x); Unsigned Result 4294967294d
printf("Unsigned Result %ud \n", ~x);
return 0;
}
15
Sizeof Operator:
• When sizeof() is used with the data types such as int, float, char… etc it
simply returns the amount of memory is allocated to that data types.
16
Comma (,) operator
▪ The comma operator is a binary operator that evaluates its first operand and
discards the result, it then evaluates the second operand and returns this value
(and type).
17
Comma (,) operator
▪ The comma operator is a binary operator that evaluates its first operand and
discards the result, it then evaluates the second operand and returns this value
(and type).
int main()
{
int x = 10;
int y = 15; Output??
printf("%d", (x, y));
return 0;
}
18
Comma (,) operator
int main()
{
int x = 10; Output:
int y = (x++, ++x); 12
printf("%d", y);
return 0;
}
int main()
{
Output:
int x = 10, y;
x = 11
y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);
x = 12
printf("y = %d\n", y);
y = 12
printf("x = %d\n", x);
x = 13
return 0;
}
19
Comma (,) operator
20
The conditional operator (? :)
maxValue = ( a > b ) ? a : b;
Equivalent to:
if ( a > b )
maxValue = a;
else
maxValue = b; 21
Operator precedence
and associativity
Summary of Operators
Detailed
Precedence
Table
2
Example:
Show all the steps how the following expression is evaluated. Consider
the initial values of i=8, j=5.
2*((i/5)+(4*(j-3))%(i+j-2))
3
Example solution:
2*((8/5)+(4*(5-3))%(8+5-2))
2*(1+(4*2)%11)
2*(1+8%11)
2*(1+8)
2*9
18
4
Operator precedence & Associativity
Ex: (x==10 + 15 && y < 10)
Assume x=20 and y=5
Evaluation:
+ (x==25 && y< 10)
< (x==25 && true)
== (False && true)
&& (False)
5
Tutorial Problems
Suppose that a=2, b=3 and c=6, What is the answer for the following:
(a==5)
(a * b > =c)
(b+4 > a *c)
((b=2)==a)
1/25/2024 2
Implicit Type Conversions
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
All the data types of the variables are upgraded to the data type of the
variable with largest data type.
bool -> char -> short int -> int -> unsigned int -> long ->
unsigned -> long long -> float -> double -> long double
•It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
1/25/2024 3
Implicit Type Conversions in Expressions
The following are the sequence of rules that are applied while evaluating
expressions
Lower Type Operands Higher Type Operands
Short or Char int
One operand is Long double, the other will be Result is also long double
converted to long double
One operand is double, the other will be Result is also double
converted to double
One operand is float, the other will be converted Result is also float
to float
One operand is unsigned Long int, the other will Result is also unsigned long int
be converted to unsigned long int
1/25/2024 4
Implicit Type Conversions in Expressions
Lower Type Operands Higher Type Operands
One operand is Long int, and the other is a) Result will be long int
unsigned int then
a) If unsigned int can be converted to long int
the unsigned int operand will be converted
b) Else both operands will be converted to b) Result will be unsigned long int
unsigned long int
One operand is Long int, the other will be Result is also long int
converted to long int
One operand is unsigned Long int, the other Result is also unsigned long int
will be converted to unsigned long int
1/25/2024 5
Implicit Type Conversions in Expressions
1/25/2024 6
Implicit Type Conversion Example
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
x = x + y;
float z = x + 1.0;
Output:
x = 107, z = 108.000000
1/25/2024 7
Explicit Type Conversions
1/25/2024 8
Type Conversions in Expressions
1/25/2024 9
The Type Cast Operator
int a =150;
float f; f = (float) a / 100; // type cast operator
• The type cast operator has the effect of converting the value of the variable ‘a’ to type
float for the purpose of evaluation of the expression.
• This operator does NOT permanently affect the value of the variable ‘a’;
• The type cast operator has a higher precedence than all the arithmetic operators
except the unary minus and unary plus.
• Examples of the use of type cast operator:
1/25/2024 10
Type Conversions in Expressions
Example Action
x=(int) 7.5 7.5 is converted to integer by
truncation
a=(int) 21.3/(int)4.5 Evaluated as 21/4 and the result
would be 5
b=(double)sum/n Division is done in floating point mode
y=(int)(a+b) The result of a+b is converted to
integer
z=(int)a+b a is converted to integer and then
added to b
p=cos((double)x) Converts x to double before using it
1/25/2024 11
Integer and Floating-Point Conversions
Assign an integer value to a floating variable: does not cause any
change in the value of the number; the value is simply converted
by the system and stored in the floating format.
1/25/2024 12
Integer and Floating-Point Conversions
#include <stdio.h>
int main ()
{ float f1 = 123.125, f2;
int i1, i2 = -150;
i1 = f1; // float to integer conversion
printf(“float assigned to int produces”);
printf(“%d\n”,i1);
f2 = i2; // integer to float conversion
printf(“integer assigned to float produces”);
123
printf(“%f\n”,f2);
i1 = i2 / 100; // integer divided by integer -150.0
printf(“integer divided by 100 produces”);
printf(“%d\n”,i1);
f1 = i2 / 100.0; // integer divided by a float -1
printf(“integer divided by 100.0 produces”);
printf(“%f\n”,f1);
return 0;
-1.5
}
1/25/2024 13
All input and output is performed with streams, which
are sequences of bytes.
In input operations, the bytes flow from a device (e.g.,
a keyboard, a disk drive, a network connection) to main
memory.
In output operations, bytes flow from main memory to
a device (e.g., a display screen, a printer, a disk drive, a
network connection, and so on).
When program execution begins, three streams are
connected to the program automatically.
Normally, the standard input stream is connected to the
keyboard and the standard output stream is connected
to the screen.
Operating systems often allow these streams to be
redirected to other devices.
A third stream, the standard error stream, is connected
to the screen.
Error messages are output to the standard error stream.
Precise output formatting is accomplished with
printf.
Every printf call contains a format control string
that describes the output format.
The format control string consists of conversion
specifiers, flags, field widths, precisions and literal
characters.
Together with the percent sign (%), these form
conversion specifications.
Printf can perform the following formatting capabilities:
◦ Rounding floating-point values to an indicated number of decimal
places.
◦ Aligning a column of numbers with decimal points appearing one
above the other.
◦ Right justification and left justification of outputs.
◦ Inserting literal characters at precise locations in a line of output.
◦ Representing floating-point numbers in exponential format.
◦ Representing unsigned integers in octal and hexadecimal format
◦ Displaying all types of data with fixed-size field widths and
precisions.
The printf function has the form
printf(“Format Specifier”, var1, var2, …., varn);
Format Specifier describes the output format.
Each conversion specification begins with a percent
sign and ends with a conversion specifier.
There can be many conversion specifications in one
format control string.
An integer is a whole number, such as 776, 0 or –52,
that contains no decimal point.
Integer values are displayed in one of several formats.
A floating-point value contains a decimal point as in
33.5, 0.0 or -657.983.
The conversion specifiers e and E display floating-point
values in exponential notation—the computer
equivalent of scientific notation used in mathematics.
For example, the value 150.4582 is represented in
scientific notation as::
1.504582 102
and is represented in exponential notation as
1.504582E+02
• printf() and scanf() are examples for formatted input and output functions and
getch(), getchar(), gets(), puts(), putchar() etc. are examples of unformatted input
output functions.
• Unformatted I/O functions are used only for character data type or character
array/string and cannot be used for any other datatype.
Printf and Scanf function
• The standard input-output header file, named stdio.h contains the
definition of the functions printf() and scanf(),
• which are used to display output on screen and to take input from
user respectively.
• Format can be a simple constant string, but you can specify %s, %d,
%c, %f, etc., to print or read strings, integer, character, or float
respectively.
• There are many other formatting options available that can be used
based on requirements.
getchar ( ) ;
• This function provides for getting exactly one character from the
keyboard until and unless the enter key is pressed. This function is
declared in stdio.h
• Example:
char ch;
ch = getchar ( ) ;
putchar (char) ;
char ch;
ch = getchar ( ) ; /* input a character from kbd*/
putchar (ch) ; /* display it on the screen */
gets() & puts() Functions
• The gets() function reads a group of characters or strings from the
keyboard by the user and these characters get stored in a character
array. This function allows us to write space-separated texts or strings
• It reads data until either a terminating newline or EOF (end of file)
occurs.
• It is declared in stdio.h header file
• The puts() function writes the string str and a trailing newline to
stdout.
• str → This is the pointer to an array of chars where the C string is
stored. (Ignore if you are not able to understand this now.)
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
Difference between scanf and gets()
• The main difference between these two functions is that scanf() stops
reading characters when it encounters a space,
• but gets() reads space as a character too. If you enter the name as
Sanjay Kumar using scanf() it will only read and store Sanjay and will
leave the part after space.
• But gets() function will read it completely.
getch()
• It reads a single character from the keyboard by the user but doesn’t
display that character on the console screen and immediately
returned without pressing enter key.
• This function is declared in conio.h(header file) and is also used for
hold the screen. int main()
{
printf("Enter any
character: ");
return 0;
}
• This function is similar to getchar( ) except the input can be from the
keyboard or a file.
• Example:
char ch;
ch = getc (stdin) ; /* input from keyboard */
ch = getc (fileptr) ; /* input from a file */
Input/Output in C
putc ( char, *file ) ;
✓Sequential (Serial)
▪ In a Sequential approach, all the statements are executed in the same
order as it is written.
✓Iterational (Repetition)
▪ In an Iterational approach certain statements are executed repeatedly.
2. if…else statement.
4. else if ladder
5. Jump Statements:
break
continue
goto
return
if (test Expression)
{ If expression is true
statement-block; (non-zero), executes
} statement.
next_statement; It gives you the choice
of executing
statement or skipping
it.
}
Example - if
// Program to calculate the absolute value of an integer
int main ()
{
int number;
printf(“Type in your number: “);
scanf(“%d”,&number);
if ( number < 0 )
number = -number;
printf(“The absolute value is”);
printf(“%d”,number);
return 0;
}
if (test expression )
{
statement _block1 if-else
} statement:
else enables you to
{ choose between
statement _block2 two statements
}
Next_statement
Example: if(job_code == 1)
rate = 7.00;
else
rate = 10.00;
prinf(“%d”,rate);
yes no
expression
Next _statement
#include<stdio.h>
int main()
{
int a, b;
printf(“Enter 2 numbers\n”);
scanf(“%d %d”,&a,&b);
if(a > b)
a;
printf(“Large is %d“,a);
else
else
cout<<"large is "<<fb;
printf(“Large is %d“,b);
return 0;
}
Syntactically OK (void
statement on if) but a
semantic error !
if ( x == 0 );
printf(“The number is zero.\n“);
range“);
printf(“in
Because the order of evaluation for the <= operator is left-to-right, the
test expression is interpreted as follows:
(5<= x) <= 10
The subexpression 5 <= x either has the value 1 (for true) or 0 (for
false). Either value is less than 10, so the whole expression is always
true, regardless of x !
if (number > 5)
if (number < 10)
printf(“1111\n“);
else printf(“2222\n“);
Rule: an else
goes with the
if (number > 5) {
most recent if,
if (number < 10)
unless braces
printf(“1111\n“);
indicate
}
otherwise
else printf(“2222\n“);
Next_statement
2/13/2024 CSE 1001 Department of CSE 6
else if ladder -Explanation
▪ expression_1 is first evaluated. If it is TRUE, statement_1 is
executed and the whole statement terminated and the
next_statement is executed.
▪ On the other hand, if expression_1 is FALSE, control passes to the
else if part and expression_2 is evaluated.
▪ If it is TRUE, statement_2 is executed and the whole system is
terminated.
▪ If it is False, other else if parts (if any) are tested in a similar way.
▪ Finally, if expression_n is True, statement_n is executed; if not,
last_statement is executed.
▪ Note that only one of the statements will be executed others will be
skipped.
▪ The statement_n’s could also be a block of statement and must be
put in curly braces.
True False
Condition-1
True False
statement-1 Condition-2
True False
statement-2 Condition-3
True False
statement-3
Condition-n
statement-n
default statement
next statement
}
Example: else-if
// Program to implement the sign function
#include <stdio.h>
int main ( )
{
int number, sign;
printf("Please type in a number: “);
scanf(“%d”,&number);
if ( number < 0 )
sign = -1;
else if ( number == 0 )
sign = 0;
else // Must be positive
sign = 1;
printf(“Sign = %d“,sign);
return 0;
}
2/13/2024 CSE 1001 Department of CSE 11
Example – multiple choices
/* Program to evaluate simple expressions of the form number operator number */
#include <stdio.h>
int main ( )
{
float value1, value2,result;
char operator;
printf("Type in your expression.\n“);
scanf(“%f %c %f”, &value1,&operator,&value2);
if ( operator == '+' )
{result=value1+value2;
printf(“%f”,result);}
else if ( operator == '-' )
{result=value1-value2;
printf(“%f”,result);}
else if ( operator == '*' )
{result=value1*value2;
printf(“%f”,result);}
else if ( operator == '/' )
{result=value1/value2;
printf(“%f”,result);}
else
printf("Unknown operator.\n“);
2/13/2024 return 0; CSE 1001 Department of CSE 12
}
Problem…
else if (disc==0)
#include<stdio.h> {
#include<math.h> printf(“Real & equal roots“);
int main() re=-b / (2*a);
{
float a,b,c,root1,root2,re,im, disc; printf(“Root1 and root2 are
scanf(“%f %f %f”,&a,&b,&c); %.21f”,re);
disc=b*b-4*a*c; }
2/13/2024 2
The switch statement
switch ( expression )
{ The expression is
case value1: successively compared
program statement against the values value1,
program statement value2, ..., valuen. If a case is
... found whose value is equal
break; to the value of expression,
case value2: the program statements that
program statement follow the case are
program statement executed.
...
break;
case value n: The switch test expression must be one
program statement with an integer value (including type
program statement char) (No float !).
...
break; The case values must be integer-type
default: constants or integer constant
program statement expressions (You can't use a variable for
program statement a case label !)
...
}
2/13/2024 3
switch- control flow
2/13/2024 4
switch- example 1
#include<stdio.h>
int main()
{
int choice;
printf(“Enter your choice: 1-yes, 2-no\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“YESSSSSSS……”);
break;
case 2: printf(“NOOOOOO……”);
break;
default: printf(“DEFAULT CASE…….”);
} printf(“The choice is %d”,choice);
return 0;
}
2/13/2024 5
switch- example 2
scanf(“%d”,&mark);
case 50:
switch (mark)
grade=‘C’
{
break;
case 100: case 40:
case 90: grade=‘D’
case 80: grade=‘A’; break;
break;
default: grade=‘F’;
case 70: break;
case 60: }
printf(“%c”,grade);
grade=‘B’;
break;
2/13/2024 6
An Example – switch case
char ch;
scanf)(“%c”,&ch);
switch(ch)
{
case ‘a’ : printf(“Vowel”);
break;
case ‘e’ : printf(“Vowel”);
break;
case ‘i’ : printf(“Vowel”);
break;
case ‘o’ : printf(“Vowel”);
break;
case ‘u’ : printf(“Vowel”);
break;
default: printf(“Not a Vowel”); }
2/13/2024 7
An Example – switch case
char ch;
scanf(“%c”,&ch);
switch(ch)
{
case ‘a’:
case ‘e’:
case ‘i’ :
case ‘o’ :
case ‘u’ : printf(“Vowel”);
break;
default: printf(“Not a Vowel”); }
2/13/2024 8
Example - switch
/* Program to evaluate simple expressions case ‘*':
of the form value operator value */ result=value1*value2;
#include <stdio.h> printf(“%f”,result);
int main (void) break;
{ float value1, value2; case ‘/':
char operator; if ( value2 == 0 )
float result; printf(“Division by
printf("Type in your expression.\n“); zero.\n“);
scanf(“%f %c %f”, else result=value1 / value2;
&value1,&operator,&value2); printf(“%f”,result);
switch (operator) break;
{case '+': default;
result=value1+value2; printf(“Unknown Operator”);
printf(“%f”,result);
}
break;
return 0;
case '-':
result=value1-value2; }
printf(“%f”,result);
break;
2/13/2024 9
What is the output of the following code snippet?
int iNum = 2;
switch(iNum)
{
case 1:
printf(“ONE”);
break;
case 2:
printf(“TWO”);
break;
case 3:
printf(“THREE”);
break;
default:
printf(“INVALID”);
break;
}
2/13/2024 10
What is the output of the following code snippet?
iNum = 2;
switch(iNum)
{
default:
printf(“INVALID”);
case 1:
printf(“ONE”);
case 2:
printf(“TWO”);
break;
case 3:
printf(“THREE”;)
}
2/13/2024 11
What is the output of the following code snippet?
switch (iDepartmentCode)
{
case 110 : printf(“HRD ”);
case 115 : printf(“IVS ”);
case 125 : printf(“E&R ”);
case 135 : printf(“CCD ”);
IVS E&R CCD
}
2/13/2024 12
What is the output of the following code snippet?
int iNum = 2;
switch(iNum)
{
case 1.5:
printf(“ONE AND HALF”);
break;
case 2:
printf(“TWO”);
case ‘A’ :
printf(“A character”);
}
2/13/2024 13
Check Validity:
• switch(1+2+23)
• switch(1*2+3%4)
• switch(a*b+c*d)
• switch(a+b+c)
Important Points:
• Duplicate case values are not allowed
• Nesting of switch statements is allowed
2/13/2024 14
int main()
{
int x = 1;
switch (x)
{
x = x + 1;
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
default: printf("Choice other than 1 and 2");
break;
}
return 0;
}
Output:: Choice is 1
2/13/2024 15
int main()
{
int x = 1;
switch (x)
{
case 2: printf("Choice is 1");
break;
case 1+1: printf("Choice is 2");
break;
}
return 0;
}
Output::
2/13/2024 16
Decision Making,
Branching
Switch and Break
(Cont..)
Problem: Find the roots of Quadratic equation using switch statement
#include<stdio.h>
int main()
{
Int d;
float a,b,c,root1,root2,re,im, disc;
printf(“Enter the values of a, b & c:“);
scanf(“%f %f %f”,&a,&b,&c);
disc=b*b-4*a*c;
printf("\nDiscriminant= %f“,disc);
if(disc<0) d=1;
if(disc==0) d=2;
if(disc>0) d=3;
switch(d)
{
case 1:
printf("imaginary roots\n“);
re= - b / (2*a);
im = pow(fabs(disc),0.5)/(2*a);
printf(“root1=%.21f+%.21fi and root2 =%.21f-%.2fi”, re,im,re,im);
break;
2/13/2024 2
case 2:
printf(“Real & equal roots“);
re=-b / (2*a);
printf(“Root1 and root2 are %.21f”,re);
break;
case 3:
printf(“Real & distinct roots“);
printf(“Roots are“);
root1=(-b + sqrt(disc))/(2*a);
root2=(-b - sqrt(disc))/(2*a);
printf(“Root1 = %.21f and root2 =%.21f”,root1,root2);
break;
} // end of switch
return 0;
} //End of Program
2/13/2024 3
Some guidelines for writing switch case statements
2/13/2024 4
Flow of control in various control structures
2/13/2024 5
Loop Control Structures
Controlling the program flow
• Forms of controlling the program
flow:
– Executing a sequence of statements
– Using a test to decide between
alternative sequences (branching) Statement1
Statement2
– Repeating a sequence of statements Statement3
(until some condition is met) Statement4
(looping) Statement5
Statement6
Statement7
Statement8
2/13/2024 2
Program Looping
• A set of statements that executes repetitively for a number of
times.
• Simple example: displaying a message 100 times:
printf(hello !\n”);
printf(hello !\n”)
printf(hello !\n”)
…
Repeat 100 times
printf(hello !\n”)
printf(hello !\n”)
printf(hello !\n”)
2/13/2024 3
The need for program looping
2/13/2024 5
Iterative (loop) control structures
➢ Each loop control structure will have
✓ Program loop: body of loop.
✓ control statement → tests certain conditions & then directs repeated
execution of statements within the body of loop.
1) Entry controlled loop: control is tested before the start of the loop. If
false, body will not be executed.
2) Exit controlled loop: test is performed at the end of the body. i.e. body
of loop executed at least once.
2/13/2024 6
Entry Controlled & Exit controlled loops
Entry
Entry
Test False
Body of
Condition
The loop
True
Body of
True
The loop Test
Condition
False
2/13/2024 7
Example – 200th triangular number
Statement before triangularNumber = 0
loop
init_expression n=1
no
loop_condition n<=200
yes
triangularNumber =
Statement(s) triangularNumber + n
loop_expression n=n+1
2/13/2024 8
The ‘for’ loop
for ( init_expression; loop_condition; loop_expression )
{ program statement(s)
}
1 init_expression
no
5 2 loop_condition
yes
3 Program statement
4 Loop expression
Next Statement
2/13/2024 9
How for works
• The execution of a for statement proceeds as follows:
1. The initial expression is evaluated first. This expression usually sets a
variable that will be used inside the loop, generally referred to as an index
variable, to some initial value.
2. The looping condition is evaluated. If the condition is not satisfied (the
expression is false – has value 0), the loop is immediately terminated.
Execution continues with the program statement that immediately
follows the loop.
3. The program statement that constitutes the body of the loop is executed.
4. The looping expression is evaluated. This expression is generally used to
change the value of the index variable
5. Return to step 2.
2/13/2024 10
The for statement
sum = 0;
no
1 2 5 4
for ( n = 1; n yes
<= 200; n = n + 1 )
{ sum = sum + n; }
Next Statement
for ( init_expression; loop_condition; loop_expression )
{ program statement(s)
}
2/13/2024 11
Finding sum of natural numbers up to 100
#include <stdio.h>
int main()
{
int n;
int sum;
sum=0; //initialize sum
2/13/2024 13
Example – for with a body of 2 statements
#include <stdio.h>
int main()
{
int n, triangularNumber=0;
2/13/2024 14
for loop variants
• Multiple expressions (comma between…)
for(i=0 , j=10 ; i<j ; i++ , j--)
• Declaring variables
for(int i=0 ; i=10 ; i++ )
2/13/2024 15
while-loop
General format:
2/13/2024 16
The while statement
while ( expression )
program statement Loop with the
test in the
beginning !
statement before loop Body might
never be
executed !
3 1 Loop_expression 4
No
yes
2 statement (s)
Next statement
2/13/2024 17
Finding sum of natural numbers up to 100
2/13/2024 18
Program to reverse the digits of a number
#include <stdio.h>
int main()
{
int number, rev=0, right_digit;
while ( number != 0 )
{
right_digit = number % 10;
rev=rev*10 + right_digit;
number = number / 10;
}
printf(“The reversed number is %d“, rev);
return 0;
}
2/13/2024 19
The do – while statement
General form:
do
{
body of the loop
}
while(test condition);
✓Exit controlled loop. At the end of the loop, the test condition is evaluated.
✓After do statement, program executes the body of the Loop.
✓Then, the condition is tested, if it is true, body of the loop is executed once again
& this process continues as long as the condition is true.
✓Body of the loop is executed at least once.
✓do-while loop can be nested.
2/13/2024 1
The do statement
do
program
statement
while ( loop_expression );
Loop with the
test at the end !
Body is
executed at least
once !
3 1 Statement(s)
yes
loop_expression
2
No
Next statement 4
2/13/2024 2
Example: Finding sum of natural numbers
up to 100
#include <stdio.h> #include <stdio.h>
int main() int main()
{
{
int n;
int n; int sum =0;
int sum=0;
n=1;
n=1; while (n<=100)
do {
do
{ sum=sum+n;
{sum = sum + n;
n = n +1;
sum
n = n= +1;
sum + counter; }
} counter
while (n= <counter
=100); +1;}} printf(“%d”,sum);
} while (counter < 100); return 0;
printf(“%d”,sum); }
return 0;
2/13/2024 } 3
Program to reverse the digits of a number
#include <stdio.h>
#include <stdio.h> int main()
int main()
{
{
int number, rev=0, right_digit;
int number, rev=0, right_digit;
printf(“Enter your number.\n“);
printf(“Enter your number.\n“);
scanf(“%d”,&number);
scanf(“%d”,&number);
do
while ( number != 0 )
{
{
right_digit = number % 10;
right_digit = number % 10;
rev=rev*10 + right_digit;
rev=rev*10 + right_digit;
number = number / 10;
number = number / 10;
}
}
while ( number != 0 );
printf(“The reversed number is %d“, rev);
printf(“The reversed number is %d“,rev);
return 0;
return 0;
}
}
2/13/2024 4
Which loop to choose ?
• Criteria: category of looping
• Entry-controlled loop -> for, while
• Exit-controlledloop -> do
• You can actually rewrite any while as a for and vice versa !
2/13/2024 5
Faculty of Engineering (FOE)
Problem-Solving Using Computers Lab
|CS 1031 | 1 Credit | 0 0 2 1
Session: Jan-May 2024
Lab Experiments
1 Algorithms and Flow Charts Describe the flowcharts and design of an algorithm
7 Control Structures: Nested Loops Choose the loop statements to solve the problem
1. To multiply to numbers.
2. To divide two numbers.
3. To check whether the given number is even or odd.
4. To swap two numbers.
5. To check whether the given number is lesser than 10 or not.
6. To convert Fahrenheit to Celsius.
7. To check the greater number in the given two numbers.
8. To calculate simple interest.
9. To check whether the given number is prime or not.
10. To calculate area of the given rectangle.
7. Write a program to calculate the amount of an electricity bill for the followingcriteria.
(Without Loop)
Units charge per unit (Rs.)
First, 1-100 up to 0
Next, 101-200 up to 1.5
Next, 201-400 up to 2.5
401 onwards 3.5
8. Write a program to calculate the discount in rupees for the following criterion. (Without Loop)
Cost price discount
>=800 25%
500-800 20%
<500 no discount (0%)
1. Write a program to take N as input and print the odd numbers in descending order.
2. Write a program to print the Fibonacci number.
Hint: (Fibonacci series is 0, 1, 1, 2, 3, 5, 8,)
3. Write a program to find whether the given number is prime or not.
4. Write a program to convert the decimal number into
binary todecimal. Ex: 1101 = 1*2 3 + 1 * 2 2 + 0 *
2 1+ 1* 2 0 =13
5. Write a program to reverse a given number
Ex: 1234 reverse=4*10 3 +3 * 10 2 + 2 * 10 1 + 1 * 10 0 =4321
6. Write a program to find the sum of n terms of the sin series sin(x) = x - x3 + x5 – x7
7. Write a program to check whether a given integer no. is palindrome or not.
8. Write a program to check whether the given number is Armstrong or not. An
Armstrong number of three digits is an integer such that the sum of the cubes of
its digits is equal to the number itself. For example, 371 is an Armstrong
number since 33 + 73 + 13 = 371.
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5 5
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
5. Write a program to generate the multiplication table for n numbers up to k terms (nested
loops).
6. Write a program to print the Fibonacci numbers that fall in the given range.
7. Write a program to print the Nth the prime number.
8. Write a program to print the Nth the Armstrong number.
58 24 13 15 63 9 8 81 1 78
After splitting:
58 24 13 15 63
9 8 81 1 78
1. Write a program to change all lower-case letters into upper case in a sentence.
2. Write a program to find the last occurrence of a particular character.
3. Write a program to concatenate/length/copy two strings using the library function.
4. Write a program to count the number of words in a sentence.
5. Write a program to reverse a string.
6. Write a program to find the string length of a string without using the predefined function.
7. Write a program to find the substring of a given string.
8. Write a program to check if the given string is a palindrome or not.
1. Write a program to define a structure personal that would contain the person’s name, date of
joining, and salary. Using this structure write a program to read this information for one person
from the keyboard and print the same on the screen.
2. Write a program to create an array of student structures to store the roll no., name, and marks in
3 subjects. Input the details of N students into the array and display roll no., name, and total
marks of each student in decreasing order of total marks.
3. Write a program to create an array of employee structures to store emp-no, name, basic salary,
and HRA. Input the details of N employees and display emp-no, name, basic, HRA, and net
salary. Display the details of all employees whose net salary is more than the average net salary
of all employees.
4. Write a program to create a structure named Date having day, month, and year as its elements.
Store the current date in the structure. Now add 45 days to the current date and display the final
date.