PSUC
PSUC
1
2
Functional Units of Computer System
It is divided in two modules in general:
• Hardware: A hardware of the computer system consists of all electronic
components such as electronic circuits, display units, storage media
(magnetic and optical (a class of data storage systems that use light to
read or write data to an underlying optical media-CD, DVD)),
electromechanical devices and communication facilities.
3
Von Neumann Architecture
• Von-Neumann computer architecture design was proposed in 1945. It
was later known as Von-Neumann architecture.
4
Von Neumann architecture… Cont’d
• Modern computers are based on a
stored-program concept introduced by
John Von Neumann.
• 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.
6
Basic CPU structure, illustrating ALU
7
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.
8
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.
9
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.
10
Memory Con’d
• The smaller and fasted unit is called Cache. The largest and slowest unit
is referred to as main memory.
11
Memory unit
5
14
Secondary memory
➢Non-volatile memory
➢Low speed
6
15
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
16
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.
17
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.
18
Difference between High Level and Low level languages
• 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.
19
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.
23
Objectives
To learn and appreciate the following concepts
2
24
Introduction to problem solving
3
25
Skill set required for Software Engineers
4
26
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
27
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
28
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
29
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
30
Types of problems
9
31
Computational Problems
• Definition: Computation is a process of evolution from one state to
another in accordance with some rules.
10
32
Broad applications of Computational Problem
11
33
Classification of computational problems
12
34
Computer Organization
13
35
Central Processing Unit
➢Data and instructions are processed in CPU
14
36
Arithmetic and Logical unit
▪ Performs arithmetic and logical operations:
• Example:
• arithmetic(+,-,*,/ etc..) and
• logical (AND, OR, NOT, <,= etc..) operations
15
37
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
38
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
39
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
40
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
41
Memory unit
➢The computer memory is measured in terms of bits, bytes and words.
20
42
Computer memory classifications
• Main memory-Primary storage
• Secondary memory-Auxiliary storage
• Cache memory
21
43
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
44
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
45
Secondary memory
24
46
Secondary memory
➢Non-volatile memory
➢Low speed
25
47
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
48
Computer languages
49
Operating System
➢OS is an integrated collection of programs which make the computer
operational and help in executing user programs.
2
50
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
51
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
52
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
53
Typical C program development environment
6
54
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
55
Structure of C Program,
Character Set, Tokens
56
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
57
C Tokens
Tokens
“hello” {
3
58
Simple C program
4
59
5
60
Hello world program
6
61
Structure of C program
#incude<stdio.h>
void main()
{
printf(“I love programming\n”); /*new line*/
printf(“easily\n”);
}
7
62
Input: Scanf()
#incude<stdio.h>
scanf(“%d”, &num);
Eg: scanf(“%d”, &integer1);
printf(“The number is = %d”, num);
}
8
63
Data Types and its Storage Requirements and its Range
Format
Specifier
%c
%c
%d
%u
%h
%hu
%ld
%lu
%f
%lf
%Lf
9
64
Character Meaning
Group
12
67
Output: Printf()
It is included in stdio.h
Examples are:
• Printf(“programming is an art”;
• Printf(“%d”, number);
• Printf(“%f%f”, p,q);
13
68
#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
69
Syntax and Logical errors
15
70
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
71
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
72
Compilation Process Example
18
73
Thank You!!
19
74
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
75
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
76
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
77
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;
}
} 78
23
Keywords
Constants(integer, real, character, string)
Literals
Variables
79
Keywords
2
80
Compiler specific keywords (32)
3
81
Constants
4
82
Note
A character constant is enclosed in single quotes.
5
83
Examples of Constant
Constant Example
6
84
Examples of Integer Constants
7
85
Examples of Real Constants
8
86
Examples of String Constants
9
87
Null Characters and Null Strings?
11
89
Two ways to define constant
1. const keyword
2. #define preprocessor
12
90
EXAMPLE PROGRAM
13
91
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
92
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
93
Variables
17
95
Variable Names- Identifiers
Putting all the variables in one place makes it easier for a reader
to understand the program.
21
99
Variables - Examples
L-value R-value
22
100
Data types
101
Comes under the category
2
102
Primary (built-in or Basic)Data types
INTEGER CHARACTER
3
103
Data types
Basic data types: int, float, double, char, and void.
4
104
Integer Types
short int or
signed short int 8 -128 to 127
short
unsigned int
8 0 to 255
6
106
The character type char
There are other escape sequences like, \t for tab, \v for vertical tab, \n
for new line etc.
7
107
Character Types
letter = ‘A'; /* OK */
9
109
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
111
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
112
Summary of Memory Used
13
113
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
114
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
115
Best Practices for Programming
Naming Variables According to Standards
17
117
Operators: Arithmetic,
Relational, Logical,
Assignment
118
Operators
The different operators are:
Increment and
Bitwise Assignment
Decrement
Conditional
2
119
Arithmetic Operators
The binary arithmetic operators are +, -, *, / and the modulus
operator %.
3
120
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
121
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
122
Working with arithmetic expressions
6
123
Working with arithmetic expressions
7
124
Working with arithmetic expressions
8
125
Summary of Operators
9
126
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
127
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
129
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
130
Increment and Decrement operators
14
131
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
132
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
133
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
135
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
136
Logical operators
Expressions Evaluates As
!(FALSE) = TRUE
!(TRUE) = FALSE
20
137
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
138
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
140
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
142
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
143
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
144
Thank You!!
28
145
Bitwise, Conditional,
Comma, Size-of
146
Bitwise Operators
2
147
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
148
Example
Suppose x = 10, y = 15
z = x & y sets z=10 like this
0000000000001010 x
0000000000001111 y
0000000000001010 z = x & y
4
149
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
150
Bitwise Shift operator: <<
<< causes all the bits in the operand
op to be shifted to the left by n
positions.
6
151
Bitwise Shift operator: >>
7
152
Examples
Suppose X is an unsigned integer whose bit pattern is 0000
0000 0000 1011
8
153
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
154
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
155
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
156
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
157
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
} 158
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
159
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
160
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
161
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
162
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
163
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
164
Comma (,) operator
20
165
The conditional operator (? :)
maxValue = ( a > b ) ? a : b;
Equivalent to:
if ( a > b )
maxValue = a;
else
maxValue = b; 21
166
Operator precedence
and associativity
167
Summary of Operators
Detailed
Precedence
Table
2
168
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))
169
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
170
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
171
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)
173
Type Conversions in Expressions
1/25/2024 2
174
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
175
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
176
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
177
Implicit Type Conversions in Expressions
1/25/2024 6
178
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
179
Explicit Type Conversions
1/25/2024 8
180
Type Conversions in Expressions
1/25/2024 9
181
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
182
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
183
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
184
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
185
186
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.
187
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.
188
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.
189
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.
190
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.
191
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.
192
193
194
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.
195
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
196
Values displayed with e, E and f show six digits of precision to the
right of the decimal point by default (e.g., 1.04592); other precisions
can be specified explicitly.
Conversion specifiers e and E print lowercase e and uppercase E,
respectively, preceding the exponent, and print exactly one digit to
the left of the decimal point.
Conversion specifier g (or G) prints in either e (E) or f format with
no trailing zeros (1.234000 is printed as 1.234).
Values are printed with e (E) if, after conversion to exponential
notation, the value’s exponent is less than -4, or the exponent is
greater than or equal to the specified precision (six significant
digits by default for g and G). Otherwise, conversion specifier f is
used to print the value.
At least one decimal digit is required for the decimal point to be
output.
197
0.0000875, 8750000.0, 8.75, 87.50 and 875
are printed as …. with conversion specifier g??
8.75e-05
8.75e+06
8.75, 87.5
875
199
200
201
The c and s conversion specifiers are used to print
individual characters and strings, respectively.
Conversion specifier c requires a char argument.
Conversion specifier s requires a pointer to char as
an argument.
Conversion specifier s causes characters to be printed
until a terminating null ('\0') character is
encountered.
202
203
The exact size of a field in which data is printed is specified
by a field width.
If the field width is larger than the data being printed, the
data will normally be right justified within that field.
An integer representing the field width is inserted between
the percent sign (%) and the conversion specifier (e.g.,
%4d).
The field width is increased to print values wider than the
field and that the minus sign for a negative value uses one
character position in the field width.
Field widths can be used with all conversion specifiers.
204
205
Function printf also enables you to specify the precision
with which data is printed.
Precision has different meanings for different data types.
When used with integer conversion specifiers, precision
indicates the minimum number of digits to be printed.
If the printed value contains fewer digits than the
specified precision and the precision value has a leading
zero or decimal point, zeros are prefixed to the printed
value until the total number of digits is equivalent to the
precision.
If neither a zero nor a decimal point is present in the
precision value, spaces are inserted instead.
206
The default precision for integers is 1.
When used with floating-point conversion specifiers e, E
and f, the precision is the number of digits to appear after
the decimal point.
When used with conversion specifiers g and G, the
precision is the maximum number of significant digits to be
printed.
When used with conversion specifier s, the precision is the
maximum number of characters to be written from the
string.
To use precision, place a decimal point (.), followed by an
integer representing the precision between the percent sign
and the conversion specifier.
207
When a floating-point value is printed with a precision smaller than the original
number of decimal places in the value, the value is rounded.
208
The field width and the precision can be combined
by placing the field width, followed by a decimal
point, followed by a precision between the percent sign
and the conversion specifier, as in the statement
printf( "%9.3f", 123.456789 );
which displays 123.457 with three digits to the right
of the decimal point right justified in a nine-digit field.
It’s possible to specify the field width and the precision
using integer expressions in the argument list following
the format control string.
209
To use this feature, insert an asterisk (*) in place of the
field width or precision (or both).
The matching int argument in the argument list is
evaluated and used in place of the asterisk.
A field width’s value may be either positive or negative
(which causes the output to be left justified in the field
as described in the next section).
The statement
printf( "%*.*f", 7, 2, 98.736 );
uses 7 for the field width, 2 for the precision and
outputs the value 98.74 right justified.
210
Most literal characters to be printed in a printf statement
can simply be included in the format control string.
However, there are several “problem” characters, such as
the quotation mark (") that delimits the format control string
itself.
Various control characters, such as newline and tab, must be
represented by escape sequences.
An escape sequence is represented by a backslash (\),
followed by a particular escape character.
Figure 9.16 lists the escape sequences and the actions they
cause.
211
212
Precise input formatting can be accomplished with
scanf.
Every scanf statement contains a format control
string that describes the format of the data to be input.
The format control string consists of conversion
specifiers and literal characters.
Function scanf has the following input formatting
capabilities:
◦ Inputting all types of data.
◦ Inputting specific characters from an input stream.
◦ Skipping specific characters in the input stream.
213
Function scanf is written in the following form:
scanf( format-control-string, other-arguments );
format-control-string describes the formats of the input, and other-arguments are
pointers to variables in which the input will be stored.
214
215
216
Conversion specifier %i is capable of inputting decimal,
octal and hexadecimal integers.
217
When inputting floating-point numbers, any of the
floating-point conversion specifiers e, E, f, g or G can
be used.
Figure 9.19 reads three floating-point numbers, one
with each of the three types of floating conversion
specifiers, and displays all three numbers with
conversion specifier f.
The program output confirms the fact that floating-
point values are imprecise—this is highlighted by the
third value printed.
218
219
Characters and strings are input using the conversion specifiers c and s,
respectively. The program inputs the first character of the string with %c
and stores it in the character variable x, then inputs the remainder of the
string with %s and stores it in character array y.
220
A sequence of characters can be input using a scan set.
A scan set is a set of characters enclosed in square brackets,
[], and preceded by a percent sign in the format control
string.
A scan set scans the characters in the input stream, looking
only for those characters that match characters contained in
the scan set.
Each time a character is matched, it’s stored in the scan
set’s corresponding argument—a pointer to a character
array.
The scan set stops inputting characters when a character
that is not contained in the scan set is encountered.
221
If the first character in the input stream does not match
a character in the scan set, only the null character is
stored in the array.
222
The scan set can also be used to scan for characters not contained
in the scan set by using an inverted scan set. For this, place a caret
(^) in the square brackets before the scan characters.
When a character contained in the inverted scan set is
encountered, input terminates.
223
A field width can be used in a scanf conversion
specifier to read a specific number of characters from
the input stream.
224
Often it’s necessary to skip certain characters in the
input stream.
For example, a date could be entered as
11-10-1999
Each number in the date needs to be stored, but the
dashes that separate the numbers can be discarded.
To eliminate unnecessary characters, include them in
the format control string of scanf (white-space
characters—such as space, newline and tab—skip all
leading white-space).
225
For example, to skip the dashes in the input, use the
statement
scanf( "%d-%d-%d", &month, &day, &year );
Although, this scanf does eliminate the dashes in the
preceding input, it’s possible that the date could be
entered as
10/11/1999
In this case, the preceding scanf would not eliminate
the unnecessary characters.
For this reason, scanf provides the assignment
suppression character *.
226
The assignment suppression character enables scanf to
read any type of data from the input and discard it without
assigning it to a variable.
Figure 9.24 uses the assignment suppression character in
the %c conversion specifier to indicate that a character
appearing in the input stream should be read and discarded.
Only the month, day and year are stored.
The argument lists for each scanf call do not contain
variables for the conversion specifiers that use the
assignment suppression character.
The corresponding characters are simply discarded.
227
228
229
Input and Output Statements
(Formatted and Unformatted)
230
Input and output In C language
• C programming language has standard libraries that allow input and output in a
program.
• The studio.h or standard input-output library in C that has methods for input and
output.
• Input output built-in functions in C falls into two categories:
1. Formatted input output (I/O) functions and
2. Unformatted input output (I/O) functions.
• 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.
231
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.
232
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 ( ) ;
233
putchar (char) ;
char ch;
ch = getchar ( ) ; /* input a character from kbd*/
putchar (ch) ; /* display it on the screen */
234
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.)
235
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
236
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.
237
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;
}
239
putch()
• putch() function is used to display a single character which is given by
the user and that character prints at the current cursor location. This
function is declared in conio.h(header file)
240
Input/Output in C
getc ( *file ) ;
• 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 */
241
Input/Output in C
putc ( char, *file ) ;
242
Decision Making,
Branching
if, if-else
243
Control Structures
➢A control structure refers to the order of executing the program
statements.
➢The following three approaches can be chosen depending on the problem
statement:
✓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.
} 250
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 !
262
Nested if-else Statement
265
Nested if statements
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
267
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
} 271
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
272
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
} 273
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; }
276
The switch Statement
2/13/2024 2
277
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
278
switch- control flow
2/13/2024 4
279
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
280
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
281
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
282
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
283
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
284
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
285
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
286
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
287
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
288
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
289
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
290
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
291
Decision Making,
Branching
Switch and Break
(Cont..)
292
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
293
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
294
Some guidelines for writing switch case statements
2/13/2024 4
295
Flow of control in various control structures
2/13/2024 5
296
Loop Control Structures
297
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
298
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
299
The need for program looping
2/13/2024 5
301
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
302
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
303
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
304
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
305
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
306
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
307
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
309
Example – for with a body of 2 statements
#include <stdio.h>
int main()
{
int n, triangularNumber=0;
2/13/2024 14
310
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
311
while-loop
General format:
2/13/2024 16
312
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
313
Finding sum of natural numbers up to 100
2/13/2024 18
314
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
315
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
316
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
317
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
318
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
319
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
320
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
321
Lab 1. Algorithms and Flowcharts
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.
322
Lab 3. Formula based C Programs
1. Write a program to convert the time in seconds to hours, minutes, and seconds. (1 hr
=3600 sec).
2. Write a program to find the sum of the digits of a four-digit number (ex.
1234 sum=10)(without using a loop).
3. Write a program to convert the temperature given in Fahrenheit to
Centigrade andCentigrade to Fahrenheit. Hint: C=5/9(F-32)).
4. Write a program for converting distance in mm to cm, inch, feet
(1 cm =10mm,1inch=2.5cm, 1 feet =12 inches).
5. Write a program to find out the distance between two points e.g. (x1, y1) and (x2, y2).
Hint: Distance=√(x2-x1)2+ (y2-y1)2
6. Write a program to evaluate the area of the circle Area = Pi * R2
7. Write a program to interchange the values of two variables using a third variable.
8. Write a program to interchange the values of two variables without using a third variable.
323
Minimum Rs. 200 for up to 100 calls.
Plus, Rs. 0.60 per call for the next 50 calls. Plus, Rs. 0.50 per call for the next 50 calls.
Plus, Rs. 0.40 per call for any call beyond 200 calls
6. Write a program to calculate an amount of a telephone bill for the following criteria. (Without
Loop)
Calls charge per call (Rs.)
1-150 0
151-250 .9
251-400 1.2
401 onwards 1.5
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.
324
2 3
4 5 6
7 8 9 10
11 12 13 14 15
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
325
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.
326
Lab 12. Pointers
1. Write a program to access two integers using pointers and add them.
2. Write a program to find out the greatest and the smallest among the three numbers usingpointers.
3. Write a program to determine the length of a character string using a pointer.
4. Write a program to compute the sum of all elements stored in an array using a pointer.
5. Write a program to determine whether a substring (string 1) is in the main string or not.If present,
return the pointer of the first occurrence.
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.
327
Array
An array in C is a variable that can store multiple values
of the same data type. It is a fixed-size collection of
similar data items stored in contiguous memory
locations.
printf(“%d\n”,x[0]);
Output:
printf(“%d\n”,x[1]); 9
printf(“%d\n”,x[2]); 11
13
or
int x[3] = {9,11,13};
printf(“%d\n”,x[i]);
4/5/2024 CSE 1001 Department of CSE 10
336
Program to read n elements into an array and print it
int a[10], i, n;
printf("enter no of numbers“); Output:
scanf(“%d”,&n); enter no of elements
3
printf(“enter n numbers \n”); enter n numbers
for(i=0;i<n;i++) 9
scanf(“%d\n”,&x[i]); 11
13
Numbers entered are:
printf(“\nNumbers entered are:\n”); 9
for(i=0;i<n;i++) 11
13
printf(“%d\n”,a[i]);
4/5/2024 CSE 1001 Department of CSE 11
337
Program to add two array elements and store the
corresponding elements sum in another array
void main()
if(m==n)
{ {
int a[10], b[10], c[10],n, m, i; for(i=0;i<m;i++)
printf("enter no. of numbers in { c[i]=a[i]+b[i]; }
first array\n“);
printf(“Sum of given array
scanf(“%d”,&n); elements\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]); //first array for(i=0;i<n;i++)
{ printf(“%d\n”,c[i]); }
}
printf("enter no of numbers in second else
array\n“); printf("cannot add“);
scanf(“%d”,&m); }
for(i=0;i<m; i++)
scanf(“%d”,&b[i]); //second array
4/5/2024 CSE 1001 Department of CSE 12
338
Displaying elements of an array in reverse order.
printf(“%d\n”,a[i]);
printf("enter no of elements”);
Example : delete element at 2nd position
scanf(“%d”,&n); a[ ]={1, 2, 3, 4, 5}
printf("enter n elements \n”);
New array after deleting 2:
for(i=0;i<n;i++) a[ ]={1, 3, 4, 5}
scanf(“%d”,&a[i]);
printf("enter the position at which the element to be deleted“);
scanf(“%d”,&pos);
for(i=pos-1; i<n-1; i++)
a[i] =a[i+1]; //shift the elements to left
n = n-1;//decrement the count of no of elements
for(i=0;i<n;i++)
printf(“%d”,a[i]);
4/5/2024 CSE 1001 Department of CSE 14
340
Insert an element into a sorted array
Read array elements (in sorted order) & element ‘ele’ to be
inserted
/ / f in di ng p o s i tio n Example: insert 3 into the array
for(i=0;i<n;i++) a[ ] = {1, 2, 4, 5,6}
▪ Memory Requirement:
Total size =size *(sizeof(data_type));
▪ Initialization:
type array-name [size]={list of values}
Example : a[ ]={1, 2, 3, 4, 5}
int a[20], i, j, n, temp;
Enter values
printf("enter n \n“); n=5
12345
scanf(“%d”, &n); Reversed array
5 4 3 2 1
printf("\n Enter values for an array“); Array Reversed
array
for(i=0;i<n;i++) a[0]=1 a[0]=5
a[1]=2 a[1]=4
scanf(“%d”,&a[i]); a[2]=3 a[2]=3
a[3]=4 a[3]=2
Contd… a[4]=5 a[4]=1
searched"; otherwise
Print “data is not found“;
Input key; // data to be searched
4/5/2024 CSE 1001 Department of CSE 23
349
Sorting
Arrangement of data elements in a particular order
→ Bubble sorting
354
Strings
Definition
▪ A string is an array of characters.
▪ Any group of characters defined between double quotation marks is a
constant string.
▪ Character strings are often used to build meaningful and readable
programs.
The common operations performed on strings are
✓Reading and writing strings
✓Combining strings together
✓Copying one string to another
✓Comparing strings to another
✓Extracting a portion of a string ..etc.
4/5/2024 CSE 1001 Department of CSE 29
355
Strings
Declaration and initialization
char string_name[size];
The size determines the number of characters in the string_name.
For example
✓The 5 characters that compose the word "Hello" plus a final null character
('\0') which specifies the end of the
✓In the second case, when using double quotes (") null character ('\0') is
appended automatically.
int main() {
printf(“%s”, question);
scanf(“%s”, &yourname);
return 0;
Please, enter your first name: gautam
} Hello.…gautam
#include <stdio.h>
int main()
{
return 0;
Enter a string:
} gautam kumar
gautam
To read everything that you enter from the keyboard until the
ENTER key is pressed (including space).
Syntax:
gets(string) ;
int main()
{
{ {
printf("\nEnter a string:\n“);
gets(str);
The function will continue to accept characters until enter key is pressed.
▪ strlen ()
✓ gives the length of the string. E.g. strlen(string)
▪ strcpy ()
✓ copies one string to other. E.g. strcpy(Dstr1, Sstr2)
▪ strcmp ()
✓ compares the two strings. E.g. strcmp(str1, str2)
▪ strcat ()
✓Concatinate the two strings. E.g. strcat(str1, str2)
#include<string.h>
int main() sent[0] sent[1] sent[2] sent[3] sent[4]
{ Enter sentence
Delhi
char sent[100]; 5 (length of string sent)
int len; I
printf("enter string \n“); D
gets(sent);
len=strlen(sent);
printf(“%d\n”,len);
printf(“%c\n”,sent[len-1]);
printf(“%c\n”,sent[0]); }
The size of the array city1 should be large enough to receive the
contents of city2.
int main()
printf(“%s”,str2);//display str2
for(i=0;i<no-1;i++)
int main() for(j=i+1;j<no;j++)
{
{ if(strcmp(string[i],string[j])>0)
char string[30][30],temp[30]; {
strcpy(temp,string[i]);
int no, i, j; strcpy(string[i],string[j]);
cout<<"\nEnter the no of strings:"; strcpy(string[j],temp);
}
cin>>no; }
cout<<"\nEnter the strings:";
for(i=0;i<no; i++) cout<<"\nThe sorted array is:";
for(i=0;i<no;i++)
gets(string[i]); puts(string[i]);
return 0;
}
Main string: cc aa bb
Sub-String : aa
56
382
Finding Substring in Main String
int main()
{
char str1[80],str2[80];
int i,j,len=0;
57
383
Finding Substring in Main String
for(i=0,j=0; str1[i]!='\0‘ && str2[j]!='\0'; i++)
if(str1[i]==str2[j])
j++;
else
j=0;
if(j==len)
cout<<"Substring\t"<<str2<< "\tfound;
else
cout<<"Substring not found";
58
384
2 dimensional Arrays
Declaration
type array_name[row_size][column_size];
For example,
int arr [3][5];
✓arr represents a two dimensional array or table
having 3 rows and 5 columns and it can store 15
integer values.
5/3/2024 CSE 1001 Department of CSE 3
385
2 dimensional Arrays
For example
int marks[5][3];
float matrix[3][3];
char page[25][80];
else exit(0); }
for(j=0;j<n;j++) }
scanf(“%d’,&a[i][j]);
5/3/2024 CSE 1001 Department of CSE 11
393
Row Sum & Column Sum of a matrix
for(i=0;i<m;i++) printf(“->“)
colsum[j]=colsum[j]+a[i][j]; printf(“%d\n”,rowsum[i]);
} }
printf("\n“);
for(i=0;i<n;i++)
5/3/2024 printf("\t %d”,colsum[i]); 14
396
Two Dimensional Character Arrays
These are array of arrays. 2-D character array consists of strings as its individual elements.
Declaration :-
char array_of_strings[no_of-strings][no_of_chars];
char a[10][10];
Initialization:-
char a[10][20]={
“aaa”,
“bbb”,
“ccc”
};
5/3/2024 CSE 1001 Department of CSE 15
397
Sorting n names in alphabetical order
for(i=0;i<no-1;i++)
int main() for(j=i+1;j<no;j++)
{ {
char string[30][30],temp[30]; if(strcmp(string[i],string[j])>0)
int no, i, j; {
printf("\nEnter the no of strings:“); strcpy(temp,string[i]);
scanf(“%d”,&no); strcpy(string[i],string[j]);
printf("\nEnter the strings:“); strcpy(string[j],temp);
for(i=0;i<no; i++) }
gets(string[i]); }
}
Printf("\nThe sorted array is:“);
for(i=0;i<no;i++)
puts(string[i]);
return 0;
5/3/2024 CSE 1001
398 }
Department of CSE 16
Multiplication of two Matrices printf("enter elements for a \n“);
scanf(“%d %d”,&m,&n); }
printf("\n enter dimension for b\n“); printf("\n enter elements for b\n“);
if(n!=p){ { for(j=0;j<q;j++)
exit(0); } }
CSE 1001 Department
399of CSE 5/3/2024 17
Multiplication of two Matrices
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
printf("\n The product matrix is \n“);
}
for(i=0;i<m;i++)
}
{
for(j=0;j<q;j++)
printf(“%d\t“,c[i][j]);
printf("\n“);
}
CSE 1001 Department
400of CSE 5/3/2024 18
Exchange the elements of principal diagonal with secondary diagonal in
an N dimensional Square matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(i==j){
temp=arr[i][j];
arr[i][j]=arr[i][n-i-1];
arr[i][n-i-1]=temp;
}
int main(){
printf("\nModified Matrix:\n“);
int i, j, temp, arr[4][4],n;
for(i=0;i<n;i++){
for(j=0;j<n;j++)
printf("\nEnter dimension: “);
printf(" “);
scanf(“%d”,&n);
Printf(“%d”,arr[i][j]);
printf("\n“);
printf(“\nEnter elements:\n");
}
for(i=0;i<n;i++)
return 0;
for(j=0;j<n;j++)
}
scanf(“%d”,&arr[i][j]);
5/3/2024 CSE 1001 Department of CSE 19
401
Exchange the Rows and Columns of a
‘mxn’ matrix /*read ‘mxn’ matrix */
printf("\nEnter the rows to exchange: “);
scanf(“%d %d”,&r1,&r2);// r1=1 and r2=2
/*Row exchange r1 r2 */
for(j=0;j<n;j++) {
temp=arr[r1-1][j];
arr[r1-1][j]=arr[r2-1][j];
arr[r2-1][j]=temp; }
- Compiler will allocate a memory location for Quantity and places the
value in that location. Suppose the address of that location is 5000, then
• Once a pointer variable has been declared, it can be made to point to a variable
using an assignment statement :
int *p = &Quantity ;
Such variables that hold memory
addresses are called
Pointer Variables.
Now…
v = 3; //assigns 3 to v
return 0;
}
5/3/2024 CSE 1001 Department of CSE 13
416
Example - Accessing via pointers.
#include <stdio.h>
int main()
{
int var1, var2; //two integer variables
int *ptr; //pointer to integers
ptr = &var1; //set pointer to address of
*ptr = 37; //same as var1=37 ( Dereferencing)
var2 = *ptr; //same as var2=var1
printf(“%d”, var2); //verify var2 is 37
return 0;
}
{
Output :
firstvalue is 10
int firstvalue = 5, secondvalue = 15;
return 0;
if (p1==p2)
printf(“p1 and p2 points to same location”);
if (p1!=p2)
printf(“p1 and p2 NOT pointing to same location”);
return 0;
}
5/3/2024 CSE 1001 Department of CSE 29
432
Array accessing using Pointers - Example
// array accessed with pointer
#include <stdio.h>
int main()
{
int arr[5] = { 31, 54, 77, 52, 93 };
int* ptr; //pointer to arr
ptr = arr; //points to arr
for(int j=0; j<5; j++) //for each element,
printf("%d ", *ptr++);
return 0;
}
“ptr” is a pointer which can be used to access the elements.
Element in 2d represented as
*(*(a+i)+j)
or
*(*(p+i)+j)
OUTPUT:
Integer variable is = 7
Float variable is = 7.600000
SI_CI(&p,&r,&n,&SI,&CI);
return 0;
} CSE 1001
462
Department of CSE 19
void SI_CI(float *pr, float *ra, int *yr, float *smp, float
*cmp)
{
int amount;
// Simple interest
*smp = ((*pr)*(*ra)*(*yr)/100);
// Compound interest
amount= (*pr)*pow((1 +(*ra)/100),(*yr));
*cmp= amount-(*pr);
}
A child couldn't sleep, so her mother told a story about a little frog,
who couldn't sleep, so the frog's mother told a story about a little
bear,
who couldn't sleep, so bear's mother told a story about a little
weasel
...who fell asleep.
...and the little bear fell asleep;
...and the little frog fell asleep;
...and the child fell asleep.
▪ Recursive steps:
▪ Identify the base case for the algorithm.
▪ Call the same function recursively with the parameter
having slightly modified value during each call.
▪ This makes the algorithm move towards the base case and
finally stop the recursion.
So factorial(5)
= 5* factorial(4)
= 4* factorial(3)
= 3*factorial(2)
= 2* factorial(1)
= 1*factorial(0)
5/3/2024 CSE 1001
=1
Department of CSE 28
470
Factorial- recursive procedure
#include <stdio.h>
long factorial (long a) {
if (a ==0) //base case
return (1);
return (a * factorial (a-1));
}
int main () {
long number;
printf("Please type a number: “);
scanf(“%d”, number);
printf(“number ! = %d”, factorial (number));
return 0;
}
x =24 = 120
5 rFact(4)
factorial(0) = 1
factorial(n) = n * factorial(n-1) [for n>0] 2
x
rFact(1) =1 = 2
472
Fibonacci Numbers: Recursion
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) [for n>1]
So fibonacci(4)
= fibonacci(3) + fibonacci(2)
= (fibonacci(2) + fibonacci(1)) + (fibonacci(1) + fibonacci(0))
= ((fibonacci(1) + fibonacci(0)) + 1) + (1 + 0)
= ( 1 + 0 ) + 1) + (1 + 0)
=3
int main(void){
int n,i, a[20], fibo;
printf("enter any num to n\n“);
scanf(“%d”, n);
printf(“Fibonacci series “);
for (i=1; i<=n; i++)
{
fibo = rfibo(i);
printf(“%d”, fibo);
}
return 0;
}
5/3/2024 CSE 1001 Department of CSE 33
475
Static Variable:
The value of static variable persists until the end of the
program.
Static variables can be declared as
static int x;
A static variable can be either an internal or external
type depending on the place of declaration.
void fnStat( );
Output:
int main() { void fnStat( ){ x=1
int i; static int x = 0; x = 12
for( i= 1; i<=3; i++) x = x + 1;
fnStat( ); x = 13
printf(“x=%d”, x);
return 0; }
5/3/2024 } CSE 1001 Department of CSE 34
476
GCD: Recursion
• Pros • Cons
– Recursion is a – Recursive programs
natural fit for typically use a large
recursive problems amount of computer
memory and the greater
the recursion, the more
memory used
– Recursive programs can
be confusing to develop
and extremely
complicated to debug
RECURSION ITERATION
result = sum(number);
Output:
Enter a positive integer: 10
printf("sum=%d", result); Sum= 55
}
return 0; Output:
Enter a positive integer number: 123
} Number of digits is: 3
5/3/2024 CSE 1001 Department of CSE 44
486
Extra Problem-Reversing a Number
#include <stdio.h>
int length(char [], int); int length(char str[], int index)
{
int main() if (str[index] == '\0')
{ {
char str[20];
return 0;
int count;
}
printf("Enter any string :: "); return (1 + length(str, index + 1));
scanf("%s", str); }
count = length(str, 0);
printf("The length of string=%d.\n",count);
return 0; Output:
}
Enter any string :: Manipal
The length of string= 7
5/3/2024 CSE 1001 Department of CSE 46
488
Extra Problem-Binary Search
#include<stdio.h>
int binarySearch(int x[],int element,int start,int end);
int main(){
int x[20],n,i,index,start=0,end,element;
printf("Enter number of elements: ");
scanf("%d",&n);
end = n;
printf("Enter array elements: ");
for(i=0;i<n;i++){
scanf("%d",&x[i]);
}
printf("Enter the element to search: ");
scanf("%d",&element);
index = binarySearch(x,element,start,end-1);
if(index == -1)
printf("Element Not Found.\n");
else
printf("Element found at index : %d\n",index);
5/3/2024 return 0; CSE 1001 Department of CSE 47
489
Extra Problem-Binary Search
int binarySearch(int x[],int element,int start,int end){
int mid,noOfElements,i;
mid = (int)(start+end)/2;
if(start > end)
return -1;
if(x[mid] == element)
return mid;
else if(x[mid] < element){
start = mid+1;
binarySearch(x,element,start,end);
}
else{
start = 0;
end = mid-1;
}
binarySearch(x,element,start,end);
Output:
Enter number of elements: 5
} Enter array elements: 1 2 3 4 5
Enter the element to search: 3
Element found at index : 2
5/3/2024 CSE 1001 Department of CSE 48
490
Extra Problem- Recursive Sorting
Base Case:
if length of the list (n) = 1
No sorting, return
Recursive Call:
1. Find the smallest element in the list and place it in the 0 th
position
2. Sort the unsorted array from 1.. n-1
sortR(&list[1], n-1)
{-2,33,0,2,4} sort(&list[1],4)
{-2,0,33,2,4} sort(&list[1],3)
{-2,0,2,33,4} sort(&list[1],2)
{-2,0,2,4,33} sort(&list[1],1)
✓Structures
struct structure_name
{
data_type member1;
data_type member2;
…
};
struct Date
{
Members of the
int day; structure Date
int month;
int year;
};
Name Name
Student1 Id Gender Id Gender Student2
Dept Dept
struct student
{
int rollno;
int age;
char name[10];
float height;
}s1, s2, s3; /* Defines 3 variables of type student */
Members of a structure themselves
are not variables. i.e. rollno alone does
not have any value or meaning.
COMP
Assigning string:
strcpy(s1.name, “Rama”);
struct student
{
Assignment statement: int rollno;
int age;
s1.rollno = 1335; char name[20];
s1.age = 18; float height;
}s1;
s1.height = 5.8;
struct Student
int main ( ) {
{ int rollno;
struct Student int age;
{ } s1={20, 21};
int rollno;
int age; main ( )
}; {
Student s1={20, 21}; Student s2={21, 21};
Student s2={21, 21}; …
} …
}
Solution A (2 marks)
Page 1 of 8
510
Solution
#include <stdio.h>
int main()
{
/*
• Declare a variable named ‘marks’ of type ‘double’. 6 CO3
• Read the value of ‘marks’ from user.
• Prints one the following messages based upon the value of ‘marks’
(i) Prints “Grade A” if ‘marks’ is greater than 90
(ii) Prints “Grade B” if 80 < marks <=90
(iii) Prints “Grade C” if 70 < marks <=80
(iv) prints “Grade Fail” if marks <=70
Page 2 of 8
511
*/
}// End of Main
int main() {
// Declare a variable named 'marks' of type 'double'. (1 Marks
double marks;
// Prints one of the following messages based on the value of 'marks'. (4 marks)
if (marks > 90) {
printf("Grade A\n");
} else if (marks > 80 && marks <= 90) {
printf("Grade B\n");
} else if (marks > 70 && marks <= 80) {
printf("Grade C\n");
} else {
printf("Grade Fail\n");
}
return 0;
}
Q B2 Write an algorithm to check whether a given number is prime or not and draw the
corresponding flowchart.
6 CO1
Solution (i) For correct algorithm (3 Marks)
(ii) For Correct Flowchart (3 Marks)
Q B3 A flowchart is given (shown below) to find and display the square and cube of a
positive number. The execution must be terminated if a negative number is entered.
6 CO1
Page 3 of 8
512
The above flowchart has some errors which are indicated with (1), (2), (3) and (4).
Answer the following questions to give the correct result.
(a) What will be the correct representation of the box in (1)?
(b) What will be the correct logic for the variable N in (2)?
(c) Out of the flow lines (3) and (4), which one is undesirable?
(d) When all the corrections are made, what will be the output, if the input value is
taken as 12?
Solution (a) The correct representation of the box in (1) is a parallelogram or input/output
box. (1.5 Marks)
(b) The logic for the variable N in (2) will be - If N>0? (1.5 Marks)
(c) Flow line (4) is undesirable. (1.5 Marks)
(d) The output will be 144, 1728. (1.5 marks)
Page 4 of 8
513
of swapping two numbers.
a. Identify and correct the error in the loop condition that may lead to
accessing memory beyond the array bounds.
b. Debug any logical errors preventing the correct calculation of the product of
the first five prime numbers.
c. Explain why the original loop condition was incorrect and how your
correction addresses the issue.
d. Suggest an alternative loop condition that would also work correctly for
iterating through the array.
Complete the missing logic in the code to display the product of the first five prime
numbers correctly.
Page 5 of 8
514
Solution (a) The original loop condition i < sizeof(primes) was incorrect. The corrected
condition is i < sizeof(primes) / sizeof(primes[0]), which gives the number
of elements in the array. (2 marks)
(b) The loop logic was correct after fixing the loop condition. (1 marks)
(c) The original loop condition was incorrect because it compared the loop
index i with the total size in bytes of the array. The correction divides the
total size by the size of one array element, ensuring that the loop iterates
over each element. (1 marks)
(d) An alternative loop condition could be i < 5, which directly specifies the
number of elements in the array. This would work correctly for iterating
through the array, given that we know there are five elements. (2 marks)
Q C2
Write a C program that accomplishes the following tasks step by step:
a. Declare three 2-D arrays named "K1," "K2," and "K3" of type "int" with
dimensions 2*2.
b. Read the values for the 2-D arrays "K1" and "K2."
c. Multiply the corresponding elements of "K1" and "K2" and store the results
in the 2-D array "K3."
d. Display the contents of the resulting 2-D array "K3."
Ensure the program is structured to perform these tasks sequentially and provide
the code for each step.
Page 6 of 8
515
(c) for (int i = 0; i < 2; ++i) ( 3 Marks)
{
for (int j = 0; j < 2; ++j)
{
K3[i][j] = K1[i][j] * K2[i][j];
}
}
Page 7 of 8
516
Q D2 Consider a scenario where you are tasked with developing a program in C to
manage employee inventory. The program should utilize structures to handle
employee information. The program should perform the following tasks:
printf("\nEmployee 2 Details:\n");
printf("Employee ID: %d\n", employee2.Employee_ID);
printf("First Name: %s\n", employee2.First_Name);
printf("Salary: %.2f\n", employee2.Salary);
Page 8 of 8
517