[go: up one dir, main page]

0% found this document useful (0 votes)
34 views517 pages

PSUC

Uploaded by

shreyanshu.8705
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views517 pages

PSUC

Uploaded by

shreyanshu.8705
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 517

Digital computer

• A digital computer is a digital system that performs various


computational tasks and represented by variables with the limited
number of discrete values.

• The discrete values are internally processed with limited number of


discrete states. The decimal digits 0,1,2,…,9 provide 10 discrete
values. Mostly all discrete values are available in the form of
American Standard Code for Information Interchange (ASCII)

• Where the first electronic digital computers developed in 1940. From


here the term digital computer emerged because of many restrictions
with other discrete values.

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.

• Software: It consists of the instructions and data that the computer


manipulates to perform various data-processing tasks. Where sequence of
instruction is called a program.

3
Von Neumann Architecture
• Von-Neumann computer architecture design was proposed in 1945. It
was later known as Von-Neumann architecture.

• Historically there have been 2 types of Computers:

1. Fixed Program Computers – Their function is very specific and they


couldn’t be reprogrammed, e.g. Calculators.

2. Stored Program Computers – These can be programmed to carry out


many different tasks, applications are stored on them, hence the name
is.

4
Von Neumann architecture… Cont’d
• Modern computers are based on a
stored-program concept introduced by
John Von Neumann.

• In this stored-program concept,


programs and data are stored in a
separate storage unit called memories
and are treated the same.

• This novel idea meant that a computer


built with this architecture would be
much easier to reprogram.
5
Von Neumann architecture is also known as ISA (Instruction set architecture)
computer and is having three basic units: Central Processing Unit (CPU), Main
Memory Unit and Input/Output Unit.

1. Central Processing Unit-


The central processing unit is defined as an electric circuit used for the executing the
instruction of computer program. It has following major components:
1.Control Unit(CU)
2.Arithmetic and Logic Unit(ALU)
3.variety of Registers

• 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.

• Primary storage is a fast memory. The memory contains large number of


semiconductor storage cells, each cell capable of one bit of information. These
cells are rarely used as an individual cell instead are processed in group of fixed
size, called words.

• To provide an easy access of any word in memory, a distinguished address is


associated with each word location. Addresses are numbers that identify
successive locations. The typical word lengths range from 16 to 64 bits.

• 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.

• Although primary storage is essentials and expensive. But in addition to


the same cheaper memory is available as a secondary memory storage,
where large amount of data and many programs may be stored.

• A wide range of secondary storage are available in the form of magnetic


disks, tapes and opticals disks (CD-ROMS).

11
Memory unit

➢The computer memory is measured in terms of bits, bytes and


words.

➢A bit is a binary digit either 0 or 1.

➢A byte is unit of memory and is defined as sequence of 8 bits.

➢The word can be defined as a sequence of 16/32/64 bits or 2/4/8


bytes respectively depending on the machine architecture
3
12
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
4
13
Secondary memory

➢Main memory is volatile and limited


➢ Hence it is essential for other types of storage devices where programs and
data can be stored when they are no longer being processed

➢Installed within the computer at the factory or added later as needed

5
14
Secondary memory
➢Non-volatile memory

➢Made up of magnetic material

➢Stores large amount of information for long time

➢Low speed

➢Holds programs not currently being executed

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.

▪ In contrast to low-level programming languages, it may


use natural language elements, be easier to use, or may
automate (or even hide entirely) significant areas of computing
systems (e.g. memory management), making the process of
developing a program simpler and more understandable than
when using a lower-level language.

▪ The amount of abstraction defines how "high-level" a


programming language is provided.

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.

3. It is easy to understand. It is tough to understand.

4. Debugging is easy. Debugging is complex comparatively.

5. It is simple to maintain. It is complex to maintain comparatively.

6. It is portable. It is non-portable.

7. It can run on any platform. It is machine-dependent.

It needs compiler or interpreter for


8. It needs assembler for translation.
translation.

9. It is used widely for programming. It is not commonly used now-a-days in programming.


20
Compiler
• A Translator (compiler) is a program that reads a program written in
one language, the source language, - and translate it into an
equivalent program in another language, the target language.

• In computing, a compiler is a computer


program that translates computer code written in one programming
language (the source language) into another language
(the target language).

• The name "compiler" is primarily used for programs that


translate source code from a high-level programming language to
a low-level programming language (e.g. assembly language, object
code, or machine code) to create an executable program
21
Assembly Language
Assembly Language is a low-level programming language. It helps in
understanding the programming language of machine code.
• Machine code is a series of instructions that provide
the necessary information to a user’s CPU to carry out a
particular task (add, subtract, compare values, etc.).

• In computers, there is an assembler that helps in


converting the assembly code into machine code
executable.

• It establishes with the help of compiling high-level


language source code like C and C++.

• It mainly depends on the system architecture, whether


it is an operating system or computer architecture to
add assembler?
22
Introduction to Computing

23
Objectives
To learn and appreciate the following concepts

✓Problem solving basics


✓Logic and its importance in problem solving
✓Various computational problems and its classification
✓Computer Organization and operating system
✓Different types of languages
✓History of C, Typical C program development environment.

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)

• The process part(Eg: summation) of the solution requires logic( How to


sum) or in other words based on the logic, process is developed.

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

➢ Consists of two functional units


▪ Control Unit (CU)
▪ Arithmetic and Logic Unit (ALU)

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

➢Each cell has its own unique address

➢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.

➢A bit is a binary digit either 0 or 1.

➢A byte is unit of memory and is defined as sequence of 8 bits.

➢The word can be defined as a sequence of 16/32/64 bits or 2/4/8 bytes


respectively depending on the machine architecture

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

➢Main memory is volatile and limited


➢ Hence it is essential for other types of storage devices where programs and data
can be stored when they are no longer being processed

➢Installed within the computer at the factory or added later as needed

24
46
Secondary memory
➢Non-volatile memory

➢Made up of magnetic material

➢Stores large amount of information for long time

➢Low speed

➢Holds programs not currently being executed

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.

➢ It acts as an interface between the man and machine.

➢ It manages the system resources like memory, processors, input-output


devices and files.

➢Windows, Linux, DOS

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

➢Character set is a Letters → ‘a’, ‘b’, ‘c’,………..’z’ Or ‘A’, ‘B’, ‘C’,……….’Z’


set of valid
characters that a
language can
recognize.
Digits → 0, 1, 2,……………………9

➢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

✓A token is a group of Special


characters that Keywords Identifiers Operators Strings Constants
Symbols
logically belong
together. Break Variable + “hello” 123 ;
✓The programmer
writes a program by Int Constant * “123” 21.3 ?
using tokens.
✓C uses the following Function
float % “s” ‘A’ >
name
types of tokens.
Array
‘g’ &
name

“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(“You can learn it easily ”); /*add comment*/

printf(“easily\n”);
}

7
62
Input: Scanf()
#incude<stdio.h>

Scanf() is used to obtain void main()


the value from the user {
int num;
It is included in stdio.h
printf(“Enter a number = ”);

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

%c Read a single character

%d Read a decimal integer

%f Read a floating point number

%g Read a short int number

%h Read a short int number

%i Read a decimal or hexadecimal or octal number


10
65
C Program Essentials: Format Specifiers
Format specifier Description
%d or %i It is used to print the signed integer value where signed integer means that
the variable can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer
means that the variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value
always starts with a 0 value.
%x It is used to print the hexadecimal unsigned integer where the hexadecimal
integer value always starts with a 0x value. In this, alphabetical characters
are printed in small letters such as a, b, c, etc.
%X It is used to print the hexadecimal unsigned integer, but %X prints the
alphabetical characters in uppercase such as A, B, C, etc.
%f It is used for printing the decimal floating-point values. By default, it prints
the 6 values after '.'.
11
66
C Program Essentials: Format Specifiers
Format specifier Description
%f It is used for printing the decimal floating-point values. By default, it prints
the 6 values after '.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.
%g It is used to print the decimal floating-point values, and it uses the fixed
precision, i.e., the value after the decimal in input would be exactly the
same as the value in the output.
%p It is used to print the address in a hexadecimal form.
%c It is used to print the unsigned character.
%s It is used to print the strings.
%ld It is used to print the long-signed integer value.

12
67
Output: Printf()

C provides the printf() to display the data on the monitor.

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

Syntax errors: violation of programming


language rules (grammar).
• Detected by the compiler
• Eg: printf (“hello world”) // semicolon missing

Logical errors: errors in meaning:


• Programs are syntactically correct but don’t produce the
expected output
• User observes output of running program

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

These are some reserved words in C which have


predefined meaning to compiler called keywords.

Keywords are not to be used as variable and


constant names.

All keywords have fixed meanings and these


meanings cannot be changed.

2
80
Compiler specific keywords (32)

Some commonly used keywords are given below:

3
81
Constants

Constants are data values that cannot be changed


during the execution of a program. Like variables,
constants have a type. In this section, we discuss
Boolean, character, integer, real, complex, and string
constants.

Topics discussed in this section:


Constant Representation
Coding Constants

4
82
Note
A character constant is enclosed in single quotes.

Use single quotes for character constants.


Use double quotes for string constants.

5
83
Examples of Constant

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint"


etc.

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?

Characters and Strings its definitions are defined, but \0 is an explicit


representation where as in “” is an implicit representation?
10
88
Symbolic Names for Control
Characters

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.

For example, const int =10; is a constant integer


expression in which 10 is an integer literal.

There are four types of literals that exist in C programming:


◼ Integer literal

◼ 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

Variables are the symbolic names for storing computational data.

Variable: a symbolic name for a memory location

In C variables have to be declared before they are used Ex:


int x;

A variable may take different values at different times


during execution.

Declarations reserve storage for the variable.

Value is assigned to the variable by initialization or assignment


16
94
Variable declarations

Data type Variable name;

Which data types Which variable names


are possible in C ? are allowed in C ?

17
95
Variable Names- Identifiers

Symbolic names can be used in C for various data items


used by a programmer.

A symbolic name is generally known as an identifier. An


identifier is a name for a variable, constant, function, etc.

The identifier is a sequence of characters taken from C


character set.
18
96
Variable names
Rules for valid variable names (identifiers) :

Name must begin with a letter or underscore ( _ ) and can


be followed by any combination of letters, underscores, or
digits.

Key words cannot be used as a variable name.

C is case-sensitive: sum, Sum, and SUM each refer to


a different variable.
Examples:
Sum
Variable names can be as long as you want, although _difference
only the first 63 (or 31) characters might be
a
significant.
J5x7
Number_of_moves
Choice of meaningful variable names can increase the 3val
readability of a program int
19
97
Declaring variables
• C imposes to declare variables before their usage.
• Advantages of variable declarations:

Putting all the variables in one place makes it easier for a reader
to understand the program.

Thinking about which variables to declare encourages the


programmer to do some planning before writing a program.

The obligation to declare all variables helps prevent bugs


of misspelled variable names.

Compiler knows the amount of memory needed for storing


the variable.

Compiler can verify that operations done on a variable are


allowed by its type.
20
98
Using and Displaying Variables
#include <stdio.h>
int main ()
{
int sum;
sum = 50 + 25;
printf("The sum of 50 and 25 is%d”,sum);
return 0;
}

Variable sum declared of type int


Variable sum assigned expression 50+25
Value of variable sum is printed

21
99
Variables - Examples

int a; // declaring a variable of type int

int sum, a1, a2; // declaring 3 variables

int x = 7; // declaring and initializing a variable

a = 5; // assigning to variable a the value 5

a1 = a; // assigning to variable a1 the value of a

L-value R-value

a1=a1+1; // assigning to variable a1 the value of a1+1


// (increasing value of a1 with 1)

22
100
Data types

101
Comes under the category

2
102
Primary (built-in or Basic)Data types

INTEGER CHARACTER

SIGNED TYPE UNSIGNED TYPE


INT UNSIGNED INT SIGNED CHARACTER
SHORT INT UNSIGNED SHORT INT UNSIGNED CHARACTER
LONG INT UNSIGNED LONG INT

FLOATING POINT TYPE VOID


FLOATING POINT TYPE
FLOAT VOID
DOUBLE
LONG DOUBLE

3
103
Data types
Basic data types: int, float, double, char, and void.

int: can be used to store integer numbers (values with no


decimal places).

float: can be used for storing floating-point numbers


(values containing decimal places).

double: the same as type float, and roughly twice the


size of float.

char: can be used to store a single character, such as


the letter a, the digit character 6, or a semicolon.

void: is used to denote nothing or empty.

4
104
Integer Types

The basic integer type is int


• The size of an int depends on the machine and
on PCs it is normally 16 or 32 or 64 bits.
modifiers (type specifiers)
• short: typically uses less bits
• long: typically uses more bits
• Signed: both negative and positive numbers
• Unsigned: only positive numbers
5
105
SIZE AND RANGE OF VALUES FOR A 16-BIT
MACHINE (INTEGER TYPE)

Type Size (bits) Range

short int or
signed short int 8 -128 to 127
short
unsigned int
8 0 to 255

int or signed int 16 -32,768 to 32,767


Integer
unsigned int 16 0 to 65,535
long int or
-2,147,483,648 to
signed long int 32
Long 2,147,483,647

unsigned long int 32 0 to 4,294,967,295

6
106
The character type char

A char variable can be used to store a single character.

A character constant is formed by enclosing the character within a


pair of single quotation marks. Valid examples: 'a’ .

Character zero ( ‘0’ ) is not the same as the number (integer


constant) 0.

The character constant ‘\n’—the newline character—is a valid


character constant. It is called as an escape character.

There are other escape sequences like, \t for tab, \v for vertical tab, \n
for new line etc.

7
107
Character Types

Character type char is related to the integer type.

Modifiers(type specifiers) unsigned and signed can be used


• char →1 byte (-128 to 127)
• signed char →1 byte (-128 to 127)
• unsigned char →1 byte (0 to 255)

ASCII (American Standard Code for Information Interchange ) is


the dominant encoding scheme for characters.
• Examples
• ' ' encoded as 32 '+' encoded as 43
• 'A' encoded as 65 …………………….'Z' encoded as 90
• 'a' encoded as 97 ……………………. 'z' encoded as 122
• ‘0’ encoded as 48 ……………………..’9’ encoded as 57
8
108
Assigning values to char
char letter; /* declare variable letter of type char */

letter = ‘A'; /* OK */

letter = A; /* NO! Compiler thinks A is a variable */

letter = “A"; /* NO! Compiler thinks “A" is a string */

letter = 65; /* ok because characters are internally stored


as numeric values (ASCII code) */

9
109
Floating-Point Types

Floating-point types represent real numbers


• Integer part
• Fractional part

The number 108.1517 breaks down into the following parts


• 108 - integer part
• 1517 - fractional part

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.

There are three floating-point type specifiers


• float
• double
• long double
10
110
SIZE AND RANGE OF VALUES FOR 16-BIT MACHINE
(FLOATING POINT TYPE)

Type Size

32 bits
Single Precision Float
4 bytes

64 bits
Double Precision double 8 bytes

Long Double 80 bits


long double
Precision 10 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

Data Types Memory Size Range


char 1 byte −128 to 127
signed char 1 byte −128 to 127
unsigned char 1 byte 0 to 255
short 2 byte −32,768 to 32,767
signed short 2 byte −32,768 to 32,767
unsigned short 2 byte 0 to 65,535
int 2 byte −32,768 to 32,767
signed int 2 byte −32,768 to 32,767
unsigned int 2 byte 0 to 65,535

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;

printf("size of short = %d bytes\n", sizeof(a));


printf("size of long = %d bytes\n", sizeof(b));
printf("size of long long = %d bytes\n", sizeof(c));
printf("size of long double= %d bytes\n", sizeof(d));
return 0;
}

15
115
Best Practices for Programming
Naming Variables According to Standards

Prefix Data Type Example

✓i int and unsigned int iTotalMarks


✓f float fAverageMarks
✓d double dSalary
✓l long and unsigned long lFactorial
✓c signed char and unsigned char cChoice
✓ai Array of integers aiStudentId
✓af Array of float afQuantity
✓ad Array of double adAmount
✓al Array of long integers alSample
✓ac Array of characters acEmpName
16
116
Example: Using data types
#include <stdio.h>
int main ()

{
int integerVar = 100;
float floatingVar = 331.79;
double doubleVar = 144368.4411;
char charVar = 'W';
printf(“%d\n”, integerVar);
printf(“%f\n”,floatingVar);
printf(“%lf\n”,doubleVar);
printf(“%c\n”,charVar);
return 0;
}

17
117
Operators: Arithmetic,
Relational, Logical,
Assignment

118
Operators
The different operators are:

Arithmetic Relational Logical

Increment and
Bitwise Assignment
Decrement

Conditional

2
119
Arithmetic Operators
The binary arithmetic operators are +, -, *, / and the modulus
operator %.

The / operator when used with integers truncates any


fractional part i.e. E.g. 5/2 = 2 and not 2.5

Therefore % operator produces the remainder when 5 is


divided by 2 i.e. 1

The % operator cannot be applied to float or double

E.g. x % y wherein % is the operator and x, y are operands

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

• Basic arithmetic operators: +, -, *, /, %


• Precedence: One operator can have a higher priority, or
precedence, over another operator. The operators within C are
grouped hierarchically according to their precedence (i.e., order
of evaluation)

6
123
Working with arithmetic expressions

• Operations with a higher precedence are carried out before


operations having a lower precedence.
High priority operators * / % …
Low priority operators + - …

Example: * has a higher precedence than +


a + b * c → a+(b*c)

• If necessary, you can always use parentheses in an


expression to force the terms to be evaluated in any desired
order.

7
124
Working with arithmetic expressions

• Associativity: Expressions containing operators of the same


precedence are evaluated either from left to right or from right
to left, depending on the operator. This is known as the
associative property of an operator

Example: + has a left to right associativity

For both the precedence group described above, associativity


is “left to right”.

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.

#include <stdio.h> Output:


int main() { 5
6
int var1 = 5, var2 = 5;
// 5 is displayed, Then, var1 is increased to 6.
printf("%d\n", var1++);
// var2 is increased to 6 , Then, it is displayed.
printf("%d\n", ++var2);
return 0;
} 11
128
Increment and Decrement Operators
#include <stdio.h>
int main()
{
int a = 10, b = 100; Output:
++a = 11
float c = 10.5, d = 100.5; --b = 99
++c = 11.500000
printf("++a = %d \n", ++a); --d = 99.500000
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

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

Prefix Mode Postfix Mode


Ex: Ex:
m=5; m=5;

y=++m; Prefix Mode y=m++; Postfix Mode

Here y continues to be 5. Only m


In this case, the value of y and m
changes to 6.
would be 6.
Postfix operator ++ appears after
Prefix operator ++ appears before the variable
the variable.

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

++(x + 1) is a syntax error

15
132
Relational operators
Operator Meaning
== Is equal to

!= Is not equal to

< Is less than

<= Is less or equal

> Is greater than

>= Is greater or equal

The relational operators have lower precedence than all


arithmetic operators:
a < b + c is evaluated as a < (b + c)

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.

ae1 relational operator ae2

ae1 & ae2 are arithmetic expressions, which may be simple


constants, variables or combinations of them.
17
134
Relational operators
The arithmetic expressions will be evaluated first & then the results
will be compared. That is, arithmetic operators have a higher priority
over relational operators. > >= < <= all have the same precedence
and below them are the next precedence equality operators i.e. == and
!=
Suppose that i, j and k are integer variables whose values
are 1, 2 and 3 respectively.

Expression Interpretation Value


i<j true 1
(i+j)>=k true 1
(j+k)>(i+5) false 0
k!=3 false 0
j==2 true 1

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

Operator Symbol Example


AND && expression1 && expression2
OR || expression1 || expression2
NOT ! !expression1

The result of logical operators is always either 0 (FALSE) or 1 (TRUE)

19
136
Logical operators
Expressions Evaluates As

(5 == 5)&&(6 != 2) True (1) because both operands are true

(5 > 1) || (6 < 1) True (1) because one operand is true

(2 == 1)&&(5 ==5) False (0) because one operand is false

! (5 == 4) True (1) because the operand is false

!(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;

• Example: precedence of op=:


a /= b + c
• Equivalent to:
a = a / (b + c) 22
139
Bitwise operators
• In arithmetic-logic unit (which is within the CPU),
mathematical operations like: addition, subtraction,
multiplication and division are done in bit-level.

Operators Meaning of operators


& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
<< Shift left
>> Shift right

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)

12 = 00001100 (In Binary) 35 = 00100011 (In Binary)


25 = 00011001 (In Binary)
Bitwise complement Operation of 35
Bitwise XOR Operation of 12 and 25 ~ 00100011
00001100 ________
^ 00011001 11011100 = 220 (In decimal)
________
00010101 = 21 (In decimal)

Bitwise complement of any number N is -(N+1) 24


141
Conditional Operator

The conditional operator is also known as a ternary operator. The


conditional statements are the decision-making statements which depends
upon the output of the expression. It is represented by two symbols, i.e., '?'
and ‘:’.

• Syntax of a conditional operator


Expression1? expression2: expression3;

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

Bitwise Logical Operators

Bitwise Shift Operators

Ones Complement operator

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

Same way |,^ according to the table are computed.

4
149
Bitwise Shift operators

<< ,>>

These are used to move bit patterns either to the left


or right.

They are used in the following form

• 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.

The leftmost n bits in the original bit


pattern will be lost and the rightmost n
bits that are vacated are filled with 0’s

6
151
Bitwise Shift operator: >>

>> causes all the bits in operand op


to be shifted to the right by n
positions.

The rightmost n bits will be lost and


the left most vacated bits are filled
with 0’s if number is unsigned integer

7
152
Examples
Suppose X is an unsigned integer whose bit pattern is 0000
0000 0000 1011

✓x<<1 0000 0000 0001 0110 Add ZEROS

✓x>>1 Add ZEROS 0000 0000 0000 0101

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

Op and n can be constants or variables.

There are 2 restrictions on the value of n

• 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)

▪Also called as 1’s complement operator.

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);

// The result is 11111010


printf("~a = %d\n", a = ~a);

// The result is 00010010


printf("b<<1 = %d\n", b << 1);

// The result is 00000100


printf("b>>1 = %d\n", b >> 1);

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::

The & operator can be used to quickly check if a number is odd or


even. The value of expression (x & 1) would be non-zero only if x is odd,
otherwise the value would be zero.

The ~ operator should be used carefully. The result of ~ operator on a


small number can be a big number if the result is stored in an unsigned
variable. And the result may be a negative number if the result is stored
in a signed variable

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.

• When sizeof() is used with the expression, it returns size of the


expression.
int main()
{
int a = 0;
double d = 10.21;
printf("%lu", sizeof(a + d));
return 0;
}
Output: ??

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).

int i = (5, 10); // Value of i will be assigned as 10

▪ The comma operator has the lowest precedence of any C operator.


▪ The comma operator is used basically to separate expressions.
i = 0, j = 10; // in initialization [ l → r ]
▪ The meaning of the comma operator in the general expression e1, e2 is
“evaluate the sub expression e1, then evaluate e2; the value of the expression is
the value of e2”.

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

• The following expression in the code:


a = 2, 3, 4;
is evaluated as:
(((a = 2), 3), 4);
• This is because the reason that assignment operator has high precedence
over the comma operator.
• Check the output for following:
1. int a = 4, 3; //Error
2. int a; //4 will be assigned
a = 4,3;
3. int a =(4, 3); //3 will be assigned

20
165
The conditional operator (? :)

condition ? expression1 : expression2

• condition is an expression that is evaluated first.


• If the result of the evaluation of condition is TRUE (nonzero), then
expression1 is evaluated and the result of the evaluation becomes the
result of the operation.
• If condition is FALSE (zero), then expression2 is evaluated and its result
becomes the result of the operation.

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*((i/5)+(4*(j-3))%(i+j-2)) i→8, j→5

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)

• Evaluate the following:


1. ( (5 == 5) && (3 > 6) )
2. ( (5 == 5) || (3 > 6) )
3. 7==5 ? 4 : 3
4. 7==5+2 ? 4 : 3
5. 5>3 ? a : b
6. K = (num > 5 ? (num <= 10 ? 100 : 200) : 500); where num =30
• In b=6.6/a+(2*a+(3*c)/a*d)/(2/n); which operation will be performed
first.
• If a is an integer variable, a=5/2; will return a value??
• The expression, a=7/22*(3.14+2)*3/5; evaluates to??
• If a is an Integer, the expression a = 30 * 1000 + 2768; evaluates to??
6
172
Type conversion

173
Type Conversions in Expressions

C permits mixing of constants and variables of different types in an


expression

C automatically converts any intermediate values to the proper type


so that the expression can be evaluated without losing any
signification

This automatic conversion is known as Implicit Type Conversion

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

The final result of an expression is converted to the type of the


variable on the left of the assignment sign before assigning the
value to it

However the following changes are introduced during the final


assignment

• Float to int causes truncation of the fractional part


• Double to float caused rounding of digits
• Long int to int causes dropping of the excess higher order bits

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;

printf("x = %d, z = %f", x, z);


return 0;
}

Output:
x = 107, z = 108.000000

1/25/2024 7
179
Explicit Type Conversions

There are instances when we want to force a type


conversion in a way that is different from the
automatic conversion
• E.g ratio=57/67
• Since 57 and 67 are integers in the program , the decimal part of the
result of the division would be lost and ratio would represent a wrong
figure

This problem can be solved by converting locally as


one of the variables to the floating point as shown
below:
• ratio= (float) 57/67

1/25/2024 8
180
Type Conversions in Expressions

The operator (float) The division is performed


converts the 57 to floating in floating point mode,
point then using the rule thus retaining the
of automatic conversion fractional part of result

The process of such a local The general form of a cast


conversion is known as is
explicit conversion or • (type-name) expression
casting a value

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:

(int) 29.55 + (int) 21.99 results in 29 + 21

(float) 6 / (float) 4 results in 1.5

(float) 6 / 4 results in 1.5

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.

Assign a floating-point value to an integer variable: the decimal


portion of the number gets truncated.

Integer arithmetic (division):

• int divided to int => result is integer division


• int divided to float or float divided to int => result is real division (floating-point)

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

 This notation indicates that 1.504582 is multiplied


by 10 raised to the second power (E+02).
 The E stands for “exponent.”

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

 0.0000875 uses e notation because, when it’s


converted to exponential notation, its exponent (-5) is
less than -4.
 The value 8750000.0 uses e notation because its
exponent (6) is equal to the default precision.
198
 The difference between g and G is identical to the
difference between e and E when the value is printed in
exponential notation—lowercase g causes a lowercase e to
be output, and uppercase G causes an uppercase E to be
output.
 The %E, %e and %g conversion specifiers cause the value to be
rounded in the output and the conversion specifier %f does
not.
 With some compilers, the exponent in the outputs will be
shown with two digits to the right of the + sign.

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) ;

• This function provides for printing exactly one character to the


screen. This function is declared in stdio.h.
• Example:

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: ");

// Reads a character but


// not displays
getch();

return 0;
}

Output::Enter any character:


238
getche()
• getche() function reads a single character from the keyboard by the
user and displays it on the console screen and immediately returns
without pressing the enter key. This function is declared in conio.h.

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 ) ;

• This function is similar to putchar ( ) except the output can be to the


screen or a file.
• Example:
char ch;
ch = getc (stdin) ; /* input from keyboard */
putc (ch, stdout) ; /* output to the screen */
putc (ch, outfileptr) ; /*output to a 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.

✓Selectional (Decision Making and Branching)


▪ In a Selectional approach, based on some conditions, different set of
statements are executed.

✓Iterational (Repetition)
▪ In an Iterational approach certain statements are executed repeatedly.

CSE 1001 Department of CSE 2


2/13/2024
244
245
Different forms of if statement
1. Simple if statement.

2. if…else statement.

3. Nested if…else statement.

4. else if ladder
5. Jump Statements:
break
continue
goto
return

2/13/2024 CSE 1001 Department of CSE 4


246
Simple if Statement
General form of the simplest if statement:

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.

2/13/2024 CSE 1001 Department of CSE 5


247
if Statement- explanation
➢ (test Expression) is first evaluated.

➢ If TRUE (non-zero), the ‘if’ statement block is executed.

➢ If FALSE (zero) the next statement following the if statement block is


executed.

➢ So, during the execution, based on some condition, some


code will not be executed (skipped).

For example: bonus = 0;


if (hours > 70){
bonus = 10000;
}
salary= salary + bonus;

2/13/2024 CSE 1001 Department of CSE 6


248
Flow chart of simple if
Entry

2/13/2024 CSE 1001 Department of CSE 7


249
Find out whether a number is even or odd.
#include <stdio.h>
int main()
{
int x;
printf(“input an integer\n”);
scanf(“%d”,&x);
if ((x % 2) == 0)
{
printf(“It is an even number\n”);
}
if ((x%2) == 1)
{
printf(“It is an odd number\n”);
}
return 0;
2/13/2024 CSE 1001 Department of CSE 8

} 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;
}

2/13/2024 CSE 1001 Department of CSE 9


251
The if-else statement

if (test expression )
{
statement _block1 if-else
} statement:
else enables you to
{ choose between
statement _block2 two statements
}
Next_statement

2/13/2024 CSE 1001 Department of CSE 10


252
if-else statement
Explanation:
1.First ,the (test expression) is evaluated.

2.If it evaluates to non-zero (TRUE), statement_1 is executed,


otherwise, if it evaluates to zero (FALSE), statement_2 is executed.

3.They are mutually exclusive, meaning, either statement_1 is


executed or statement_2, but not both.

4.If the statements_ 1 and statements_ 2 take the form of block ,


they must be put in curly braces.

Example: if(job_code == 1)
rate = 7.00;
else
rate = 10.00;
prinf(“%d”,rate);

2/13/2024 CSE 1001 Department of CSE 11


253
The if-else statement

yes no
expression

Program statement 1 Program statement 2

Next _statement

2/13/2024 CSE 1001 Department of CSE 12


254
Find out whether a number is even or odd.
#include <stdio.h>
int main()
{
int x;
printf(“Input an integer\n”);
scanf(“%d”,&x);
if ((x % 2) == 0)
{
printf(“It is an even number\n”);
}
else
{
printf(“It is an odd number\n”);
return 0;
2/13/2024 } CSE 1001 Department of CSE 13
255
WAP to find largest of 2 numbers

#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;
}

2/13/2024 CSE 1001 Department of CSE 14


256
Attention on if-else syntax !
if ( expression )
program
statement 1
In C++, the ; is
else
part (end) of a
program statement !
statement 2
if ( remainder == 0 )
prinf("The number is even.\n“);
else
printf(“The number is odd.\n“);

Syntactically OK (void
statement on if) but a
semantic error !
if ( x == 0 );
printf(“The number is zero.\n“);

2/13/2024 CSE 1001 Department of CSE 15


257
Example: determine if a year is a leap
year
#include<stdio.h> A leap year is
int main() exactly divisible
{ by 4 except for
int year;
century years
printf(“Enter the year“);
(years ending
scanf(“%d”,&year);
if(year%4 == 0) with 00). The
{ century year is
if( year%100 == 0) a leap year only
{ if it is perfectly
if ( year%400 == 0) divisible by 400.
printf("%d is a leap year",year);
else
printf("%d is not a leap year",year);
} else printf("%d is a leap year",year);
} else printf("%d is not a leap year",year);
return 0;
} 2/13/2024 CSE 1001 Department of CSE 16
258
Testing for character ranges
Output:
enter a
#include<stdio.h> character:
int main() C
{ uppercase char
char ch; special char
printf(“enter a character\n”);
scanf(“%c”,&ch); enter a
if (ch >= 'a' && ch <= 'z') character:
printf(“lowercase char\n“); j
if (ch >= ‘A' && ch <= ‘Z') lowercase char
special char
printf(“uppercase char\n“);
if (ch >= ‘0' && ch <= ‘9')
enter a
printf(“digit char\n“); character:
else 5
printf(“ special char\n”); digit char
return 0;
}
2/13/2024 CSE 1001 Department of CSE 17
259
Testing for ranges

? if (x >= 5 && x <= 10)

range“);
printf(“in

? if (5 <= x <= 10)


printf(“in range“);

2/13/2024 CSE 1001 Department of CSE 18


260
Testing for ranges

YES if (x >= 5 && x <= 10)


printf(“in range“);

NO ! if (5 <= x <= 10)


printf(“in range“);

Syntactically correct, but semantically an error !!!

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 !

2/13/2024 CSE 1001 Department of CSE 19


261
Decision Making,
Branching
nested if-else, if-else ladder

262
Nested if-else Statement

2/13/2024 CSE 1001 Department of CSE 2


263
If-else nesting -Explanation
1. The if-else constructs can be nested (placed one within another)
to any depth.
2. In this nested form, expression_1 is evaluated.
➢ If it is zero (FALSE-F), statement_4 is executed and the entire
nested if statement is terminated;
➢ If not (TRUE-T), control goes to the second if (within the first if)
and expression_2 is evaluated. If it is zero, statement_3 is executed;
➢ If not, control goes to the third if (within the second if) and
expression_3 is evaluated.
➢ If it is zero, statement_2 is executed;
➢ If not, statement_1 is executed. The statement_1 (inner most)
will only be executed if all the if statement is true.

2/13/2024 CSE 1001 Department of CSE 3


264
Smallest among three numbers
if (a < b)
#include <stdio.h>
{ if (a < c)
int main() { smallest = a; }
{ else
int a, b, c, smallest; { smallest = c; }
}
else
printf(“Enter a, b & c\n“);
{ if (b < c)
scanf(“%d %d %d, &a,&b,&c); { smallest = b; }
else
{ smallest = c; }
}
printf(“Smallest is %d“,smallest);
return 0;
}
2/13/2024 CSE 1001 Department of CSE 4

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“);

2/13/2024 CSE 1001 Department of CSE 5


266
The else-if ladder
if (Expression_1 )
{
statement _block1
}
else if (Expression_2)
{
statement _block2
}
…….
else if (Expression_n)
{
statement _blockn
}
else
{
last_statement
}

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.

2/13/2024 CSE 1001 Department of CSE 7


268
else-if ladder Flow of control

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

2/13/2024 CSE 1001 Department of CSE 8


269
Testing for character ranges
#include<stdio.h>
int main()
{
char ch;
printf(“enter a character\n”);
scanf(“%c”,&ch);
if (ch >= 'a' && ch <= 'z')
printf(“lowercase char\n“);
else if (ch >= ‘A' && ch <= ‘Z')
printf(“uppercase char\n“);
else if (ch >= ‘0' && ch <= ‘9')
printf(“digit char\n“);
else
printf(“ special char\n”);
return 0;
}
2/13/2024 CSE 1001 Department of CSE 9
270
WAP using else-if ladder to calculate grade for the
marks entered
int main() {
char cgrade;
int imarks;
printf("enter marks“);
For inputs
scanf(“%d”,&imarks); imarks= 46
if(imarks>79) grade = D
if(imarks>79)
imarks= 64
cgradecgrade
= 'A'; = 'A'; grade = B
else ifelse if (imarks>59)
(imarks>59)
cgradecgrade
= 'B'; = 'B';
else if (imarks>49)
else cgrade
if (imarks>49)
= 'C';
else if (imarks>39) cgrade = 'C';
else cgrade
if (imarks>39)
= 'D';
else cgrade = 'D';
else cgrade = 'F';
cgrade = 'F';
printf(“Grade :%c\n”,cgrade);
2/13/2024 return 0; CSE 1001 Department of CSE 10

} 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…

2/13/2024 CSE 1001 Department of CSE 13


274
Find the roots of Quadratic equation using if-else statement

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; }

if (disc<0) else /*disc > 0 */


{ {
printf("imaginary roots\n“); printf(“Real & distinct roots“);
re= - b / (2*a); printf(“Roots are“);
im = pow(fabs(disc),0.5)/(2*a);
printf(“root1=%.21f+%.21fi and root1=(-b + sqrt(disc))/(2*a);
root2 =%.21f-%.2fi”, re,im,re,im); root2=(-b - sqrt(disc))/(2*a);
} printf(“Root1 = %.21f and root2
=%.21f”,root1,root2);
}
return 0;
}
2/13/2024 CSE 1001 Department of CSE 14
275
Decision Making,
Branching
Switch and Break

276
The switch Statement

➢Switch is multiple–branching statement where based on a


condition, the control is transferred to one of the many possible
points.

➢ Enables the program to execute different statements based on


an expression that can have more than two values. Also called
multiple choice statements.

➢The expression provided in the switch should result in a constant


value otherwise it would not be valid.

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
}

Assume iDepartmentCode is 115


find the output ?

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::

Compiler Error: duplicate case value

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

(1) Order the cases alphabetically or numerically – improves


readability.
(2) Put the normal cases first ; put the exceptional cases later.
(3) Order cases by frequency:-put the most frequently executed
cases first and the least frequently used cases later.
(4) Use default case to detect errors and unexpected cases [user
friendly messages].

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”)

Program looping: enables you to develop concise programs containing


repetitive processes that could otherwise require many lines of code !

2/13/2024 3
299
The need for program looping

Example problem: computing triangular numbers.


(The n-th triangular number is the sum of the integers from 1 through
n)
#include <stdio.h>
int main (void)
{
int triangularNumber;
triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8;
printf(“The eighth triangular number is
%d“,triangularNumber);
return 0;
}

What if we have to compute the 200-th (1000-th, etc) triangular number ?

We have 3 different statements for looping.


2/13/2024 4
300
Iterative (loop) control structures
➢ Three kinds of loop control structures:
✓while
✓do while
✓for

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.

➢ Two types: Based on position of control statement.

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

Statement after loop Print triangularNumber

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

for(n = 1; n <=100; n=n + 1)


{
sum=sum + n;
}
printf(“%d”,sum);
return 0;
}
2/13/2024 12
308
Infinite loops
• It’s the task of the programmer to design correctly the algorithms so
that loops end at some moment !
// Program to count 1+2+3+4+5
#include <stdio.h>
int main()
{ What is wrong here ?
int i, n = 5, sum =0; Does the loop end?
for ( i = 1; i <= n; n = n + 1 )
{
sum = sum + i;
printf(“%d”,sum);
}
return 0;
}

2/13/2024 13
309
Example – for with a body of 2 statements

// Program to generate a table of triangular numbers

#include <stdio.h>
int main()
{
int n, triangularNumber=0;

printf(“TABLE OF TRIANGULAR NUMBERS\n\n“);


printf(“Sum from 1 to n\n“);

for ( n = 1; n <= 10; n++ )


{
triangularNumber += n;
printf(“The %d th triangular number is
%d\n”,n,triangularNumber);
}
return 0;
}

2/13/2024 14
310
for loop variants
• Multiple expressions (comma between…)
for(i=0 , j=10 ; i<j ; i++ , j--)

• Omitting fields (semicolon have to be still…)


i=0;
for( ; i<10 ; i++ )

• Declaring variables
for(int i=0 ; i=10 ; i++ )

2/13/2024 15
311
while-loop
General format:

while (test expression) Note: braces optional if


{ only one statement.
body of the loop
}

✓Entry controlled loop statement.


✓Test condition is evaluated & if it is true, then body of the loop is executed.
✓This is repeated until the test condition becomes false, & control transferred out
of the loop.
✓Body of loop is not executed if the condition is false at the very first attempt.
✓While loop can be nested.

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

#include <stdio.h> #include <stdio.h>


int main() int main()
{
{
int n;
int n; int sum;
int sum; sum=0; //initialize
sum=0; //initialize sum sum
n=1;
while (n < 100)
for(n = 1; n < 100; n=n + 1) {
{ sum= sum + n;
sum=sum + n; n = n + 1;
} }
printf(“%d”,sum);
printf(“%d”,sum);
return 0;
return 0; }
}

2/13/2024 18
314
Program to reverse the digits of a number
#include <stdio.h>
int main()
{
int number, rev=0, right_digit;

printf(“Enter your number.\n“);


scanf(“%d”,&number);

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

• Criteria: Number of repetitions:


• Indefinite loops ->while
• Counting loops -> for

• 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

Week Topics Session Outcome

1 Algorithms and Flow Charts Describe the flowcharts and design of an algorithm

Use Unix commands to manage files and develop


2 Working with Linux Commands
programs,including multi-module programs

3 Formula-based CPrograms Understand the fundamentals of C programming.

Choose the decision-making statements to solve the


4 Control Structures: if statement
problem.

Choose the decision-making statements to solve the


5 Control Structures: Switch
problem.

6 Control Structures: Loops Choose the loop statements to solve theproblem

7 Control Structures: Nested Loops Choose the loop statements to solve the problem

8 1-D Array Implement different Operations on 1-D arrays.

9 2-D Arrays Implement different Operations on 2-D arrays

10 Strings Implementation of different Operations on strings

11 Functions Use functions to solve the given Problem


Understand and apply the concept of pointers in
12 Pointers
programming

Understand and apply the concept of Structure in


13 Structures
programming

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.

Lab 2. Working with Linux Commands

22. clear Clear terminal


23. ps Display the processes in terminal
24. man Access manual for all Linux commands
25. grep Search for a specific string in an output
26. echo Display active processes on the terminal
27. sort sort the file content
28. cal View Calendar in terminal
29. df Check the details of the file system
wc Check the lines, word count, and characters in a
30.
file using different options

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.

Lab 4. Control Structures: If statement


1. Write a program to check whether the given number is odd or even.
2. Write a program to check whether a given year is a leap year or not.
3. Write a program to find the roots of a quadratic equation.
a. Hint: root = -b +/- sqrt(b2-4ac)/2a
4. Write a program to find the total no. of days for a given number of
months countingfrom January month.
a. Example: m=3, days=31+ (28 0r 29) + 31.
5. Write a program to take two numbers as an input and find whether
one number is amultiple of the other or not.
6. Write a program that returns a letter grade based on a quiz score. The
input will be theinteger score from a ten-point quiz.
a. The letter grades are assigned by:
b. 9-10“A”7-8“B”5-6“C”3-4“D”<3“F”
7. Write a program that takes three sides of a triangle input and calculates its
area, if theseconditions are satisfied a+b>c, b+c>a, a+c>b, calculate
area=(a+b+c)/2
8. Write a program to check whether the given character is a vowel, consonant, or digit.

Lab 5. Control Structures: Switch


1. Write a program to program to calculate an area of a circle, a rectangle, or a triangle
depending on the user’s choice.
2. Write a program to remove all the break statements from Ex-1 (with switch-case construct)
and try to execute the program with a few inputs. Observe the difference.
3. Write a program to program to input the number of week’s days (1-7) and translate to its
equivalent name of the day of the week (e.g., 1 to Sunday, 2 to Monday)
4. Write a program to design a calculator that performs addition, subtraction, minus, and
division operation. This program inputs two operands and an operator and then displays the
calculated results.
5. Write a program to calculate a bill for internet browsing. The conditions are given below:

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%)

Lab 6. Control Structures: Loops

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.

Lab 7. Control Structures: Nested Loops


1. Write a program to print different patterns using nestedloops.
1

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.

Lab 8. 1-D Array


1. Write a program to find the largest and smallest element in an array.
2. Write a program to find the sum of odd index numbers in an array.
3. Write a program to print the subarray that lies between the two indexes.
4. Write a program to find the number of positive numbers, negative numbers, oddnumbers,
even numbers, and the number of 0 of an array.
5. Write a program to reverse an array with an auxiliary array.
6. Write a program to check whether an array is sorted or not.
7. Write a program to arrange the elements of an array in ascending order by a simple sorting
method. (Selection sort/bubble sort)
8. Write a program to take an array of 10 elements. Split it into the middle and store theelements
in two different arrays. E.g.- Initial array:

58 24 13 15 63 9 8 81 1 78

325
After splitting:

58 24 13 15 63

9 8 81 1 78

Lab 9. 2-D Arrays


1. Write a program to take 3 student marks in 5 subjects. Print the total marks of eachstudent
and the average marks of each subject.
2. Write a program for searching for an element in the matrix and counting the number of
occurrences of that element.
3. Write a program to multiply two matrices.
4. Write a program to check if the given matrix is a magic square or not.
5. Write a program to find whether a given matrix is symmetric or not.
Hint: A = AT
6. Write a program to find the trace and norm of a given square matrix.
Hint: Trace = sum of principal diagonal elements
Norm = sort (sum of squares of the individual elements of an array)

Lab 10. Strings

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.

Lab 11. Functions


1. Write a program to find the factorial of a number using a function. (Ex: 5! =5*4*3*2*1. Use
a function Fact to evaluate factorial & print the result).
2. Write a program to find the maximum of a given set of numbers using functions. (Use a
function Max and return the result to the main function)
3. Write a program to find the GCD of two numbers recursively. (Ex: GCD of 9, 24 is 3)
4. Write a program to check whether the given number is prime or not. Using this function
generates first n prime numbers using the above function.
5. Write a function to generate the nth Fibonacci term using recursion. Print first N Fibonacci
terms using this function. Hint: (Fibonacci series is 0, 1, 1, 2, 3, 5, 8,)
6. Write a program to check if the given string is a palindrome or not, using the stringhandling
function.
7. Write a function Sort for sorting a list of names which will use a function compare to
compare two names. (Selection /bubble Sort may be used).

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.

Lab 13. Structures

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.

Lab 14. End-term Exam

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.

To declare an array in C, a programmer specifies the type


of the elements and the number of elements required by
an array as follows: type arrayName [arraySize].

The arraySize must be an integer constant greater than


zero and type can be any valid C data type

4/5/2024 CSE 1001 Department of CSE 2


328
Arrays

➢An array is a group of related data items that share


a common name.

➢The array elements are placed in contiguous memory


locations.

➢A particular value in an array is indicated by writing an


integer number called index number or subscript in
square brackets after the array name.

➢The least value that an index can take in array is 0..


4/5/2024 CSE 1001 Department of CSE 3
329
Arrays
Array Declaration:
data-type name [size];

where data-type is a valid data type (like int, float, char...)


✓name is a valid identifier

✓size specifies how many elements the array has to contain.


▪ size field is always enclosed in square brackets [ ] and
takes static values.

▪ For example an array salary containing 5 elements is declared


as follows int salary [5];

4/5/2024 CSE 1001 Department of CSE 4


330
Arrays - One Dimensional

▪ A linear list of fixed number of data items of same type.


▪ These items are accessed using the same name using a single
subscript. E.g. roll[0], roll[1]…. or salary [1], salary [4]
▪ A list of items can be given one variable name using only one
subscript and such a variable is called a single-subscripted variable
or a one- dimensional array.

4/5/2024 CSE 1001 Department of CSE 5


331
Arrays - 1D
Total size:

The Total memory that can be allocated to 1Darray is computed as

Total size =size *(sizeof(data_type));

where size→ number of elements in 1-D array

data_type→ basic data type.

sizeof() → is a unary operator which returns the size of


data type in bytes.

4/5/2024 CSE 1001 Department of CSE 6


332
Arrays - 1D
If the values of array are 3, 2, 6, 1, 9 then these values are
stored in array arr as follows.
int main()
{
int arr[50],n; // declaration of ‘arr’
printf(" enter value of n\n“); // no of elements
scanf(“%d”, &n); // reading the limit into n
for(int i=0;i<n;i++)
{
scanf(“%d”,&arr[i]); // reading n elements
}
for(int i=0; i<n;i++) //displaying n elements
{ printf(“%d”,arr[i]);
printf(“\t”);
}
return 0;
4/5/2024 CSE 1001 Department of CSE 7
} 333
Initializing one-dimensional array
int number[3] ={0,0,0}; or {0} ;
→ declares the variable number as an array of size 3
and will assign 0 to each element.
int age[ ] ={16,25,32,48,52,65};
→ declares the age array to contain 6 elements with
initial values 16, 25, 32, 48, 52, 65 respectively. It is
same as:
int age[6] ={16,25,32,48,52,65};
int number[5] ={4,3,1};

4/5/2024 CSE 1001 Department of CSE 8


334
Initializing one-dimensional array with zeros
Initialize all the elements of an integer array
‘values’ to zero
int values[20];
Begin for loop
Initialize counter
Set limit for counter for ( int i=0; i<20; i++)
Increment counter

Initialize element in array ‘values’


values[i]=0;

4/5/2024 CSE 1001 Department of CSE 9


335
Printing one-dimensional array
For example

int x[3] = {9,11,13};

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};

for (int i = 0; i<3; i++)

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.

int a[10], n, i; Example : a[ ]={1, 2, 3, 4, 5}


Enter values
printf(“Enter values\n“); n=5
12345
for(i=0;i<n;i++) Reverse printing of array
5 4 3 2 1
scanf(“%d”,&a[i]); Array before Array after
a[0]=1 a[0]=1
printf(“\nReverse order printing a[1]=2 a[1]=2
a[2]=3 a[2]=3
of array\n”); a[3]=4 a[3]=4
a[4]=5 a[4]=5
for(i=n-1;i>=0;i--) // reverse loop

printf(“%d\n”,a[i]);

4/5/2024 CSE 1001 Department of CSE 13


339
WAP to delete an element from an array

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}

if (ele<a[i]) break; New array after inserting 3 :


a[ ] = {1, 2, 3, 4, 5,6}
pos = i+1; //position of insertion
for(i=n; i>=pos; i--) //shift the elements to right
a[i]=a[i-1];
a[pos-1] = ele; //ele is inserted at the specified pos.
n = n + 1; // increment the count of no of elements

4/5/2024 CSE 1001 Department of CSE 15


341
WAP to insert an element to an array at a given position
int a[100], n,i, pos,ele;
Example : insert 9 at 2nd position
scanf(“%d”,&n); // number of elements a[ ]={1, 2, 3, 4, 5}
printf("\nEnter the elements of array:“);
for(i=0;i<n;i++) New array after inserting 9 :
a[ ]={1, 9, 2, 3, 4, 5}
scanf(“%d”,&a[i]);
printf("\nEnter the element and position of insertion:”);
scanf(“%d %d”,&ele, &pos);
for(i=n; i>=pos; i--) //shift the elements to right
a[i]=a[i-1];
a[pos-1] = ele;//ele is inserted at the specified pos.
n = n + 1; // increment the count of no of elements
printf("\nThe array after insertion is:“);
for(i=0;i<n; i++)
printf(“%d\n”, a[i]);
4/5/2024 CSE 1001 Department of CSE 16
342
Syntax
1D Array:
▪ Syntax: type array_name[size];

▪ Memory Requirement:
Total size =size *(sizeof(data_type));

▪ Initialization:
type array-name [size]={list of values}

▪ Write and Read:


for(i=0;i<n;i++) for(i=0;i<n;i++)
scanf(“%d”,&a[i]); prinft(“%d\n”,a[i]);

4/5/2024 CSE 1001 Department of CSE 17


343
Write a program to reverse an array using only
one array

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

4/5/2024 CSE 1001 Department of CSE 18


344
Reversing an array
for(i=0, j=n-1; i<n/2; i++, j--) Example :
a[ ]={1, 2, 3, 4, 5}
{
temp=a[i];
a[i]=a[j];
a[j]=temp;

printf("\n Reversed array: \n“); Output:


Enter values for an array
for(i=0;i<n;i++)
n=5
printf(“%d\t”,a[i]); 12345
Reversed array
} 5 4 3 2 1

4/5/2024 CSE 1001 Department of CSE 19


345
Linear Search

• Finding whether a data item is present in a set of


items

→ linear search / sequential search

4/5/2024 CSE 1001 Department of CSE 20


346
Linear search- illustration 1

4/5/2024 CSE 1001 Department of CSE 21


347
Linear search- illustration 2

4/5/2024 CSE 1001 Department of CSE 22


348
Pseudo code for linear search
/*search procedure*/
int found=0; //setting flag
for(i=0; i<n; i++) {
Print "enter no of elements"; if(a[ i ]==key) // comparison
Input n; {
found=1;
for(i=0;i<n;i++){
pos=i+1;
Print “enter number\n"; break;

Input a[i]; // entered data items }}


if(found==1)
}
Print“data_found_in”,pos,
Print “enter the element to be "position";

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

4/5/2024 CSE 1001 Department of CSE 24


350
Bubble Sort- Illustration

4/5/2024 CSE 1001 Department of CSE 25


351
Bubble Sort- Illustration

4/5/2024 CSE 1001 Department of CSE 26


352
Pseudo code for Bubble Sort procedure
for(i=0;i<n;i++)
Example :
Input a[i]; // entered elements a[ ]={16, 12, 11, 67}
for(i=0;i<n-1;i++) //pass
{ for(j=0;j<n-i-1;j++) Array after sorting (ascending)
a[ ]={11, 12, 16, 67}
{ if(a[j]>a[j+1]) // comparison
{ // interchange
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
4/5/2024 CSE 1001 Department of CSE 27
353
C H A R AC T E R A R R AY S
STRINGS

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, consider the following array:


char name [20];
is an array that can store up to 20 elements of type char.
It can be represented as:

4/5/2024 CSE 1001 Department of CSE 30


356
Strings

✓The character sequences "Hello" and "Merry Christmas"


represented in an array name respectively are shown as
follows :

4/5/2024 CSE 1001 Department of CSE 31


357
Initialization of null-terminated character sequences
▪ arrays of characters or strings are ordinary arrays that
follow the same rules of arrays.

For example

To initialize an array of characters with some predetermined


sequence of characters one can initialize like any other array:

char myWord[ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };

4/5/2024 CSE 1001 Department of CSE 32


358
Initialization of null-terminated character sequences
▪ Arrays of char elements have an additional methods to initialize their
values: using string literals
▪ “Manipal ” is a constant string literal.
For example,
char result[14] =“Manipal”;
▪ Double quoted (") strings are literal constants whose type is in fact a
null-terminated array of characters.
So string literals enclosed between double quotes always have a null
character ('\0') automatically appended at the end.

4/5/2024 CSE 1001 Department of CSE 33


359
Initialization
▪ Initialization:

char myWord [ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };

char myWord [ ] = "Hello";

▪ In both cases the array of characters myword is declared with a size of 6


elements of type char:

✓The 5 characters that compose the word "Hello" plus a final null character
('\0') which specifies the end of the

sequence and that,

✓In the second case, when using double quotes (") null character ('\0') is
appended automatically.

4/5/2024 CSE 1001 Department of CSE 34


360
Example
#include <stdio.h>

int main() {

char question[ ] = "Please, enter your first name: ";

char greeting[ ] = "Hello, ";

char yourname [ 80];

printf(“%s”, question);

scanf(“%s”, &yourname);

printf(“%s…. %s\n”, greeting, yourname );

return 0;
Please, enter your first name: gautam
} Hello.…gautam

4/5/2024 CSE 1001 Department of CSE 35


361
Example

#include <stdio.h>
int main()
{

const int MAX = 80; //max characters in string

char str[MAX]; //string variable str

printf("Enter a string: \n");

scanf("%s",&str); //put string in str

printf("%s",str); //display string from str

return 0;
Enter a string:
} gautam kumar
gautam

4/5/2024 CSE 1001 Department of CSE 36


362
Reading Embedded Blanks

To read everything that you enter from the keyboard until the
ENTER key is pressed (including space).
Syntax:
gets(string) ;

CSE 1001 Department of CSE 4/5/2024 37


363
Example
#include <stdio.h>
#include<string.h>

int main()
{

char str[80]; //string variable str

printf(“\nEnter a string: ”);


gets(str); //put string in str or use gets(str)

printf(“ the string is \n“);


puts(str);
Enter a string: Manipal University Jaipur, India
return 0; the string is
Manipal University Jaipur, India
}

4/5/2024 CSE 1001 Department of CSE 38


364
Count the number of characters in a string
#include <stdio.h> gets(sent);
puts(sent);

int main() while(sent[i]!='\0')

{ {

char sent[100]; count++;

int i=0, count=0; i++;


}

printf("enter sentence \n“); printf(“\n The No of characters=%d “, count);


return 0;
}

4/5/2024 CSE 1001 Department of CSE 39


365
Count the number of words in a sentence
#include <stdio.h>
while(sent[i]!='\0')
int main() {
{ if (sent[i]==' '&& sent[i+1]!=' ')
count++;
const int MAX = 100; i++;
char sent[MAX]; }
printf(“n %d n no. of words = " ,count);
int i=0,count=1; return 0;
}

printf("enter sentence \n“);


gets(sent);
printf("\n”);

4/5/2024 CSE 1001 Department of CSE 40


366
Reading multiple lines: Example
#include <stdio.h>
printf("You entered:\n”);
int main()
printf(“%s”,str);
{
return 0;
const int MAX = 2000;
}
//max characters in string

char str[MAX]; //string variable str

printf("\nEnter a string:\n“);

gets(str);
The function will continue to accept characters until enter key is pressed.

4/5/2024 CSE 1001 Department of CSE 41


367
Library functions: String Handling functions (built-in)
• Used to manipulate a given string.
• These functions are part of string.h header file.

▪ 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)

4/5/2024 CSE 1001 Department of CSE 42


368
Library function: strlen()
• String length can be obtained by using the following function
n=strlen(string);

• This function counts and returns the number of characters in


a string, where n is an integer variable which receives the
value of the length of the string.

• The argument may be a string constant.


Eg: printf(“%d”,strlen(“Manipal”)); prints out 7.

4/5/2024 CSE 1001 Department of CSE 43


369
Copies a string using a for loop
#include <stdio.h>
#include<string.h>
int main()
{
char str1[ ] = “Manipal Institute of Technology”;
char str2[80]; //empty string
int n=strlen(str1);
for(int j=0 ; j<n; j++) //copy strlen characters
{str2[j] = str1[j]; } // from str1 to str2
str2[j] = ‘\0’; //insert NULL at end
printf(“%s”,str2); //display str2
return 0;
}

4/5/2024 CSE 1001 Department of CSE 44


370
Extracting a character from a string
#include <stdio.h> D E L H I

#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]); }

4/5/2024 CSE 1001 Department of CSE 45


371
To encrypt and decrypt a string
#include <stdio.h> for(i=0;sent[i]!=‘\0’;i++)
#include<string.h> sent[i]=sent[i]+1;
int main() printf(“ the encrypted string is \n”);
{ puts(sent);
const int MAX = 100;
for(i=0;sent[i]!=‘\0’;i++)
char sent[MAX];
sent[i]=sent[i]-1;
int len,I;
printf(“ the decrypted string is \n”);
printf("enter sentence \n“);
puts(sent);
gets(sent);
}

4/5/2024 CSE 1001 Department of CSE 46


372
Library function: strcpy()
Copying a String the EASY WAY using
strcpy(destination, source)
▪ The strcpy function works almost like a string assignment operator
and assigns the contents of source to destination.

✓destination may be a character array variable or a string constant.

e.g., strcpy(city, ”DELHI”);

will assign the string “DELHI” to the string variable city.

✓Similarly, the statement strcpy(city1, city2);


will assign the contents of the string variable city2 to the string
variable city1.

The size of the array city1 should be large enough to receive the
contents of city2.

4/5/2024 CSE 1001 Department of CSE 47


373
strcpy(): Example
#include <stdio.h>

int main()

char str1[ ] = “Tiger, tiger, burning bright\n”

“In the forests of the night”;

const int MAX = 80; //size of str2 buffer

char str2[MAX]; //empty string

strcpy(str2, str1); //copy str1 to str2

printf(“%s”,str2);//display str2

4/5/2024 CSE 1001 Department of CSE 48


374
Library function: strcmp()

▪ The strcmp function compares two strings identified by the


arguments and has a value 0 if they are equal.
▪ If they are not, it has the numeric difference between the first non
matching characters in the strings.
strcmp(string1, string2);
string1 and string2 may be string variables or string constants.
e.g., strcmp(“their”, ”there”); will return a value of –9 which is the
numeric difference between ASCII “i” and ASCII “r”. That is, “i” minus “r”
with respect to ASCII code is –9.
If the value is negative, string1 is alphabetically above string2.

4/5/2024 CSE 1001 Department of CSE 49


375
Library function: strcat()
The strcat function joins two strings together.

It takes the following form:


strcat(string1, string2);
string1 and string2 are character arrays.
✓When the function strcat is excuted, string2 is
appended to string1.
✓ It does so by removing the null character at the end
of string1 and placing string2 from there.
✓The string at string2 remains unchanged.

4/5/2024 CSE 1001 Department of CSE 50


376
Concatenation of 2 strings
#include <stdio.h>
#include <string.h>
int main()
{ char s1[40], s2[50];
printf("\nEnter the first string“);
gets(s1);
printf("\nEnter the second string“);
gets(s2);
strcat(s1, s2);
printf("\nConcatenated string is“);
printf(“%s”,s1);
return 0; }
4/5/2024 CSE 1001 Department of CSE 51
377
Reversing a string

int main() for(i=0;i<n;i++)


{ {
char str[70]; temp=str[i];
char temp; str[i]=str[n-i-1];
int i, n=0; str[n-i-1]=temp;
printf("\nEnter the string:“); }
gets(str); printf("\nReversed string is:“);
//find the string length puts(str);
n=strlen(str); return 0;
}

4/5/2024 CSE 1001 Department of CSE 52


378
Check whether a string is Palindrome or not
for(i=0;i<n/2;i++)
int main() {
{ if(str[i]!=str[n-i-1])
char str[30];
{ flag=0;
int i, j, n, flag=1;
break; }
printf("\nEnter the string:“);
}
gets(str);
if(flag==1)
//find the string length
printf("\nIts a Palindrome“);
n=strlen(str);
else
printf("\nNot a Palindrome“);
return 0;
}
4/5/2024 CSE 1001 Department of CSE 53
379
Change all lower case letters into uppercase in a
sentence

int main() for(i=0;i<n;i++)


{ {
char string[30]; if(string[i]>=97 && string[i]<=122)
int i,n=0; string[i]=string[i]-32;
printf("\nEnter the string“); }
gets(string);
puts(string);
for(i=0;string[i]!='\0';i++) getch();
n++; return 0;
}
4/5/2024 CSE 1001 Department of CSE 54
380
Strings Bubble Sort

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;
}

4/5/2024 CSE 1001 Department of CSE 55


381
Finding Substring in Main String

Main string: cc aa bb
Sub-String : aa

Enter main string: cc aa bb


Enter sub-string : aa
Substring aa is found at positions 3

56
382
Finding Substring in Main String
int main()
{
char str1[80],str2[80];
int i,j,len=0;

cout<<"Enter the main string :\n";


gets(str1);

cout<<"Enter sub string :\n";


gets(str2);

//finding length of substring


for(i=0;str2[i]!='\0'; i++)
len++;

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];

✓The first example tells that marks is a 2-D array of 5 rows


and 3 columns.
✓The second example tells that matrix is a 2-D array of 3
rows and 3 columns.

✓Similarly, the third example tells that page is a 2-D array of


25 rows and 80 columns.

5/3/2024 CSE 1001 Department of CSE 4


386
An array int mark[5][4] is represented as follows
Student
Tests1 [0] Test 2 [1] Test 3 [2] Test 4 [3]
[subscript]

1 [0] 20 (mark[0][0]) 20 (mark[0][1]) 21 (mark[0][2]) 22 (mark[0][3])

2 [1] 18 (mark[1][0]) 23 (mark[1][1]) 22 (mark[1][2]) 20 (mark[2][3])

3 [2] 11 (mark[2][0]) 22 (mark[2][1]) 15 (mark[2][2]) 16 (mark[2][3])

4 [3] 22 (mark[3][0]) 21 (mark[3][1]) 23 (mark[3][2]) 24 (mark[3][3])

5 [4] 17 (mark[4][0]) 15 (mark[4][1]) 16 (mark[4][2]) 18 (mark[4][3])

5/3/2024 Deparment of CSE 5


387
2 Dimensional Arrays
Initialization of two dimensional arrays
type array-name [row size] [col size ] = {list of values};
int table [2][3]={0,0,0,1,1,1};
→ initializes the elements of the first row to zero and the
second row to 1.
Initialization is always done row by row.
The above statement can be equivalently written as
int table [2][3]={{0,0,0},{1,1,1}};
OR in matrix form it can be written as
int table [2][3]= { {0,0,0},
{1,1,1} };

5/3/2024 CSE 1001 Department of CSE 6


388
2 Dimensional Arrays
When array is completely initialized with all values, need not necessarily specify the
first dimension.

int table [][3]= { {0,0,0},


{1,1,1 }
};
If the values are missing in an initializer, they are set to zero
int table [2][3]= { {1,1},
{2}
};
will initialize the first two elements of the first row to 1, the first element of the
second row to two, and all other elements to zero.

To set all elements to zero


int table [3][3]={{0},{0},{0}};
5/3/2024 CSE 1001 Department of CSE 7
389
Read a matrix and display it
int main()
{ for(i=0;i<m;i++)
int i, j, m, n, a[100][100]; {
for(j=0;j<n;j++)
printf("enter dimension for a:“); {
scanf(“%d %d”,&m,&n); printf(“%d\t”,a[i][j]);
}
cout<<"\n enter elements\n"; printf(“\n”);
for(i=0;i<m;i++) }
{
for(j=0;j<n;j++) return 0;
{ }
scanf(“%d”, &a[i][j]);
}
5/3/2024
} CSE 1001 Department of CSE 8
390
Addition of two Matrices
if (m!=p||n!=q)
#include<stdio.h> {
#include<stdlib.h>
printf("cannot add \n“);
int main()
exit(0); }
{
//Reading the elements
int i, j, m, n, p, q, a[10][10], b[10][10],
printf("enter elements for a \n“);
c[10][10];
for (i=0;i<m;i++)
printf("enter dimension for a \n“);
for(j=0;j<n;j++)
scanf(“%d %d”,&m,&n);
scanf(“%d”,&a[i][j]);
printf("enter dimension for b\n“);
scanf(“%d
5/3/2024
%d”,&p,&q); CSE 1001 Department of CSE 9
391
Matrix Addition
//Display
printf("\n enter elements for b\n)";
printf("\n final matrix is \n“);
for(i=0;i<p;i++)
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
scanf(“%d”, &b[i][j]);
for(j=0;j<n;j++)
//Addition
for(i=0;i<m;i++)
printf(“%d\t”,c[i][j]);
for(j=0;j<n;j++)
printf("\n“);
c[i][j]=a[i][j]+b[i][j];
}

5/3/2024 CSE 1001 Department of CSE 10


392
Check whether a given Matrix is Symmetric or not
printf("enter dimension \n“); for(i=0;i<m;i++){

scanf(“%d %d”,&m,&n); for(j=0;j<n;j++){

if(m!=n) if (a[ i ][ j ]!=a[ j ][ i ]){

{ printf("\n matrix is not

printf("it is not a square \n“); symmetric \n“);

else exit(0); }

{ printf("enter elements \n“); } }

for(i=0;i<m;i++) printf("\n matrix is symmetric“);

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

5/3/2024 CSE 1001 Department of CSE 12


394
Row Sum & Column Sum of a matrix
int a[10][10]; //Row sum
int rowsum[10], colsum[10]; for(i=0;i<m;i++)
printf("enter dimension for a \n“); {
scanf(“%d %d”,&m, &n); rowsum[i]=0;
//Reading for(j=0;j<n;j++)
printf("enter elements for a \n“); rowsum[i]=rowsum[i]+a[i][j];
for (i=0;i<m;i++){ }
for(j=0;j<n;j++) printf("\n“);
scanf(“%d”, &a[i][j]);
}
5/3/2024 CSE 1001 Department of CSE 13
395
Row Sum & Column Sum of a matrix
Display
//Column sum for(i=0;i<m;i++)
for(j=0;j<n;j++) {
{ for(j=0;j<n;j++)
colsum[j]=0; printf("\t %d“,a[i][j]);

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“);

#include <stdlib.h> for (i=0;i<m;i++)

int main(){ int i, j, m, n, p, q; {

int a[10][10], b[10][10],c[10][10]; for(j=0;j<n;j++)

printf("enter dimension for a \n“); scanf(“%d”,&a[i][j]);

scanf(“%d %d”,&m,&n); }

printf("\n enter dimension for b\n“); printf("\n enter elements for b\n“);

scanf(“%d %d”, &p,&q); for(i=0;i<p;i++)

if(n!=p){ { for(j=0;j<q;j++)

printf("not multiplicable \n“); scanf(“%d”,&b[i][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; }

printf(“\nEnter the cols to exchange: “);


scanf(“%d %d”,&c1,&c2);
/*Column exchange : c1  c2 */
for(i=0;i<m;i++) {
temp=arr[i][c1-1];
arr[i][c1-1]=arr[i][c2-1];
arr[i][c2-1]=temp; }
5/3/2024 CSE 1001 Department of CSE 20
402
Trace and Norm of a Matrix
Trace is sum of principal diagonal elements of a square matrix.
Norm is Square Root of sum of squares of elements of a matrix.

int trace=0, sum=0,i,j,norm;


int m=3,n=3; for(i=0;i<m;i++)
printf(“enter elements for a \n“); {
for (i=0;i<m;i++){ for(j=0;j<n;j++)
for(j=0;j<n;j++) sum=sum+a[ i ][ j]*a[ i ][ j ];
}
scanf(“%d”,&a[i][j]);
norm=sqrt(sum);
}
printf(“ trace is %d”, trace );
for(i=0;i<m;i++)
printf(“ norm is %d”, norm );
trace=trace + a[i][i];

5/3/2024 CSE 1001 Department of CSE 21


403
Multi Dimensional Arrays
In memory the array elements are stored linearly.

5/3/2024 Deparment of CSE 22


404
Pointers - Concept
• Consider the following statement

int Quantity =50;

- Compiler will allocate a memory location for Quantity and places the
value in that location. Suppose the address of that location is 5000, then

5/3/2024 CSE 1001 Department of CSE 2


405
Pointer
-A memory location or a variable which stores the address of
another variable in memory

5/3/2024 CSE 1001 Department of CSE 3


406
Declaring and initializing pointers
Syntax:
data_type * pt_name;

This tells the compiler 3 things about the pt_name:

▪ The asterisk(*) tells the variable pt_name is a pointer


variable.
▪ pt_name needs a memory location.
▪ pt_name points to a variable of type data_ type

5/3/2024 CSE 1001 Department of CSE 4


407
Declaring and initializing pointers
Example:
int *p; //declares a variable p as a pointer variable
that points to an integer data type.

float *x; //declares x as a pointer to floating point


variable.

• Once a pointer variable has been declared, it can be made to point to a variable
using an assignment statement :

int quantity = 10;


p = &quantity; // p now contains the address of quantity. This is known as
pointer initialization.

5/3/2024 CSE 1001 Department of CSE 5


408
Accessing the address of a variable
int Quantity=50 ;
• To assign the address 5000 (the
location of quantity) to a variable
p, we can write:

int *p = &Quantity ;
Such variables that hold memory
addresses are called
Pointer Variables.

5/3/2024 CSE 1001 Department of CSE 6


409
Program to illustrate the address of operator
#include <stdio.h>
Output:
int main()
{ 0x29feec
int var1 = 11; 0x29fee8
int var2 = 22; 0x29fee4
int var3 = 33;

//print the addresses of these variables


printf(“%x”,&var1);
printf(“%x”,&var2);
printf(“%x”,&var3);
return 0;
5/3/2024 CSE 1001 Department of CSE 7
} 410
Pointers Concept

The Address-of Operator &

• To find the address occupied by a variable

5/3/2024 CSE 1001 Department of CSE 8


411
Summary till now …
int v; //defines variable v of type int
int* p; //defines p as a pointer to int

p = &v; //assigns address of variable v to pointer p

Now…
v = 3; //assigns 3 to v

5/3/2024 CSE 1001 Department of CSE 9


412
To be taken care …
▪ Before a pointer is initialized, it should not be used.
▪ We must ensure that the pointer variables always point to the corresponding
type of data.
▪ Assigning an absolute address to a pointer variable is prohibited. i.e p=5000
▪ A pointer variable can be initialized in its declaration itself.
Example:
int x, *p=&x; //declares x as an integer
variable and then initializes
p to the address of x.

5/3/2024 CSE 1001 Department of CSE 10


413
To be taken care …
The statement

int *p = & x, x; not valid.

i.e target variable ‘x’ must be declared first.

5/3/2024 CSE 1001 Department of CSE 11


414
Accessing variable through a pointer

• A variable’s value can be accessed by its pointer using


unary operator *(asterisk) known as indirection
operator.

Consider the following statements:


int quantity, *p, n; // 2 int variables & 1 integer pointer
quantity =50; // assigns value 50 to quantity
p=&quantity; // assigns the address of quantity to p
n=*p; // contains the indirection operator *

* Operator - value at address operator


5/3/2024 CSE 1001 Department of CSE 12
415
Example – Accessing variable through a pointer
#include <stdio.h>
Output :
int main() 11
{ 22
int var1 = 11; //two integer variables
int var2 = 22;
int *ptr; //pointer to integer

ptr = &var1; //pointer points to var1


printf(“%d”,*ptr); //print contents of pointer (11)

ptr = &var2; //pointer points to var2


printf(“%d”,*ptr); //print contents of pointer (22)

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;
}

5/3/2024 CSE 1001 Department of CSE 14


417
Reference and dereference
operators
▪ & is the ‘reference’ operator and can be read as
"address of"

▪ * is the ‘dereference’ operator and can be read as


“value at address” or "value pointed by"

5/3/2024 CSE 1001 Department of CSE 15


418
Example- understanding pointers
#include <stdio.h>
int main()

{
Output :
firstvalue is 10
int firstvalue = 5, secondvalue = 15;

int * p1, * p2;

p1 = &firstvalue; // p1 = address of firstvalue secondvalue is 20


p2 = &secondvalue; // p2 = address of secondvalue

*p1 = 10; // value pointed by p1 = 10

*p2 = *p1; // value pointed by p2 = value pointed by p1

p1 = p2; // p1 = p2 (value of pointer is copied)

*p1 = 20; // value pointed by p1 = 20

printf(“%dfirstvalue is\n ",firstvalue);

printf( “%dsecondvalue is “,secondvalue);

return 0;

5/3/2024 CSE 1001 Department of CSE 16


419
Pointer expressions
• Pointers can be used in most valid C expressions.
However, some special rules apply.

• You may need to surround some parts of a pointer


expression with parentheses in order to ensure that the
outcome is what you desire.

• As with any variable, a pointer may be used on the right


side of an assignment operator to assign its value to
another pointer.

5/3/2024 CSE 1001 Department of CSE 17


420
Pointer Expressions - Example
• Eg: int a=10, b=20,c,d=10;
int *p1 = &a, *p2 = &b;
Expression a b c
c= *p1**p2; OR *p1 * *p2 10 20 200
OR (*p1) * (*p2)
c= c + *p1; 10 20 210

c=5 * - *p2 / *p1; 10 20 -10


OR ( 5 * (- (*p2)))/(*p1)
//space between / and * is required
*p2 =*p2 +10; 10 30

5/3/2024 CSE 1001 Department of CSE 18


421
Operations on Pointer Variables
• Assignment – the value of one pointer variable can be
assigned to another pointer variable of the same type
• Relational operations - two pointer variables of the
same type can be compared for equality, and so on
• Some limited arithmetic operations
• integer values can be added to and subtracted from a pointer
variable
• value of one pointer variable can be subtracted from another
pointer variable
• Shorthand Increment and Decrement Operators

5/3/2024 CSE 1001 Department of CSE 19


422
Allowed Pointer Operations - Example Assume an
• int a = 10, b = 20, *p1, *p2, *p3, *p4; integer
occupies 4
• p1 = &a; //assume address of a = 2004 bytes

• p2 = &b; //assume address of b = 1008


Pointer Operations Example expression Result
Addition of integers p3 = p1 + 2 value of p3 = 2004 + 4*2 =
from pointers 2012
Subtraction of integers p4 = p2 – 2 value of p4 = 1008-4*2 =
from pointers 1000
Subtraction of one c = p3– p1 Value of c = 2012– 2004= 2
pointer from another
Pointer Increment p1++ Value of p1 = 2008
Pointer Decrement --p1 Value of p1 = 2004

5/3/2024 CSE 1001 Department of CSE 20


423
Allowed Pointer Operations -
Example
if (p1<p2)
printf(“p1 points to lower memory than p2”);

if (p1==p2)
printf(“p1 and p2 points to same location”);

if (p1!=p2)
printf(“p1 and p2 NOT pointing to same location”);

5/3/2024 CSE 1001 Department of CSE 21


424
Invalid Operations:
▪ Pointers are not used in division and
multiplication.
p1/p2;
p1*p2;
p1/3; are not allowed.

▪ Two pointers can not be added.


p1 + p2 is illegal.

5/3/2024 CSE 1001 Department of CSE 22


425
Program to exchange two values
#include<stdio.h>
int main()
{

int x, y, t, *a, *b;


a=&x; b=&y;
printf("Enter the values of a and b: \n");
scanf("%d %d", a, b); // equivalent to scanf(“%d %d”, &x, &y);
t=*a;
*a=*b;
*b=t;
Enter the values of a and b:
printf("x = %d \n", x);
printf("y = %d", y);
10 5
x= 5
return 0; y = 10
}

5/3/2024 CSE 1001 Department of CSE 23


426
BASIC OPERATIONS ON
Pointers AND
POINTERS TO ARRAYS
5/3/2024 CSE 1001 Department of CSE 24
427
Pointers and arrays
▪ When an array is declared, the compiler allocates a
base address and sufficient amount of storage to
contain all the elements of the array in contiguous
memory locations.

▪ The base address is the location of the first element


(index 0) of the array.

▪ The compiler also defines the array name as a


constant pointer to the first element.

5/3/2024 CSE 1001 Department of CSE 25


428
Pointers and arrays
▪ An array x is declared as follows and assume the
base address of x is 1000.
int x[5] ={ 1,2,3,4,5};
▪ Array name x, is a constant pointer, pointing to
the first element x[0] .
▪ Value of x is 1000 (Base Address), the location of
x[0]. i.e. x = &x[0] = 1000 (in the example
below)

5/3/2024 CSE 1001 Department of CSE 26


429
Array accessing using Pointers
• An integer pointer variable p, can be made to point to an
array as follows:
int x[5] ={ 1,2,3,4,5};
int *p;
p = x; OR p = &x[0];

▪ Following statement is Invalid:


p = &x ; //Invalid
• Successive array elements can be accessed by writing:
printf(“%d”, *p); p++;
or
printf(“%d”, *(p+i)); i++;

5/3/2024 CSE 1001 Department of CSE 27


430
Pointers and arrays
• The relationship between p and x is shown below:

p= &x[0]; (=1000) BASE ADDRESS


p+1=>&x[1] (=1004)
p+2=>&x[2] (=1008)
p+3=>&x[3] (=1012)
p+4=>&x[4] (=1016)

• Address of an element of x is given by:


Address of x[i] = base address + i * scale factor of (int)
Address of x[3]= 1000 +(3*4) = 1012

5/3/2024 CSE 1001 Department of CSE 28


431
Array accessing using array name
as pointer
#include <stdio.h>
- Example
int main()
{

int arr[5] = { 31, 54, 77, 52, 93 };


Int j;

for( j=0; j<5; j++) //for each element,


printf(“%d ”, *(arr+j)); //print value

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.

5/3/2024 CSE 1001 Department of CSE 30


433
Sum of all elements stored in an array
#include <stdio.h>
int main()
{
int *p, sum=0, i=0;
int x[5] ={5, 9, 6,3,7};
p=x;
while(i<5)
{
sum+=*p;
i++;
p++;
}
printf("sum of elements = %d“, sum);
return 0;
5/3/2024 CSE 1001 Department of CSE 31
} 434
Pointers & Character strings
//length of the string
#include <stdio.h>
int main()
{
char name[15];
char *cptr=name;
printf("Enter some word to find its length: \n“);
scanf(“%s”, name);
while(*cptr!= '\0')
cptr++;
printf("length= %d"cptr-name);
return 0;
}
5/3/2024 CSE 1001 Department of CSE 32
435
Pointers & Character strings
▪ The statements
char name[10];
char *cptr =name;
declares cptr as a pointer to a character array and
assigns address of the first character of name as the
initial value.
▪ The statement while(*cptr!=‘\0’)
is true until the end of the string is reached.
▪ When the while loop is terminated, the pointer cptr
holds the address of the null character [‘\0’].
▪ The statement length = cptr – name; gives the
length of the string name.

5/3/2024 CSE 1001 Department of CSE 33


436
Pointers & Character strings
• A constant character string always represents a
pointer to that string.
• The following statements are valid.
char *name;
name =“Delhi”;
These statements will declare name as a pointer
to character array and assign to name the
constant character string “Delhi”.

5/3/2024 CSE 1001 Department of CSE 34


437
Pointers and 2D arrays
int a[][2]={ {12, 22},
{33, 44} };
int (*p)[2];
p=a; // initialization

Element in 2d represented as

*(*(a+i)+j)
or
*(*(p+i)+j)

5/3/2024 CSE 1001 Department of CSE 35


438
Pointers and 2D arrays
// 2D array accessed with pointer
#include <stdio.h>
int main()
{
int i, j, (*p)[2], a[][2] = {{12, 22}, {33, 44} };
p=a;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“%d \t“, *(*(p+i)+j));
printf("\n“);
}
return 0;
}
5/3/2024 CSE 1001 Department of CSE 36
439
Array of pointers
▪ We can use pointers to handle a table of strings.
char name[3][25];
name is a table containing 3 names, each with a
maximum length of 25 characters (including ‘\0’)

▪ Total storage requirement for name is 75 bytes.


But rarely all the individual strings will be equal in
lengths.

▪ We can use a pointer to a string of varying length as


char *name[3] = { “New Zealand”, “Austrailia”, “India” };

5/3/2024 CSE 1001 Department of CSE 37


440
Array of pointers
So, char *name[3] = { “New Zealand “,
“Australia”,
“India”};
Declares name to be an array of 3 pointers to
characters, each pointer pointing to a particular
name.
name[0] → New Zealand
name[1]→ Australia
name[2]→ India
This declaration allocates 28 bytes.
5/3/2024 CSE 1001 Department of CSE 38
441
Array of pointers
The following statement would print out all the 3
names.
for(i=0; i<=2;i++)
printf(“%s”,name[i]);
or printf(“%s”, *(name + i));

To access the jth character in the ith name, we


may write as
*(name[i] +j)

The character array with rows of varying lengths are


called ragged arrays and are better handled by
pointers.
5/3/2024 CSE 1001 Department of CSE 39
442
Pointer to Void Type
• The void pointer in C is a pointer which is not associated with
any data types.
• It points to some data location in the storage means points to
the address of variables. It is also called general purpose
pointer.
#include<stdlib.h>
int main() {
int a = 7;
float b = 7.6;
void *p;
p = &a;
printf("Integer variable is = %d", *( (int*) p) );
p = &b;
printf("\nFloat variable is = %f", *( (float*) p) );
return 0;
}

5/3/2024 CSE 1001 Department of CSE 40


443
Pointer to Void Type
#include<stdlib.h>
int main() {
int a = 7;
float b = 7.6;
void *p;
p = &a;
printf("Integer variable is = %d", *( (int*) p) );
p = &b;
printf("\nFloat variable is = %f", *( (float*) p) );
return 0;
}

OUTPUT:
Integer variable is = 7
Float variable is = 7.600000

5/3/2024 CSE 1001 Department of CSE 41


444
Functions-Overview:
Parameters/Arguments
Formal parameters
void dispNum( int n ) // function definition
{
printf(“ The entered num=%d”, n);
}
int main(){ //calling program
int no;
printf(“Enter a number \n“);
scanf(“%d”,&no); Actual parameters
dispNum( no); //Function reference
return 0;
} CSE 1001
445
Department of CSE 2
Functions- Parameter Passing

▪ Pass by value (call by value)

▪ Pass by reference (call by reference)

CSE 1001 Department of CSE 3


446
Pass by value:
void swap(int x, int y )
{
int t=x;
x=y;
y=t;
printf(“In fn: x= %d and y=%d “,x,y);
}
Output:
int main() In fn: x = 7 & y = 5
{ After swap: a = 5 & b = 7
int a=5,b=7;
swap(a, b);
printf(“After swap: a= %d and b= %d“,a,b);
return 0;
CSE 1001 Department of CSE 4
} 447
Pass by Reference – Using Pointers:
void swap(int *x, int *y )
{ Change is directly on the variable
int t=*x; using the reference to the address.
*x=*y;
*y=t; When function is called:
address of a → x
}
address of b → y
Output:
int main()
After swap: a = 7 and b = 5
{
int a=5,b=7;
swap(&a, &b);
printf(“After swap: a=%d and b= %d”,a,b);
return 0; } CSE 1001 Department of CSE 5
448
Pointers as functions arguments:
When we pass addresses to a function, the parameters receiving
the addresses should be pointers.
int change (int *p) #include <stdio.h>
{ int main()
*p = *p + 10 ; {
return 0; int x = 20;
} change(&x); Output :
X after change=30
printf(“x after
change==%d“,x);
return 0;
}
CSE 1001 Department of CSE 6
449
Pointers as function arguments
• When the function change() is called, the address of the
variable x, not its value, is passed into the function
change().

• Inside change(), the variable p is declared as a pointer


and therefore p is the address of the variable x. The
statement

• *p=*p +10 adds 10 to the value stored at the address p.


Since p represents the address of x, the value of x is
changed from 20 to 30. therefore it prints 30.

CSE 1001 Department of CSE 7


450
Function that return multiple values-Using pointers

Using pass by reference we can write a function that


return multiple values.

void fnOpr(int a, int b, int *sum, int *diff) {


*sum = a + b;
*diff = a -b; }
int main() { Output:
int x, y, s, d; x= 5 & y= 3
printf(“Enter two numbers: \n“); Sum =8 & Diff = 2
scanf(“%d %d”,&x, &y);
fnOpr(x, y, &s, &d);
printf(“Sum = %d & Diff =%d “, s, d);
return 0; }
CSE 1001 Department of CSE 8
451
Nesting of functions:
• C language allows nesting of functions by calling one function
inside another function.
• Nesting of function does not mean that we can define an entire
function inside another function. The following examples shows
both valid and invalid function nesting in C language

// Wrong way of function nesting // Right way of function nesting

void fun() void sleep()


{ {
printf(“I am having Fun….”); printf(“I am having sleep”);
}
void sleep()
{ void fun()
printf(“I am having sleep”); {
} printf(“I am having Fun….”);
} sleep();
}
CSE 1001 Department of CSE 9
452
Nesting of Functions:
void First (void){ // FUNCTION DEFINITION
printf(“I am now inside function First\n”);
}
void Second (void){ // FUNCTION DEFINITION
printf( “I am now inside function Second\n”);
First(); // FUNCTION CALL
printf(“Back to Second\n”);
}
int main (){
printf( “I am starting in function main\n”);
First (); // FUNCTION CALL
printf( “Back to main function \n”);
Second (); // FUNCTION CALL
printf( “Back to main function \n”);
return 0;
5/3/2024 CSE 1001 Department of CSE
} 453 10
Nesting of Functions:
void fnOpr(int a, int b, int *sum, int *diff)
{
*sum = a + b; int fnDiff(int p, int q){
if (fnDiff(a,b)) if (p>q)
*diff = a -b; return(1);
else else
*diff = b - a; return (0);}
}
int main() {
int x, y, s, d; Output:
printf(“Enter the values: \n“); x= 3 & y= 5
scanf(“%d %d”, &x, &y); s =8 & d = 2
fnOpr(x, y, &s, &d);
printf(“The results are, Sum =%d and Diff = %d“, s, d);
return 0; }
CSE 1001 Department of CSE 11
454
Passing 1D-Array to Function
Rules to pass an array to a function
▪ The function must be called by passing only the name of
the array.

▪ In the function definition, the formal parameter must be


an array type; the size of the array does not need to be
specified.

▪ The function prototype must show that argument is an


array. CSE 1001
455
Department of CSE 12
Passing 1D-Array to Function:
int fnSum( int a[ ], int n) {
int sum=0,i;
for(i=0;i<n;i++)
sum+=a[i];
return (sum); } Output: n=5
1, 2, 3, 4, 5
int main() { Sum of elements = 15
int n, a[20], x, y,i;
printf(“Enter the limit \n“); Array name is passed along
scanf(“%d”,&n); with number of elements
printf(“Enter the values: \n“);
for (i=0; i<n; i++)
scanf(“%d”,&a[i]);
printf(“The sum of array elements is =%d “,fnSum(a, n));//fn call
return 0; }
CSE 1001 Department of CSE 13
456
Passing 2D-Array to Function:

Rules to pass a 2D- array to a function


▪ The function must be called by passing only the array
name.
▪ In the function definition, we must indicate that the
array has two-dimensions by including two set of
brackets.

▪ The size of the second dimension must be specified.

▪ The prototype declaration should be similar to function


header.

CSE 1001 Department of CSE 14


457
Passing 2D-Array to Function:
int fn2d(int x[ ][10], int m, int n)
{
int i, j, sum=0; Output: m=2 n=3
for(i=0; i<m; i++) 1 2
for(j=0; j<n; j++) 3 4
sum+=x[i][j]; 5 6
return(sum); Sum of elements = 21
}
int main() {
int i, j, a[10][10], m, n;
printf("Enter dimentions of matrix");
scanf("%d%d", &m, &n);
printf("Enter the elements");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf ("Sum of elements of 2D array is=%d",fn2d(a, m, n));
return 0;
}
CSE 1001 Department of CSE 15
458
Write a c program to add all the even elements of
an array using a function Add()

#include <stdio.h> int main()


int Add( int a[ ], int n) {
{ int n, a[20], x, y,i;
int sum=0,i; printf("Enter the limit \n");
for(i=0;i<n;i++) scanf("%d",&n);
{ printf("Enter the values: \n");
if((a[i]%2) == 0) for (i=0; i<n; i++)
sum+=a[i]; scanf("%d",&a[i]);
} printf("The sum of even array
return (sum); elements is =%d
} ",Add(a,n));
Return 0;
}

CSE 1001 Department of CSE 16


459
Write a C program to replace all odd numbers of an array
with the largest number in the array using a function
Replace()
#include <stdio.h>
void Replace( int arr[ ], int main()
int n) {
{ int n, a[20], x, y,i;
// To find the largest printf("Enter the limit \n");
int i, max = arr[0]; scanf("%d",&n);
for (i = 1; i < n; i++) printf("Enter the values: \n");
if (arr[i] > max) for (i=0; i<n; i++)
max = arr[i]; scanf("%d",&a[i]);
Replace(a,n);
// To replace printf("The array after replacement is\n");
for(i=0;i<n;i++) for (i=0; i<n; i++)
{ printf("%d \n",a[i]);
if(arr[i]%2 != 0)
arr[i]=max; return 0;
} }
}
CSE 1001 Department of CSE 17
460
Write a C program to replace all the zeros in the
matrix by the trace of the matrix using a function
Trace()
int main() {
#include <stdio.h> int i, j, m, n;
#include <math.h>
float a[10][10];
void Trace(float a[ ][10], int m, int n)
printf("Enter dimentions of matrix");
{ scanf("%d %d", &m, &n);
int i, j, norm, sum=0; printf("Enter the elements");
for(i=0;i<m;i++)
// Finding Trace for(j=0;j<n;j++)
for(i=0;i<m;i++) scanf("%f",&a[i][j]);
{ Trace(a, m, n);
for(j=0;j<n;j++) printf("Matrix after replacement \n");
sum=sum+a[ i ][ j]*a[ i ][ j ]; for(i=0;i<m;i++)
} {
norm=sqrt(sum); for(j=0;j<n;j++)
//Replacing zeros {
for(i=0;i<m;i++) printf("%f",a[i][j]);
for(j=0;j<n;j++) }
if(a[i][j]==0) printf("\n");
a[i][j]=sum; }
return 0;
} CSE 1001 Department of CSE 18
461 }
Write a C program using pass-by-pointer method to
compute the simple interest and compound interest using a
function SI_CI()
#include <stdio.h>
#include <math.h>
int main() {
float p,q,r,SI,CI;
int n;
printf("Enter the value of Principal p = ");
scanf("%f",&p);
printf("Enter the value of Rate r = ");
scanf("%f",&r);
printf("Enter the value of Period in year n = ");
scanf("%d",&n);

SI_CI(&p,&r,&n,&SI,&CI);

printf("Simple Interest SI=%f \n",SI);


printf("Compound Interest CI=%f \n",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);
}

CSE 1001 Department of CSE 20


463
What is Recursion ?
• Sometimes, the best way to solve a problem is by solving a smaller
version of the exact same problem first.

• Recursion is a technique that solves a problem by solving a smaller


problem of the same type.

• A recursive function is a function that invokes / calls itself directly or


indirectly.

• In general, code written recursively is shorter and a bit more elegant,


once you know how to read it.

• It enables you to develop a natural, straightforward, simple solution


to a problem that would otherwise be difficult to solve.

5/3/2024 CSE 1001 Department of CSE 22


464
What is Recursion ?
▪ Mathematical problems that are recursive in nature like factorial,
fibonacci, exponentiation, GCD, Tower of Hanoi, etc. can be easily
implemented using recursion.

▪ Every time when we make a call to a function, a stack frame is


allocated for that function call where all the local variables in the
functions are stored. As recursion makes a function to call itself many
times till the base condition is met, many stack frames are allocated
and it consumes too much main memory and also makes the
program run slower.

▪ We must use recursion only when it is easy and necessary to use,


because it take more space and time compared to iterative approach.

5/3/2024 CSE 1001 Department of CSE 23


465
Let us consider the code …
int main() {
int i, n, sum=0;
printf("Enter the limit“);
scanf(“%d”,n);
printf("The sum is %d“,fnSum(n));
return 0;
}
int fnSum(int n){
int sum=0;
for(i=1;i<=n;i++)
sum=sum+i;
return (sum);
466 }
5/3/2024 CSE 1001 Department of CSE 24
Recursive Thinking …..
Recursion Process

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.

5/3/2024 CSE 1001 Department of CSE 25


467
Steps to Design a Recursive Algorithm
▪ Base case:
▪ It prevents the recursive algorithm from running forever.

▪ 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.

5/3/2024 CSE 1001 Department of CSE 26


468
Let us consider same code again …
int main() {
int i, n, sum=0; int fnSum(int x) {
printf("Enter the limit“); if (x == 1) //base case
scanf(“%d”, n);
return 1;
printf(“The sum is %d“,fnSum(n));
return 0; else
} return x + fnSum(x-1) ;
//recursive
int fnSum(int n){ case
int sum=0; }
for(i=1;i<=n;i++)
sum=sum+i;
return (sum);
}
5/3/2024 CSE 1001 Department of CSE 27
469
Factorial of a natural number–
a classical recursive example

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;
}

5/3/2024 CSE 1001 Department of CSE 29


471
Recursion - How is it doing!
rFact(5) 120

x =24 = 120
5 rFact(4)

Notice that the recursion


isn’t finished at the bottom -- x
4 rFact(3) =6 = 24
It must unwind all the way
back to the top in order to be
done. x = 6
3 rFact(2) =2

factorial(0) = 1
factorial(n) = n * factorial(n-1) [for n>0] 2
x
rFact(1) =1 = 2

long rFact (long a) {


if (a ==0)
return (1); x
return (a * rFact (a-1)); 1 rFact(0) =1 =1
}
CSE 1001 Department of CSE 5/3/2024 30

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

5/3/2024 CSE 1001 Department of CSE 31


473
Fibonacci Numbers: Recursion
Fibonacci series is 0,1, 1, 2, 3, 5, 8 …
int rfibo(int n)
{
if (n <= 1)
return n;
else
return (rfibo(n-1) + rfibo(n-2));
}
Output:
n=4
fib = 3

5/3/2024 CSE 1001 Department of CSE 32


474
Fibonacci Series using Recursion
int rfibo(int);

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

int gcd(int x, int y)


{ gcd(24,9)  Control In gcd fn on call
if (x == 0) gcd(9,24%9) gcd(9, 6)
return (y); gcd(6,9%6) gcd(6, 3)
if (y==0) gcd(3,6%3) gcd(3, 0)
return (x); return values return 3
return gcd(y, x % y); return 3
} return 3
return 3
Output:
x= 24 , y = 9
gcd = 3
5/3/2024 CSE 1001 Department of CSE 35
477
Recursion - Should I or Shouldn’t I?

• 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

5/3/2024 CSE 1001 Department of CSE 36


478
Recursion vs Iteration

RECURSION ITERATION

Uses more storage space Less storage space


requirement requirement
Less Overhead during
Overhead during runtime
runtime

Runs slower Runs faster

A better choice, a more


Less elegant solution for
elegant solution for
recursive problems
recursive problems

5/3/2024 CSE 1001 Department of CSE 37


479
Recursion – Do’s
• You must include a termination condition or Base
Condition in recursive function; Otherwise your
recursive function will run “forever” or infinite.

• Each successive call to the recursive function must be


nearer to the base condition.

5/3/2024 CSE 1001 Department of CSE 38


480
Extra Problem- Finding product of two numbers
#include <stdio.h> int product(int a, int b)
{
int product(int, int); if (a < b)
int main() {
return product(b, a);
{ }
int a, b, result; else if (b != 0)
{
printf("Enter two numbers to find their product: ");
return (a + product(a, b - 1));
scanf("%d%d", &a, &b); }
else
result = product(a, b);
{
printf("%d * %d = %d\n", a, b, result); return 0;
return 0; }
}
}
Output:
Enter two numbers to find their product: 10 20
10*20=200

5/3/2024 CSE 1001 Department of CSE 39


481
Extra Problem- Dividing two numbers
#include <stdio.h> int divide(int a, int b)
int divide(int a, int b); {
if(a - b <= 0)
{
int main() return 1;
}
{
else
int a,b; {
return divide(a - b, b) + 1;
}
printf("Enter two numbers for division"); }
scanf("%d%d", &a,&b);
printf("%d/%d=%d",a,b,divide(a,b));
return 0;
}
Output:
Enter two numbers for division: 20 10
20/10=2

5/3/2024 CSE 1001 Department of CSE 40


482
Extra Problem- Calculating power of a number
#include <stdio.h> int power(int base, int powerRaised)
int power(int n1, int n2); {
if (powerRaised != 0)
return (base*power(base, powerRaised-1));
int main()
else
{ return 1;
int base, powerRaised, result; }

printf("Enter base number: ");


scanf("%d",&base);

printf("Enter power number);


scanf("%d",&powerRaised);
Output:
result = power(base, powerRaised); Enter base number:3
Enter power number: 4
printf("%d^%d = %d", base, powerRaised, result); 3^4=81
return 0;
}
5/3/2024 CSE 1001 Department of CSE 41
483
Extra Problem- Sum of natural numbers
#include <stdio.h> int sum(int num)
int sum(int n); {
if (num!=0)
int main() return num + sum(num-1);
{ else
int number, result; return num;
}
printf("Enter a positive integer: ");
scanf("%d", &number);

result = sum(number);
Output:
Enter a positive integer: 10
printf("sum=%d", result); Sum= 55
}

5/3/2024 CSE 1001 Department of CSE 42


484
Extra Problem- To count number of digits
#include <stdio.h>
int countDigits(int); int countDigits(int num)
{
int main()
static int count=0;
{
int number;
if(num>0)
int count=0;
{
count++;
printf("Enter a positive integer number: "); countDigits(num/10);
scanf("%d",&number); }
else
count=countDigits(number); {
return count;
printf(“Number of digits is: %d\n",count); }
}
return 0; Output:
} Enter a positive integer number: 123
Number of digits is: 3
5/3/2024 CSE 1001 Department of CSE 43
485
Extra Problem- To find sum of all digits
#include <stdio.h>
int sumDigits(int num)
int sumDigits(int num);
{
int main() static int sum=0;
{ if(num>0)
int number,sum; {
sum+=(num%10);
printf("Enter a positive integer number: sumDigits(num/10);
"); }
scanf("%d",&number); else
{
sum=sumDigits(number); return sum;
}
printf("Sum of all digits are: %d\n",sum); }

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 rev(int num){


int rev(int); static int n = 0;
int main() { if(num > 0)
int num; n = (n* 10) + (num%10) ;
printf(“enter number)”;
else
scanf(“%d”,num);
printf(“%d”, rev(num)); return n;
return 0; return rev(num/10);
} } Output:
num = 234
rev = 432

5/3/2024 CSE 1001 Department of CSE 45


487
Extra Problem- To find length of a string

#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)

For eg: list [ ] = {33,-2,0,2,4} n=5

5/3/2024 CSE 1001 Department of CSE 49


491
Extra problem-Sorting

list[] function calls


{33,-2,0,2,4} sort(list,5) Main()

{-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)

Base case reached .... Return

5/3/2024 CSE 1001 Department of CSE 50


492
Extra problem - Sorting
sortR(list, n);// call of fn & display of sorted array in main()
int sortR(int list[], int ln){ /* move smallest element to 0-th
element */
int i, tmp, min;
tmp = list[0];
if (ln == 1)
list[0] = list[min];
return 0;
list[min] = tmp;
/* find index of smallest no */
/* recursive call */
min = 0;
return sortR(&list[1], ln-1);
for(i = 1; i < ln; i++)
}
if (list[i] < list[min])
Output:
min = i; Orign. array-: 33 -2 0 2 4
Sorted array -: -2 0 2 4 33

5/3/2024 CSE 1001 Department of CSE 51


493
Introduction
▪ C provides facility to define one’s own type
(user-defined) that may be a composite of basic
types (int, char, double, etc) and other user-
defined types.

✓Structures

CSE 1001 Department of CSE 5/3/2024 3


494
Introduction
▪ Definition:
▪ collection of one or more variables, possibly of
different types, grouped together under a single
name for convenient handling

• A structure type in C is called struct.

CSE 1001 Department of CSE 5/3/2024 4


495
Structures
• Structures hold data that belong together.
• Examples:
❑Student record: student id, name, branch, gender, start
year, …
❑Bank account: account number, name, address, balance,

❑Address book: name, address, telephone number, …
• In database applications, structures are called records.

CSE 1001 Department of CSE 5/3/2024 5


496
Structure versus Array
• A struct is heterogeneous, that means it can be
composed of data of different types.

• In contrast, array is homogeneous since it can


contain only data of the same type.

CSE 1001 Department of CSE 5/3/2024 6


497
Structure Definition - Syntax
The general format of a structure definition

struct structure_name
{
data_type member1;
data_type member2;

};

CSE 1001 Department of CSE 5/3/2024 7


498
Structure Definition - Examples
• Example:

struct Date
{
Members of the
int day; structure Date
int month;
int year;
};

CSE 1001 Department of CSE 5/3/2024 8


499
struct examples
• Examples:
i) struct StudentInfo{
int Id; The “StudentInfo”
int age; structure has 4 members
char Gender;
of different types.
double CGA;
};
ii) struct Employee{
char Name[15];
char Address[30]; The “Employee”
int Age; structure has 6
float Basic;
members
float DA;
float NetSalary;
};
5/3/2024 CSE 1001 Department of CSE 9
500
Important Points Regarding
Structures

• Definition of Structure reserves no space.

• It is nothing but the “ Template / Map / Shape


” of the structure .

• Memory is created, very first time when a


variable of structure type is created /
Instance is created.

CSE 1001 Department of CSE 5/3/2024 10


501
Declaring Structure Variables
• Declaration of a variable of struct type using struct tag name, after
structure definition:
<struct-type> <identifier_list>;
• Example:
StudentInfo Student1, Student2;

Name Name
Student1 Id Gender Id Gender Student2
Dept Dept

Student1 and Student2 are variables of StudentInfo type.


5/3/2024 CSE 1001 Department of CSE 11
502
Declaring Structure Variables
Declare them at the time of structure definition:

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.

CSE 1001 Department of CSE 5/3/2024 12


503
Member or dot operator

▪ The link between member and a structure


variable is established using the member
operator ‘.’ which is also known as ‘dot
operator’
<struct-variable>.<member_name>

e.g.: student s1; // s1 is a variable of type


//student structure.
s1. rollno;
s1. age;
s1. name;

CSE 1001 Department of CSE 5/3/2024 13


504
Ex: Member accessing using dot
operator
• Example:
StudentRecord Student1; //Student1 is a variable of type
//StudentRecord
Student1
strcpy(Student1.Name, "Chan Tai Man");
Student1.Id = 12345;
Name
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M'; Id Gender
printf("The student is “);
switch (Student1.gender){ Dept
case 'F': cout << "Ms. "; break;
case 'M': cout << "Mr. "; break; Chan Tai Man
}
printf(“%s \n”, Student1.Name); 12345 M

COMP

5/3/2024 CSE 1001 Department of CSE 14


505
Assigning values to members
Different ways to assign values to the members of a structure:

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;

Reading the values into members:


scanf(“%s %d %d %f”, s1.name, &s1.age, &s1.rollno,
&s1.height);
CSE 1001 Department of CSE 5/3/2024 15
506
Structure Initialization Methods

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}; …
} …
}

CSE 1001 Department of CSE 5/3/2024 16


507
Structure: Example
struct Book { // definition
char title[20];
char author[15];
int pages;
float price;
};
int main( ){
struct Book b1;
printf(“Input values”);
scanf(“%s %s %d %f”, b1.title, b1.author, &b1.pages,
&b1.price);
//output
printf(“%s %s %d %f”, b1.title, b1.author, b1.pages,
b1.price);
return 0;
}
CSE 1001 Department of CSE 5/3/2024 17
508
Structure: Example
struct Book { // definition
char title[20];
char author[15];
int pages;
float price;
};
int main( ){
struct Book b1;
printf(“Input values”);
gets(b1.title); gets(b1.author);
scanf(“%d %f”, &b1.pages, &b1.price);
//output
printf(“%s %s %d %f”, b1.title, b1.author, b1.pages,
b1.price);
return 0;
}
CSE 1001 Department of CSE 5/3/2024 18
509
Name:
Enrolment No:

Odd Semester End Term Examination, December 2023


Department of First Year
B.Tech – All Branches
Course Code: CS1002 Course: Problem Solving Using Computers Semester: I
Time: 03 hrs. Max. Marks: 80
Solution cum Marking Scheme
SECTION A
S.No. Marks CO
Q A1 Predict the output of the following program:
# include <stdio.h>
int main()
{
int x = 3, y = 0;
2
(x & y) ? printf("True ") : printf("False ");
(x && y) ? printf("True ") : printf("False "); CO2
return 0;
}

Solution (i) False (1 marks)


(ii) False (1 marks)

Q A2 Predict the output of the following program:


int main()
{
int x = 65;
printf("%c", x);
return 0;
2 CO2
}

Solution A (2 marks)

Q A3 Draw a flow chart to swap two numbers.


2 CO1

Page 1 of 8

510
Solution

For logic 1 marks and for correct flow chart(symbols) 1 marks.

Q A4 Predict the output of the following C code.


int main() {
int num = 8;
int result = num << 2;
int result1=num>>2;
printf("After left shift by 2 bits:result= %d\n", result);
printf("After left shift by 2 bits: result1=%d\n", result1); 2 CO2
return 0;
}

Solution (i) After left shift by 2 bits:result= 32 (1 Marks)


(ii) After left shift by 2 bits: result1=2 (1 Marks)

Q A5 Explain NULL pointer in the context of C programming? Provide a concise


definition. Also write the size of a character pointer and size of an integer pointer
on a 32-bit system.
2 CO4
Solution (i) A NULL pointer is a pointer that does not point to any memory
location. It points to NULL. (1 marks)
(ii) 4 Byte (1/2+1/2 marks)
SECTION B
Q B1 Write a C program that performs the following tasks sequentially.

#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

Solution #include <stdio.h>

int main() {
// Declare a variable named 'marks' of type 'double'. (1 Marks
double marks;

// Read the value of 'marks' from the user. (1 Marks)


printf("Enter the marks: ");
scanf("%lf", &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)

Q B4 Write a C program which performs the following tasks sequentially.


a. Declare a string variable named ‘place’ with a capacity of 100.
b. Using input function read the string value as “Manipal University Jaipur”.
c. Determine the length of string using string library function.
d. Determine the frequency of the character 'a' in the string and display the
count of it.

Solution (a) Char place[100] (1 marks)


(b) gets(place) or fgets (place, sizeof(place), stdin); (1 marks) 6 CO4
(c) int length = strlen(place); (1 Marks)
(d) int count = 0; (3 Marks)
for (int i = 0; i < length; ++i)
{
if (place[i] == 'a')
{
count++;
}
Q B5 Explain the difference between "Call by Value" and "Call by Reference" in the
context of function parameter passing. Illustrate each concept by citing the example 6 CO4

Page 4 of 8

513
of swapping two numbers.

Solution (a) 2 marks for difference.


(b) (2+2) marks for program of swapping by call by value and call by
reference respectively.
SECTION-C (Analytical Based Questions)
Q C1 Debug and complete the following C program, which is designed to find the
product of the first five prime numbers.
#include <stdio.h>
int main() {
int primes[] = {2, 3, 5, 7, 11};
int product = 1;
// Debug and fix the issues in the for loop
for (int i = 0; i < sizeof(primes); i++) {
product *= primes[i]; }
// Missing logic: Complete the code to display the product of the first five prime
numbers
return 0;
}
Issues to Address: 10 CO3

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.

Solution (a) int K1[2][2], K2[2][2], K3[2][2]; ( 1 Marks)


(b) printf("Enter values for matrix K1 (2x2):\n"); ( 3 Marks)
for (int i = 0; i < 2; ++i) 10 CO4
{
for (int j = 0; j < 2; ++j)
{
printf("Enter element K1[%d][%d]: ", i, j);
scanf("%d", &K1[i][j]);
}
}
printf("Enter values for matrix K2 (2x2):\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
printf("Enter element K2[%d][%d]: ", i, j);
scanf("%d", &K2[i][j]);
}
}

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];
}
}

(d) printf("Resultant matrix K3 :\n"); ( 3 marks)


for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
printf("%d\t", K3[i][j]);
}
printf("\n");
}
SECTION-D
Q D1 #include"stdio.h"
int fun1(int *,int *);
void main()
{
int a=10,b=20,z;
int *p,*q;
p=&a,q=&b;
z=fun1(p,q);
printf("a=%d b=%d p=%d q=%d,\n",a,b,*p,*q);
printf("z=%d\n",z++);
}
int fun1(int *m,int *n)
{
int temp=0,sum=0;
temp=*m;
*m=*n; 10 CO4
*n=temp;
sum=*m+*n;
printf("m=%d n=%d sum=%d\n",*m,*n,sum);
return sum;
}
(i) What value of m,n,sum will be printed?
(ii) What value of a,b,p,q will be printed?
(iii) What value of z will be printed?

Solution (i) m=20 n=10 sum=30 (1.5+1.5+1.5 Marks)


(ii) a=20 b=10 p=20 q=10, ( 1+1+1+1 Marks)
(iii) z=30

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:

a. Define a structure named Employee with the following attributes:


Employee_ID (integer)
First_Name (string)
Salary (float)
b. Create a structure to store information of 2 employees in the inventory.
c. Display the information of both the employees.
Solution (a) struct Employee ( 2 marks)
{
int Employee_ID;
char First_Name[50];
float Salary;
};

(b) // Create structures to store information for 2 employees ( 5 marks)


struct Employee employee1, employee2;

// Input information for employee1


printf("Enter details for Employee 1:\n");
printf("Employee ID: ");
scanf("%d", &employee1.Employee_ID); 10 CO5
printf("First Name: ");
scanf("%s", employee1.First_Name);
printf("Salary: ");
scanf("%f", &employee1.Salary);

// Input information for employee2


printf("\nEnter details for Employee 2:\n");
printf("Employee ID: ");
scanf("%d", &employee2.Employee_ID);
printf("First Name: ");
scanf("%s", employee2.First_Name);
printf("Salary: ");
scanf("%f", &employee2.Salary);

(c) // Display information of both employees (3 Marks)


printf("\nEmployee 1 Details:\n");
printf("Employee ID: %d\n", employee1.Employee_ID);
printf("First Name: %s\n", employee1.First_Name);
printf("Salary: %.2f\n", employee1.Salary);

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

You might also like