0% found this document useful (0 votes)
16 views

Computer Hardware and Software BMS

The document discusses the history and generations of computers from the first generation using vacuum tubes to the modern fifth generation pursuing artificial intelligence. It covers the characteristics and uses of different types of computers including microcomputers, minicomputers, and mainframes.

Uploaded by

Nirmala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Computer Hardware and Software BMS

The document discusses the history and generations of computers from the first generation using vacuum tubes to the modern fifth generation pursuing artificial intelligence. It covers the characteristics and uses of different types of computers including microcomputers, minicomputers, and mainframes.

Uploaded by

Nirmala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 368

Module 1:

INTRODUCTION TO COMPUTER
HARDWARE AND SOFTWARE

Swetha M S
Asst. Professor
Dept. of ISE
BMSIT&M

Department of Information Science and Engg


Transform Here
What is computer?
A Computer is device that can automatically
performs a set of instructions. The computer takes
as input these instructions as a single unit, uses
them to manipulate the data, and outputs the
results in user-specified ways. The processing is
fast, accurate and consistent, and is generally
achieved without significant human intervention.

Department of Information Science and Engg


Transform Here
History of Computer

Department of Information Science and Engg


Transform Here
COMPUTER GENERATIONS
Generation Based on Other Features

First. Vacuum tubes Magnetic drums for memory

Magnetic cores, disks, punched cards and


Second Transistors
printouts

Integrated circuits
Third. Keyboard, monitor and operating system
(ICs)

Fourth Microprocessors Networking

ULSI Nano
Fifth Mainly unclear
technology.

Department of Information Science and Engg


Transform Here
Vacuum Tubes: The First Generation
 Memory requirements were met by magnetic drums (forerunner of today's
hard disk).
 Because of the size of vacuum tubes, first generation computers took up a
lot of space.
 They also consumed enormous amounts of power and generated a lot of
heat. In spite of housing these computers in air-conditioned enclosures,
frequent breakdowns were common.
 The ENIAC used 18,000 vacuum tubes, occupied 1800 sq. ft. of room space
and consumed 180KW of power.
 Machines of this generation were prohibitively expensive to buy and
maintain.
 First-generation computers were programmed using a first-generation
language-machine language.
 Program input was provided by punched cards and output was obtained on
paper.
 First-generation computers were only used for scientific work and were not
Department of Information Science and Engg
deployed commercially. Transform Here
Vacuum Tubes

Department of Information Science and Engg


Transform Here
Transistors: The Second Generation

 Compared to vacuum tubes, transistors were faster, smaller and


consumed less power smaller magnetic cores also replaced the first-
generation magnetic drums.
 Even though transistor generated less heat, second-generation
computers still needed air-conditioning.
 The input-output mechanism however remained largely unchanged.
 Second-generation computers were programmed using a symbolic
or assembly language.
 The computers also implemented the stored program concept
which allowed both program and data to reside in memory.

Department of Information Science and Engg


Transform Here
Transistors: The Second Generation

Department of Information Science and Engg


Transform Here
Department of Information Science and Engg
Transform Here
Integrated Circuits: The Third Generation
 By virtue of miniaturization, computers consequently got smaller,
cheaper and energy efficient. For these reasons, they could be seen
in several medium-sized organizations.
 This generation adopted a keyboard and monitor to interact with
the user.
 Memory capacity increased substantially and the magnetic hard
disk was used for secondary storage.
 Third-generation computers also had an operating system, which is
a special program meant to control the resources of thecomputer.
 By virtue of a feature known as time sharing, the computercould
run programs invoked by multiple users.
 The existing programming languages were supplemented by
BASIC, C, C++ and Java.
Department of Information Science and Engg
Transform Here
Integrated Circuits: The Third Generation

Department of Information Science and Engg


Transform Here
The Microprocessor: The Fourth Generation
 The integration of components went several steps ahead. Using LSI and
VLSI technology, it is now possible to have the entire CPU, its
associated memory and input/output control circuitry on a single chip.
 Intel introduced the 4004 microprocessor in 1971 and improvement in
the usual parameters (like speed, heat generation, size, etc.) continues
at a frenetic pace to this day.
 Microprocessors have invaded our homes to drive desktops, laptops,
smartphones,microwave ovens and washing machines.
 Laptops and smartphones offer gigabytes (GB) of memory compared
to a few megabytes (MB) that were available in the early days of this
generation.
 Operating systems have moved from the rudimentary MSDOS to a
mouse based Graphical User Interface (GUI) like Windows. More
advanced systems like Linux are now available for desktops and laptops,
and a variant of it (Android) powers most of our smartphones.

Department of Information Science and Engg


Transform Here
The Microprocessor: The Fourth Generation

Department of Information Science and Engg


Transform Here
Artificial Intelligence: The Fifth Generation

 The fifth generation represents a vision of the computers of the future. The
conventional parameters of computing (speed, size, energy consumption,
VLSI to UL.SI, etc.) would continue to improve path-breaking changes in
the way we use computers are also expected.
 Fifth-generation systems should be capable of producing human-like behaviour.
These systems expected to interact with users in natural language and learn from
experience. Speech recognition and speech output should also be possible with
these systems.
 Computer speeds need to make an exponential jump, a feat that would be
possible using quantum computers.
 Computers must be able to perform parallel processing so that multiple
processors concurrently handle different aspects of a problem.
 Neural networks and expert systems have to be developed. These applications
would be able to make decisions and advise humans by analysing data using
human-like intelligence but without using the services of an expert.

Department of Information Science and Engg


Transform Here
Department of Information Science and Engg
Transform Here
Types of Computers

Types of
Computers

Microcomputer Minicomputer Mainframe Supercomputer

16 Department of Information Science and Engg


Transform Here
1. Microcomputer
• Can be classified into:
•Desktop PCs
•sits on desks, rarely moved, large and
bulky.
•Memory capacity, graphics capacity and
software availability vary from one
computer to another Used both for
business and home applications

17 Department of Information Science and Engg


Transform Here
Microcomputer

•Portable PCs
•Can be moved easily from place to
place
•Weight may varies
•Small PCs are popular known as
laptop
•Widely used by students, scientist,
reporters, etc
18 Department of Information Science and Engg
Transform Here
Microcomputer Model

Desktop Laptop Notebook

Subnotebook Palmtop

19 Department of Information Science and Engg


Transform Here
Microcomputer
•Advantages
•Small size
•Low cost
•Portability
•Low Computing Power
•Commonly used for personal applications

•Disadvantages
•Low processing speed
20 Department of Information Science and Engg
Transform Here
Uses of Microcomputer
•Word Processing

•Home entertainment

•Home banking

•Printing
21 Department of Information Science and Engg
Transform Here
2. Minicomputer
• Medium sized computer
• Also called the minis
• e.g. IBM36, HP9000, etc
• Computing power lies between microcomputer and
mainframe computer

22 Department of Information Science and Engg


Transform Here
23 Department of Information Science and Engg
Transform Here
MiniComputer
•Characteristics
•Bigger size than PCs
•Expensive than PCs
•Multi-User
•Difficult to use
•More computing power than PCs
•Used by medium sized business organizations,
colleges, libraries and banks.

24 Department of Information Science and Engg


Transform Here
Uses of Minicomputer
• Control of Automated Teller Machine (ATMs)

• Hospital patients registration

• Inventory Control for supermarket

• Insurance claims processing

• Small bank accounting and customer details tracking

25 Department of Information Science and Engg


Transform Here
Minicomputer
•Advantage
•Cater to multiple users
•Lower costs than mainframes
•Disadvantage
•Large
•Bulky

26 Department of Information Science and Engg


Transform Here
3. Mainframe
• Known as enterprise servers

• Occupies entire rooms or floors

• Used for centralized computing

• Serve distributed users and small


servers in a computing network

27 Department of Information Science and Engg


Transform Here
Main Frame
• Large, fast and expensive computer
• Cost millions of dollar
• e.g. IBM3091, ICL39, etc
• Characteristics:
• Bigger in size than minicomputers Very expensive
• Support a few hundred users simultaneously (Multi-
Users)
• Difficult to use
• More computing power than minicomputers
• Have to be kept in a special air-conditioned room
• Used in big business organizations and government
departments

28 Department of Information Science and Engg


Transform Here
29 Department of Information Science and Engg
Transform Here
30 Department of Information Science and Engg
Transform Here
Mainframe
•Advantage
•Supports many users and instructions
•Large memory
•Disadvantage
•Huge size
•Expensive

31 Department of Information Science and Engg


Transform Here
Supercomputer

• Fastest and expensive


• Used by applications for
molecular chemistry, nuclear
research, weather reports, and
advanced physics
• Consists of several computers
that work in parallel as a single
system

32 Department of Information Science and Engg


Transform Here
Super Computer

• Advantage
• Speed

• Disadvantage
• Generate a large
amount of heat
during operation

33 Department of Information Science and Engg


Transform Here
Information Processing System

• DATA is a collection of independent and unorganized facts.

• INFORMATION is the processed and organized data presented in a


meaningful form.

• DATA PROCESSING is the course of doing things in a sequence of steps.

Department of Information Science and Engg


Transform Here
Information Processing System

• COMPUTER is an electronic machine that follows a set of instructions in


order that it may be able to accept and gather data and transform these
into information.

Department of Information Science and Engg


Transform Here
PROCESSING
SYSTEM

DATA INFORMATION

Department of Information Science and Engg


Transform Here
Functions of an Information Processing
System

1. It accepts and gather data. (INPUT)

1. It processes data to become information. (PROCESSING)

2. It stores data and information. (STORE)

3. It presents information. (OUTPUT)

Department of Information Science and Engg


Transform Here
Three Major Components of an
Information Processing System

• HARDWARE is the tangible part of a computer system.

• SOFTWARE is the non-tangible part that tells the computer how to do its
job.

• PEOPLEWARE refer to people who use and operate the computer


system, write computer programs, and analyze and design the
information system.

Department of Information Science and Engg


Transform Here
Basic Units of Measurement

• BIT is a unit of information equivalent to the result of a choice between


only 2 possible alternatives in the binary number system.

• BYTE is a sequence of 8 bits (enough to represent one character of


alphanumeric data) processed as a single unit for information.

Department of Information Science and Engg


Transform Here
Basic Units of Measurement

•A byte can be used to represent a single


character, which can be:

•A letter
•A number
•A special character or symbol, or
•A space

Department of Information Science and Engg


Transform Here
Department of Information Science and Engg
Transform Here
BITS, BYTES AND WORDS
Unit Equivalent to Remarks

1 kilobyte (KB) 1024 bytes Space used by 10 lines of text.

I megabyte (MB) 1024 kilobytes Memory of the earliest PCs

1 gigabyte (GB) 1024 megabytes Storage capacity of a CD-ROM

I terabyte (TB) 1024 gigabytes Capacity of today's hard disks.

1 petabyte (PB) 1024 terabytes Space used for rendering of film Avatar

Department of Information Science and Engg


Transform Here
INSIDE THE COMPUTER

Department of Information Science and Engg


Transform Here
THE CENTRAL PROCESSING UNIT (CPU)

The CPU has evolved from a bulky vacuum tube


based unit of the 1940s to a modern 5cm square
chip that is commonly called the
microprocessor, or simple processor. It
comprises the following components
 Arithmetic and Logic Unit (ALU)
 Control Unit (CU)
 Special purpose registers
 A clock

Department of Information Science and Engg


Transform Here
PRIMARY MEMORY
The primary memory which includes the following
types:
 Random Access Memory (RAM-SRAM and DRAM)
Read Only Memory (ROM, PROM, EPROM,
EEIROM)
 Cache Memory (Li, L2 and L3)
 CPU Registers

Department of Information Science and Engg


Transform Here
SECONDARY MEMORY
The last couple of decades have seen the emergence of
multiple types of storage devices.
Hard disk including the portable disk (500 GB to 4
TB).
 Magnetic tape (20 TB).
 CD-ROM (700 MB-less than 1 GB).
 DVD-ROM (4.7 GB and 8.5 GB).
 Blu-ray disk (27 GB and 50 GB).
Flash memory based on the EEPROM (1 GB to 128
GB).
 The obsoleted floppy disk (1.2 MB and 1.44 MB).
Department of Information Science and Engg
Transform Here
The Hard Disk
• Every disk contains a spindle that holds one or more platters made of
non-magnetic material like glass or aluminium (Fig. 1.4). Each platter has
two surfaces coated with magnetic material.
• Information is encoded onto these platters by changing the direction of
magnetization using a pair of read-write heads available for each platter
surface.
• Eight surfaces require eight heads; they are mounted on a single arm and
cannot be controlled individually.
• Each surface is composed of a number of concentric and serially numbered
tracks.
• There are many tracks bearing the same track number as there are
surfaces. This can then visualize a cylinder comprising all tracks bearing
the same number on each disk surface.
• Thus, there will be as cylinders in the disk as there are tracks on each
usable surface.
 Each track is further broken into sectors or blocks. So, if each track has
32 blocks and a disk has eight surfaces,
Department then and
of Information Science UpEngg
256 blocks per cylinder.
Transform Here
Department of Information Science and Engg
Transform Here
Magnetic Tape
 The age-old magnetic tape is still around thanks to the enhancements that have been
made to this device.

 The basic technology has not changed though; the tape is made of a plastic film with one
side coated with magnetic material.

 Current technology supports capacities of 1 TB or more, but 200 TB tapes are expected
to be launched in the near future.

 The device is portable though because a separate tape drive is required, and most
computers don't have one.

 Data are read from and written to the tape using a read-write head and an erasure head.

 The write operation is preceded by the erasing operation. The data access is sequential.
To locate a file, the tape has to be rewound before a sequential search can begin.
Department of Information Science and Engg
Transform Here
Optical Disks: The CD-ROM, DVD-ROM
 Non-volatile read-only memory, which we saw in the ROM family (including
PROM, EPROM and EEPROM), is also available on optical disks. These
disks, comprising mainly the CD-ROM and DVD-ROM, can hold large
volumes of data (700 MB to 8.5 GB) on inexpensive media.

 CD-R, DVD-R – Data can be recorded only once, CD-RW, DVD-RW – Data
can be recorded multiple times.

 The optical drive uses three motors for the following functions: operating
the tray, spinning the disk and guiding the laser beam.

Department of Information Science and Engg


Transform Here
Flash Memory
 They are portable, need little power and are quite reliable.
 The memory stick or pen drive is the most common type of flash
memory used on the computer.
 The solid state disk (SSD) a bigger device meant to replace the
traditional magnetic hard disk. Many small laptops (like Chrome
books) have the operating system and a small set of programs
stored on this online device.
 The third device, the magnetic card, is used mainly in cameras,
but using adapters, they can connect to the USB port as well.
 The most popular form of this device is the micro-SD card, which is
available in SDHC and SDXC flavours. The SD card offer high
capacities that can go up to 128 GB.

Department of Information Science and Engg


Transform Here
Floppy Diskette
The floppy diskette was once the only form of
portable storage that could be carried in the pocket.
A read/write head actually makes contact with this
disk while it is rotating.
The floppy was available in two sizes (5.25" and
3.5"), offering capacities of 1.2 MB and 1.44 MB (yes,
MB not GB), respectively.

Department of Information Science and Engg


Transform Here
PORTS AND CONNECTORS
1. Universal Serial Bits (USB)
2. Serial port
3. Parallel port
4. Video Graphics Array (VGA) port
5. digital video interface (DVI)
6. PS(Personal System)/2 port
7. High Definition Multimedia Interface (HDMI)

Department of Information Science and Engg


Transform Here
INPUT DEVICES
1. The Keyboard
2. Pointing Devices
3. The Scanner

Department of Information Science and Engg


Transform Here
OUTPUT DEVICES
1. The Monitor
2. Impact Printers
▫ Dot-matrix Printer
▫ Daisy-wheel Printer
▫ Line Printer
3. Non-Impact Printers
Laser Printer
Ink-jet Printer
4. Plotters

Department of Information Science and Engg


Transform Here
Department of Information Science and Engg
Transform Here
COMPUTERS IN ANETWORK
• Interconnection of computer is called a
computer network.
• Different ways of connecting computers in
network is called as network topology.

Department of Information Science and Engg


Transform Here
Network Types

• Local Area Network (LAN)


• Wide Area Network (WAN)
• Technology advances have led to the birth of other types of
networks
• Metropolitan Area Network (MAN)
• Campus Area Network (CAN)
• Personal Area Network (PAN)
• The Internet and internet

Department of Information Science and Engg


Transform Here
NETWORK HARDWARE
• Network Interface Card
• Hub and Switch
• Bridge and Router

Department of Information Science and Engg


Transform Here
WHY COMPUTERS NEED SOFTWARE
Software is a collection of code that drives a computer to
perform a related group of tasks.
SOFTWARE TYPES
• System software
▫ Basic Input Output System (BIOS)
▫ Operating system
▫ Device driver
▫ Compilers and associated programs
• Application software
▫ Office software
▫ Database software
▫ Communications software
▫ Entertainment software
Department of Information Science and Engg
Transform Here
HISTORY OF C

Department of Information Science and Engg


Transform Here
BASIC STRUCTURE OF C PROGRAMS

Department of Information Science and Engg


Transform Here
C Syntax and Hello World
#include inserts another file. “.h” files are called
“header” files. They contain stuff needed to interface to
libraries and code in other “.c” files.

This is a comment. The compiler ignores this.

#include <stdio.h>
The main() function is always
/* The simplest C Program */ where your program starts
Int main ( ) running.
{
Blocks of code (“lexical
printf(“Hello World\n”); scopes”) are marked by { … }
return 0;
}

Return ‘0’ from this function Print out a message. ‘\n’ means “new line”.
63 Department of Information Science and Engg
Transform Here
Writing and Running Programs
#include <stdio.h>
/* The simplest C Program */
int main(int argc, char **argv)
{
1. Write text of program (source code) using an editor
printf(“Hello World\n”);
return 0;
such as vi, gedit, save as file e.g. programname.c
}

2. Run the compiler to convert program from source to


an “executable” or “binary”:
$ cc programname.c

$ cc program name.c
tt.c: In function `main':
tt.c:6: parse error before `x'
tt.c:5: parm types given both in parmlist and separately
tt.c:8: `x' undeclared (first use in this function)
3. Compiler gives errors and warnings; edit source file,
tt.c:8: (Each undeclared identifier is reported only once
tt.c:8: for each function it appears in.)
fix it, and re-compile
tt.c:10: warning: control reaches end of non-void function
tt.c: At top level:
tt.c:11: parse error before `return'

4. Run it and see if it works 


$ ./a.out
Hello World
program
$▌

64 Department of Information Science and Engg


Transform Here
OK, We’re Back.. What is a Function?
A Function is a series of instructions to run. You pass
Arguments to a function and it returns a Value.

“main()” is a Function. It’s only special because it


always gets called first when you run your program.

Return type, or void

Function Arguments
#include <stdio.h>
/* The simplest C Program */
int main(int argc, char **argv)
{ Calling a Function: “printf()” is just
another function, like main(). It’s defined
printf(“Hello World\n”);
for you in a “library”, a collection of
return 0; functions you can call from your program.
}
Returning a value
65 Department of Information Science and Engg
Transform Here
Department of Information Science and Engg
Transform Here
EXECUTING A ‘C’PROGRAM

Department of Information Science and Engg


Transform Here
Queries?

Department of Information Science and Engg


Transform Here
Module-2
Managing input/output
Decision Making & Branching

Swetha M S
Dept of ISE
BMSIT&M

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-1
Looping statements
• Loop is a control structure that repeats a group
of steps in a program.
– Loop body stands for the repeated statements.
• There are three C loop control statements:
– while, do-while and for.

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-2
Comparison of Loop Choices (1/2)
Kind When to Use C Structure
Counting loop We know how many loop while, for
repetitions will be needed
in advance.
Sentinel- Input of a list of data ended while, for
controlled loop by a special value
End file- Input of a list of data from while, for
controlled loop a data file

Department of ISE BMS Institute of Technology & Mgmt 5-3


Comparison of Loop Choices (2/2)
Kind When to Use C Structure
Input validation Repeated interactive input do-while
loop of a value until a desired
value is entered.
General Repeated processing of while, for
conditional data until a desired
loop condition is met.

Department of ISE BMS Institute of Technology & Mgmt 5-4


The while Statement in C
• The syntax of while statement in C:
while (loop repetition condition)
{ statements; }
• Loop repetition condition is the condition
which controls the loop.
• The statement is repeated as long as the loop
repetition condition is true.
• A loop is called an infinite loop if the loop
repetition condition is always true.
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-5
Flow diagram –while loop

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-6
Check the given number is palindrome or not
int main( )
{ int n,temp,digit,rev=0;
printf("enter a integer number\n");
scanf("%d",&n);
temp=n;
while (n!=0)
{ digit=n%10;
n=n/10;
rev=digit+10*rev;
} // while ends
if(temp==rev)
{
printf("%d is a PALINDROME\n",temp);
} // if ends
else
{ printf("%d is not a PALINDROME\n",temp); }
return 0;
}
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-7
WAP to check whether the given number is armstrong or not
def: if the given number is equal to the sum of the cubes of individual digits
then it is known as armstrong ex: 407,153= 1 + 125 + 27 = 153

#include<stdio.h> if (m==s)
int main() printf("The number is Armstrong");
{ else
int r,s=0,n,m; printf("The number is not a
printf("Enter a number"); Armstrong");
scanf("%d",&n); getch();
m=n; }
while(n>0)
{
r=n%10;
n=n/10;
s=s+(r*r*r);
}
Department of ISE BMS Institute of Technology & Mgmt 5-8
The do-while Statement in C
• The syntax of do-while statement in C:
do
statement
while (loop repetition condition);
• The statement is first executed.
• If the loop repetition condition is true, the
statement is repeated.
• Otherwise, the loop is exited.
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-9
Flow diagram do-while loop

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-10
Example –do while
(input validation loop)
#include <stdio.h>
int main( )
{ int sum=0,num;
do
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
} while(num!=0);
printf("sum=%d",sum);
return 0;
} Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-11
An Example of the do-while Loop

/* Find even number input */


do{
printf(“Enter a value: ”);
scanf(“%d”, &num);
}while (num % 2 !=0)

This loop will repeat if the user


inputs odd number.

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-12
Difference b/w while & do while
While Do while
1. Entry controlled loop 1. Exit Controlled loop
2. If the condition is FALSE , while 2. If the condition is FALSE also in do-
loop is never executed. while loop, at least once statements can
be executed.

3. syntax: 3. Syntax
while(condn) do
{ stmts;} { stmts;
}while(condn);

4. Flow diagram 4. Flow Diagram

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-13
The for Statement in C
• The syntax of for statement in C:
for (initialization ; condition ; update expr)
{ statements;
}
• The initialization expression set the initial value of the
loop control variable( using assignment operator =).
• The condition test the value of the loop control
variable(using Relational Operator).
• The update expression update the loop control
variable(using incr/decr operator).
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-14
Flow diagram -for loop

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-15
for statement
for(i=0;i<=4;i++)
{
printf(“\t%d”,i)
}
printf(“\n for loop over”);
O/P
1 2 3 4 5
for loop over
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-16
Comparison of 3 loops
For loop while Do while
for (n=1;n<=10;n++) n=1; n=1;
{ while(n<=10) do
………….. { {
………….. ………….. …………..
} ………….. …………..
n=n+1 n=n+1;
} }
while(n<=10);

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-17
C pgm to sum of first n natural numbers
#include <stdio.h>
Output
int main()
Enter the value of n.
{ int n, count, sum=0; 10
printf("Enter the value of Sum=55
n.\n"); scanf("%d",&n);
for(count=1;count<=n;++count)
{ sum+=count; }
printf("Sum=%d",sum);
return 0; }

Department of ISE BMS Institute of Technology & Mgmt 5-18


C pgm to find factorial of a given number
#include<stdio.h>
int main( )
{
int i,f=1,num;
printf("Enter a number: ");
scanf("%d",&num);
for(i=1;i<=num;i++)
f=f*i;
printf("Factorial of %d is: %d",num,f);
return 0;
}
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-19
Additional Features of for
• More than1 variable can be initialized
• More than 1 part for update expression
section
• Test condition can have any compound
relation
• More than 1 parts in each section will be
seperated by commas.
for(i=1,m=50; i<20 && sum <100; i++,m--)

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-20
Additional Features of for
• We can also use expression in the initialization
and incr/decr part.
for( x=((m+n)/2;x>0;x=x/2)
• One or more sections can be omitted, if
necessary
m=5;
for( ;m!=100; )
{ printf(“%d\n”, m);
m=m+5;
}
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-21
Nested Loops
• Nested loops consist of an outer loop with one
or more inner loops.
• e.g.,
for (i=1;i<=100;i++){ Outer loop

for(j=1;j<=50;j++){
… Inner loop
}
}
• The above loop will run for 100*50 iterations.
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-22
Eg pgm using nested for loops
#include <stdio.h>
O/P
int main() i=1 j=1
{ i=1 j=2
int I,j; i=1 j=3
i=2 j=1
for(i=1;i<=3;i++) i=2 j=2
{for(j=1;j<=3;j++) i=2 j=3
printf(“i=%d \t j=%d”, i,j); i=3 j=1
i=3 j=2
}return 0; i=3 j=3
}

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-23
C program to print Floyd's triangle:
#include <stdio.h>
int main()
{
int n, i, c, a = 1;
printf("Enter the number of rows of Floyd's triangle
to print\n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (c = 1; c <= i; c++)
{
printf("%d ",a);
a++;
}
printf("\n");
}
return 0;
} Department of ISE Acharya Institute of Technology
5-24
Homework #4 (1/2)
• Write a program that prompts the user to input
an integer n.
• Draw a triangle with n levels by star symbols.
For example,
n = 3,
*
**
***
• After drawing the triangle, repeat the above
process until the user input a negative integer.
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-25
Homework #4 (2/2)
• An usage scenario:
Please input: 2
*
**
Please input: 3
*
**
***
Please input: -9
Thank you for using this program.
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-26
Unconditional control Transfer)
• C permits a jump from one statement to
another within a loop as well as the jump out
of a loop.
• 4 unconditional control statements are
available in C
– goto (branching statement)
– break (looping)
– continue (looping)
– return (used only in functions)
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-27
UNCONDITIONAL BRANCHING
STATEMENTS (goto)
• C supports the goto statement to branch
unconditionally from one point of the program to
another.
• The goto requires a label in order to identify the
place where the branch is to be made.
• A label is any valid variable name and must be
followed by a colon.
goto label;
• The general form is .. .
label:

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-28
UNCONDITIONAL BRANCHING
STATEMENTS (goto)

Note: Don’t use 2 labels with same name

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-29
Example for goto
#include<stdio.h>
#include<math.h>
main()
{
double x, y;
read:
printf(“Enter a No:”);
scanf(“%f”,&x);
if(x < 0)
goto read;
y = sqrt(x);
printf(“sqrt root of %f is %f \n”,x, y);
return 0;
}
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-30
Example-2
// pgm to print n natural numbers
#include<stdio.h> natural:
#include<conio.h> if(i<=n)
void main() {
{ printf("%5d",i); i++;
int n,i=1; goto natural;
clrscr(); }
printf("Enter the final value"); getch();
scanf("%d",&n); }
printf("The natural numbers
are \n");

Department of ISE BMS Institute of Technology & Mgmt 5-31


Break statements
• The break command unconditionally stops the
execution of any loop in which it is
encountered, and goes to the next command
after the done.
• it is used to move the control outside of the
control statements.
• Syntax break;

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-32
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-33
Eg of break statment
main()
{
int t ;
for ( ; ; ) // infinite loop
{
printf(“\nEnter a Value:”);
scanf("%d" , &t) ;
if ( t==10 )
break ;
}
printf("End of an infinite loop...\n");
} Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-34
NOTE: When the loops are nested, the break
would only exit from the loop containing it.
That is, the break will exit only a single loop.
for(…….)
{
…..
for(…..)
{
if(condn)
break;
} Exit from inner loop

….
} Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-35
4. Evaluate polynomial using Horner’s method (LAB
pgm) f(x)=a4x4+a3x3+a2x2+a1x+a0

#include<stdio.h> for(i=n;i>=0;i--)
#include<conio.h> {printf(“\na[%d]=“,i);
void main() scanf("%d",&a[i]);
{ }
int n,i,sum,a[10],x; printf(“\nEnter the Value of x:");
sum=0; scanf("%d",&x);
printf(“\nEnter the noof coefficients:"); for(i=n;i>=0;i--)
scanf("%d",&n); {
printf("Enter n+1 co-efficients: \n"); sum=sum*x+a[i];
}
printf("Sum is %d",sum);
getch();
}
Department of ISE BMS Institute of Technology & Mgmt 5-36
continue
Syntax: continue;
• The keyword continue allows us to take the
control to the beginning of the loop bypassing
the statements inside the loop which have not
yet been executed.

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-37
Pgm to show how continue works
#include<stdio.h> Output
main( )
{ 12
int i,j; 21
for(i = 1; i< = 2; i++)
{
for(j=1; j<=2; j++)
{
if (i= =j)
continue;
printf(“\n%d\t%d\n”, i,j);
}
}
return 0
} Department of ISE BMS Institute of Technology & Mgmt 5-38
Sum of positive elements
#include<stdio.h>
int main()
{
int a[5]={-1,2,-3,4,-5};
int i,sum=0;
for(i=0;i<5;i++)
{
if(a[i]<0)
continue;
sum+=a[i];
}
printf(“sum of positive elements: %d\n”, sum);
return 0;
}
Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-39
Difference b/w break & continue
S.No Break Continue

1. Appears both in switch Appears only in


and loop(for, while ,do) loop(for,while,do) statements
statements
2. Used to exit from the Used to continue the loop,
loop immediately skipping one or more
skipping one or more statements in the loop.
statements in the loop
3. Syntax: break; Syntax: continue;

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt 5-40
Module-3
Arrays

By
Prof Swetha M S
ISE-BMSIT&M
Department of ISE BMS Institute of Technology & Mgmt
Syllabus-Arrays
o Using an array
o Using arrays with Functions
o Multi-Dimensional arrays

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Arrays
Defn:
Array is a data structure that represents a
collection of elements of same data type. (derived
data type)
Syntax: datatype array_name[subsript/index/size];
Eg: int Num[3];
Num[0] Num[1] Num[2]

Array name: Num

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Need
• Easy to process large amount of data
Classification of Arrays
• Single (one) Dimensional
• Two dimensional
• Multidimensional

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Single dimensional Array
• Linear list consist of data items of same
type.
• In memory all data items stored in
continuous memory location.
eg. int a[3];
a[0]
10 a[1] 30a[2]
20

1000 1002 1004 1005


Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Properties of Array
1. Elements stored in array should be of same type
2. Elements are stored contiguously in memory.
3. Subscript of first item is always zero(if not specified)
4. Each data item is accessed using the name of the array
5. Index of the array is always an integer
eg. a[2] √ correct
a[2.5] X wrong
a[‘5’] √ correct it takes ASCII value of ‘5’
a[5+2] √ correct

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Declaration of one dimensional
Array
Syntax: Datatype array_name[index];
• int marks[5]; mem2* 5=10 bytes
• float avg [3]; mem4*3=12 bytes
• char name[5]; mem1*5=5 bytes
Declaration using Named constants
const int SIZE=5;
int a[SIZE];
Declaration using Symbolic Constants
#define SIZE 3;
int marks[2+SIZE];

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Storing values in Arrays
• Initialization
• Assigning values
• User input from keyboard
Initialization
data type
array_name[index]={v1,v2,…vn};
eg int a[5]= {10,20,30,40,50};

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Initialization
1. int a[3]={1,2,3,4,5} // Error number of values more than
the size of the array

2. char name[5]={‘K’, ‘U’, ‘M’, ‘A’,’R’};


3. int a[5]={10,20};
4. int a[ ]={10,20,30,40};
Array initialization with String
String is defined as sequence of character enclosed within
double quotes ends with NULL(\0) character.
Char b[ ]= “WELCOME” // array size is equal to size of string +1
W E L C O M E \0

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
• Note: Size of the array must be known
during compilation.
• Eg:
main()
{
int a[ ]; // error
a[1]=20;

}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
User input for arrays
• Using loops

Reading array Input Displaying ouput array

for(i=0;i<=n-1;i++) for(i=0;i<=n-1;i++)
{ {
scanf(“%d”,&a[i]); printf(“%d”,a[i]);
} }

Department of ISE BMS Institute of Technology & Mgmt


Bubble sort
#include<stdio.h> {
#include<conio.h> if(a[j]>a[j+1])
void main() {
{ temp=a[j];
int n,i,j,a[10],temp; a[j]=a[j+1];
clrscr(); a[j+1]=temp;
printf("Enter the No. of Elements:\n"); }
scanf(“%d”,&n); }
printf(“ Enter the array Elements:\n”); }
for(i=0;i<n;i++) printf(“\nThe sorted elements are:\n");
{ for(i=0;i<n;i++)
printf("\t"); {
scanf("%d",&a[i]); printf("\t");
} printf("%d",a[i]);
for(i=0;i<n-1;i++) }
{ getch();
for(j=0;j<n-1+i;j++) }
Department of ISE BMS Institute of Technology & Mgmt
Output
Enter the No. of Elements: 5
Enter the array Elements:
5 3 1 2 4
The sorted elements are
1 2 3 4 5

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Copy one array to another
array
// Copying data from array 'a' to array 'b ‘
#include<stdio.h> for (i = 0; i < num; i++)
int main() { {
int arr1[30], arr2[30], i, num; arr2[i] = arr1[i];
printf("\nEnter no of elements:"); }
scanf("%d", &num); //Printing of all elements of array
//Accepting values into Array printf("The copied array is :");
printf("\nEnter the values :"); for (i = 0; i < num; i++)
for (i = 0; i < num; i++) {
{ printf("\narr2[%d] = %d", i,arr2[i]);
scanf("%d", &arr1[i]); }
} return (0);
}
Department of ISE BMS Institute of Technology & Mgmt
Output
Enter no of elements : 5
Enter the values : 11 22 33 44 55
The copied array is : 11 22 33 44 55

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
H/w
• average of array elements
• Find max value in an array
• Sum of odd and even numbers in an array

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Two dimensional arrays
• A two dimensional array stores data as a
logical collection of rows and columns.
• Also called arrays of arrays ( matrix)
• Each element of a two-dimensional array has a
row position and a column position.
• Syntax:
– data type array_name[row][col];
– eg: int array[5][3];

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Creating/declaring 2-D arrays
int a[3][2];

a[0,0] a[0,1]
a[0,0]
a[1,0] a[1,1]
a[2,0] a[2,1]

• Row size and col size must be integers.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Initializing 2D arrays
• int data[2][5]; //allocates consecutive memory for
10 integer values
Initialized directly in the declaration statement

• double t[2][2] = {{3.0,5.0},{2.1,7.2}};


//allocates and initializes
(Or)
t[0][0]= 3.0; t[0][1]=5.0; t[1][0]=2.1; t[1][1]=7.2
3.0 5.0 2.1 7.2

1 st row 2nd row

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
int c[ ][3] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12} };
Implicitly declares the number of rows to be 4.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Input of Two-Dimensional Arrays
• Data may be input into two-dimensional
arrays using nested for loops interactively or
with data files.
for (i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
scanf(“%d “, &a[i][j]);
}
printf(“\n”);
} Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Output of Two-Dimensional Arrays
• Nested for loops are used to print the rows
and columns in row and column order.
int a[2][3] = {5, 6, 9, 4, 2, 10};

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


{
for(j = 0; j < 3; j++)
{
printf(“%d “, a[i][j]);
}
printf(“\n”);
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Matrix addition
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
scanf("%d", &first[c][d]);
}
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);

printf("Sum of entered matrices:-\n");


for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
//Sum[0][0]=first[0][0]+sec[0][0]
//Sum[0][1]
printf("%d\t", sum[c][d]);
}
printf("\n");
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
return 0; }
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Matrix Multiplication
“For matrix multiplication, the number of columns in the first matrix
must be equal to the number of rows in the second matrix”
2x2 3x3
#include <stdio.h>
include<process.h>
int main()
{
int r1, c1,r2,c2 i, j,k, a[5][5], b[5][5], c[5][5];
printf("Enter the number of rows and columns of matrix A\n");
scanf("%d%d", &r1, &c1);
printf("Enter the number of rows and columns of matrix B\n");
scanf("%d%d", &r2, &c2);
if(c1!=r2)
{
printf(“Matrix Multiplication not possible\n”);
exit(0); Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
else
{
printf("Enter the elements of first matrix\n");
for (i = 1; i < =r1; i++)
for (j = 1; j <= c1; j++)
scanf("%d", &a[i][j]);

printf("Enter the elements of second matrix\n");


for (i = 1; i <=r2; i++)
for (j = 1 ; j < =c2; j++)
scanf("%d", &b[i][j]);

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
for(i=1;i<=r1;i++) printf("The product of 2 Matrices are:\n
{ for(i=1;i<=r1;i++)
for(j=1;j<=c2;j++) {
{ for(j=1;j<=c2;j++)
c[i][j]=0; {
for(k=1;k<=c1;k++) printf("%d \t",c[i][j]);
{ }
c[i][j]=c[i][j]+a[i][k]*b[k][j]; printf(“\n”);
}
}
}
}
return 0;
}
}

Department of ISE Acharya Institute of Technology


10/15/2015 Department of ISE Acharya Institute of Technology 30
Module-3

Strings

Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M

Department of ISE BMS Institute of Technology & Mgmt 5-1


Strings
• A string is a array of characters enclosed with in double
quotes terminated with a null character(\0).
W E L C O M E \0
• The operations that are performed on character strings
are
 Reading and writing strings.
 Combining strings together.
 Copying one string to another.
 Comparing strings for equality.
 Extracting a portion of a string.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Declaration of Strings
Syntax
char<var name>[array_length];
Eg:
char msg[6];
char str1[10],str2[10],…..;

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Initialization of Strings
Syntax
char str[size]=string constant;
char str[ ]=string constant;
Eg:
char msg[10]=“Hello”;
H E L L O \0 \0 \0 \0 \0

char msg [] = “ Hello”;


H E L L O \0

char msg[ ]={‘H’,’e’,’l’,’l’,’o’,’\0’};


H E L L O \0

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Reading and displaying strings

• Read a string scanf(), gets(), getchar()


• Display a string printf(), puts(), putchar()

i) Using scanf() and printf()


scanf(“%s”,&msg);  format specifier is %s
printf(“ Hello”);
printf(“%s”, msg);

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
read and display string using scanf and
printf
#include<stdio.h>
int main()
{
char name[20]; // declaration of string;
printf(“\nEnter your name:”);
scanf(“%s”, &name); // & is optional for string
printf(“\nwelcome %s !!!\n”, name);
return 0;
}
Output1: Output2:
Enter your name: BMSIT Enter your name: BMSIT BANGALORE
Welcome BMSIT !!!
Welcome BMSIT!!!
Department of ISE BMS Institute of Technology & Mgmt
Read and display string using gets
and puts function
#include<stdio.h> Output:
#define size 20 Enter the name with
int main() space: dennis ritchie
{ You are : dennis ritchie
char name[20];
printf(“Enter the name with space:”);
gets(name);
printf(“\nyou are:”);
puts(name);
return 0;
}

Department of ISE BMS Institute of Technology & Mgmt


Difference between scanf()
and gets()
scanf() gets()
1. Reads input till space, it omits 1. Reads input including space till
characters after blank space. enter key is pressed
2.Syntax 2.Syntax
scanf(“format specifier”, str_var); gets(str_var);
3. eg: 3. eg:
char str[10]; char str[10];
scanf(“%s”, str); gets(str);

Department of ISE BMS Institute of Technology & Mgmt


Read and display strings using
getchar() and putchar()
#include<stdio.h> printf("you are:");
#define size 20 for(i=0;name[i]!='\0';i++)
int main() putchar(name[i]);
{ return 0;
char name[20]; }
int i=0;
printf("enter the name :");
while((name[i]=getchar())!='\n') Output:
{ enter the name: BMSIT
i++;
}
You are: BMSIT
name[i]='\0';

Department of ISE BMS Institute of Technology & Mgmt


Creating array of strings
#include<stdio.h>
#include<conio.h>
int main()
{
char days[7][10]={"Sunday","Monday",”Wednesday","Thursday","Friday","Saturday"};
for(i=0;i<7;i++)
{
printf("%s \t",days[i]);
}
getch();
return0;
}

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
String Manipulation functions
#include<string.h>
String manipulation functions:
Function Work of Function

strlen() Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings

strcmp() Compares two string

strlwr() Converts string to lowercase

strupr() Converts string to uppercase

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Strlen()
Syntax:
temp_variable = strlen(string_name);
Eg:
#include<stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
int length;
length=strlen(a);
printf("Length of string a=%d \n",length); //calculates the length of string before null
charcter.
return 0;
}
Output:
Length of string a=7
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Calculate the length of the string
without using string functions
#include <stdio.h>
int main()
{
char s[20];
int i;
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);
return 0;
}
Output:
Enter a string: welcome
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Length of string:7
strcmp function
Syntax:
temp_varaible=strcmp(string1,string2);
• It compares the two strings and returns an
integer value.
• If both the strings are same (equal) then this
function would return 0
• otherwise it may return a negative or positive
value based on the comparison.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Eg for strcmp
#include <stdio.h> Output1
#include <string.h> Enter first string: Apple
int main() Enter second string: Apple
{ Both strings are equal.
char str1[30],str2[30]; Output2
printf("Enter first string: ");
Enter first string: Apple
gets(str1); Enter second string: cat
printf("Enter second string: "); strings are unequal.
gets(str2);
if(strcmp(str1,str2)==0)
printf("Both strings are equal");
else
printf("Strings are unequal");
return 0;
} Department of ISE BMS Institute of Technology & Mgmt
Compare two string without strcmp()
#include<stdio.h>
int main() { Output1:
char str1[30], str2[30]; Enter two strings:
int i;
printf("\nEnter two strings :");
apple
gets(str1); apple
gets(str2); str1=str2
i = 0;
while (str1[i] == str2[i] && str1[i] != '\0') Output2:
i++; Enter two strings:
if (str1[i] > str2[i])
printf("str1 > str2"); apple
else if (str1[i] < str2[i]) cat
printf("str1 < str2");
else str1<str2
printf("str1 = str2");
return (0);
} Department of ISE BMS Institute of Technology & Mgmt
strcat
• strcat() concatenates(joins) two strings.
• It takes two arguments, i.e, two strings
and resultant string is stored in the first
string specified in the argument.
Syntax
• strcat(first_string,second_string);

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pgm for strcat
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
Output string after concatenation: HelloWorld
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pgm to concatenate two strings
without strcat
#include <stdio.h>
int main() Output:
{ Enter first string: hello
char s1[10], s2[10], i, j; Enter second string: world
printf("Enter first string: "); The concatenated string is: helloworld
scanf("%s",s1);
printf("Enter second string: ");
scanf("%s",s2);
for(i=0; s1[i]!='\0'; ++i); /* i contains length of string s1. */
for(j=0; s2[j]!='\0'; ++j, ++i)
{ s1[i]=s2[j]; }
s1[i]='\0';
printf("After concatenation: %s",s1);
return 0;
} Department of ISE BMS Institute of Technology & Mgmt
Strcpy()
• Function strcpy() copies the content of one
string to the content of another string.
• It takes two arguments.
Syntax
• strcpy(destination,source);

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pgm for strcpy
#include <stdio.h>
#include <string.h>
int main()
{
char a[10],b[10];
printf("Enter string: ");
gets(a);
strcpy(b,a); //Content of string a is copied to string b.
printf("Copied string: ");
puts(b);
return 0;
}
Output:
Enter string: hai
Copied String: hai
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pgm to copy one string to another
without strcpy
#include <stdio.h>
Output:
int main()
{ Enter String s1: hello
char s1[10], s2[10], i; String s2: hello
printf("Enter string s1: ");
scanf("%s",s1);
for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='\0';
printf("String s2: %s",s2);
return 0;
} Department of ISE BMS Institute of Technology & Mgmt
Bubble sort
#include<stdio.h> {
#include<conio.h> if(a[j]>a[j+1])
void main() {
{ temp=a[j];
int n,i,j,a[10],temp; a[j]=a[j+1];
clrscr(); a[j+1]=temp;
printf("Enter the No. of Elements:\n"); }
scanf(“%d”,&n); }
printf(“ Enter the array Elements:\n”); }
for(i=0;i<n;i++) printf(“\nThe sorted elements are:\n");
{ for(i=0;i<n;i++)
printf("\t"); {
scanf("%d",&a[i]); printf("\t");
} printf("%d",a[i]);
for(i=0;i<n-1;i++) }
{ getch();
for(j=0;j<n-1+i;j++) }
Department of ISE BMS Institute of Technology & Mgmt
Department of ISE BMS Institute of Technology & Mgmt
Module-3
Linear search, Binary Search
Bubble sort and Selection sort

Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M

Department of ISE BMS Institute of Technology & Mgmt 5-1


Linear Search
#include<stdio.h> for (c = 0; c < n; c++)
int main() {
{ if (array[c] == search)
int array[10], search, c, n; /* If required element is found */
printf("Enter number of elements in {
array\n"); printf("%d is present at location
scanf("%d", &n); %d.\n", search, c+1);
printf("Enter %d integer(s)\n", n); break;
}
for (c = 0; c < n; c++)
}
scanf("%d", &array[c]);
if (c == n)
printf("Enter a number to search\n"); printf("%d isn't present in the
scanf("%d", &search); array.\n", search);
return 0;
}

Department of ISE BMS Institute of Technology & Mgmt


Output
Enter the No. of Elements: 4
Enter the array Elements:
11 5 77 32
Enter the elements to serach-77
Element found at position 3

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt
Bubble sort
#include<stdio.h> {
#include<conio.h> if(a[j]>a[j+1])
void main() {
{ temp=a[j];
int n,i,j,a[10],temp; a[j]=a[j+1];
//clrscr(); a[j+1]=temp;
printf("Enter the No. of Elements:\n"); }
scanf(“%d”,&n); }
printf(“ Enter the array Elements:\n”); }
for(i=0;i<n;i++) printf(“\nThe sorted elements are:\n");
{ for(i=0;i<n;i++)
printf("\t"); {
scanf("%d",&a[i]); printf("\t");
} printf("%d",a[i]);
for(i=0;i<n-1;i++) }
{ getch();
for(j=0;j<n-i-1;j++) }
Department of ISE BMS Institute of Technology & Mgmt
Output
Enter the No. of Elements: 5
Enter the array Elements:
5 1 4 2 8
The sorted elements are
1 2 4 5 8

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt
Selection sort
#include <stdio.h> {
if (array[j]<array[min])
int main()
min = j;
{
}
int array[10], n, i, j, min, temp;
}
printf("Enter number of
elements\n"); t = array[i];
scanf("%d", &n); array[i] = array[min];
array[min] = t;
printf("Enter %d integers\n", n);
}
for (i = 0; i < n; i++) }
scanf("%d", &array[i]);
printf("Sorted list in ascending
for (i = 0; i < (n - 1); i++) // finding order:\n");
minimum element (n-1) times
for (i = 0; i< n; i++)
{
printf("%d\n", array[i]);
min = i;
return 0;
for (j = i + 1; j < n; j++)
}
Department of ISE •
BMS Institute of Technology & Mgmt
Output
Enter the No. of Elements: 5
Enter the array Elements:
5 7 4 8 1
The sorted elements are
1 4 5 7 8

Department
Departmentof
of ISE
ISE BMS Institute of Technology & Mgmt
Module-4
Functions
Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M

Department of ISE BMS Institute of Technology & Mgmt


Functions
• Function is a sub program or a self contained
block of statements used to perform a specific
task.
• Every C program contains at least one function
called main()
• Types of functions
– Built in functions functions provided by C compiler
eg: scanf(),printf(),sqrt(),sin()
– User defined functions functions defined by user eg:
main()

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 2
Advantages of user defined
functions
• Provides modularity and thus reduces
complexity of the program
• avoids repetition of code
• Easy to debug/test the program
• Reduces time and cost (functions created for
one pgm can be reused to another pgm with
little or no modification)

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 3
Function Definition
Syntax:
return_type function_name ( param list)
{
declarations;
executable_statments;
}
Int add(int a, int b)
Note:
• A function can return only one value
• If the function returns no value then the return_type
would be void.
• If the return_type is not specified by default type is
int
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 4
Function Definition- Contd

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Parameter list will take the following form
• type param1, type param2,….type param n
– Eg: int add(int a, int b)
• Data type to be specified for each
parameter
– int max(int a b,c) - wrong
– int max(int a, int b,int c) - correct

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 6
Examples-Program

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Location of Functions
// after the main // before the main
Include header files Include header files
Function prototype Function prototype
main() Function definition()
{ {
} }
Function definition() main()
{ {
} }
Department of ISE BMS Institute of Technology & Mgmt
Location of Functions
Pgm1.c Pgm2.c
Include header files Function definition()
Function prototype {
main() }
{
}

Department of ISE BMS Institute of Technology & Mgmt


Location of Functions-After the main

Department of ISE BMS Institute of Technology & Mgmt


Location of Functions-Before the main

Department of ISE BMS Institute of Technology & Mgmt


Actual and formal parameters
• Arguments/parameters appearing in function call is
called actual arguments/parameters
• Arguments/parameters appearing in function
definition is called formal arguments/parameters
• The number of actual and formal parameters must
be equal.
• Also the data types and the order of declaration of
formal and actual parameters must be the same.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 12
Actual and formal parameters

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
• Each function will have
– Function prototype
– Function call
– Function definition
– Int add( int a, int b)
• If function is defined after main, function prototype is
must .
• Function prototype tells the compiler which function is
used by the main what is its return type , number and
type of parameters.
• Name of parameters is optional in function prototype
• Function prototype should end with a semicolon

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 14
Program to Print a sentence using
function
#include<stdio.h>
void display(); //function declaration
void main()
{
display(); //function call
}
void display() //function definition
{
printf("C Programming");
return;
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
#include<stdio.h>
int add(int , int ); // function prototype
int main()
{
int a=5,b=10;
add(a, b); // function call
}
int add(int m, int n) // function definition
{
int m,n,y;
Y= m+ n;
return(y);
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 16
Simple program using functions
#include<stdio.h>
int add(int,int); // function prototype
int main()
{
int mark1=50,mark2=40,tot;
tot=add(mark1,mark2); // function call mark1,mark2 actual arguments
printf(“the total is %d\n”,tot);
return 0;
}
int add(int a,int b) // function defintion a,b formal parameters
{
int c;
c=a+b;
return (c); // returns the value of c to the variable tot
} Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 17
Note :
number of arguments, type of arguments, return
type in function prototype should match with
function defintion
int max( int a, int b); // fn prototype
main()
{…
max(x,y); // function call
}
int max( float a, float b, int c) // fn defn
{
} //This is wrong

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 18
Module-4
Functions
Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M

Department of ISE BMS Institute of Technology & Mgmt


Types of User-defined Functions in C
Programming
• Function with no arguments and no return value
• Function with no arguments and a return value
• Function with arguments and no return value
• Function with arguments and a return value.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Function with arguments and a return value.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Function with arguments and no return value

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Function with no arguments and a return value

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Function with no arguments and no return value

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Types of User-defined Functions in C
Programming-example-2
• Function with no arguments and no return value
• Function with no arguments and a return value
• Function with arguments and no return value
• Function with arguments and a return value.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
No arguments passed and no return Value

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
No arguments passed but a return value

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Argument passed but no return value

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Argument passed and a return value

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Module-4
Functions
Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M

Department of ISE BMS Institute of Technology & Mgmt


Argument Passing
Parameter passing mechanism
• Call by value
• Call by reference
Call by value:
When the value of the variable is passed during
function invocation is called call by value.
Call by reference:
When an address of the variable is passed during
function invocation is called call by reference.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 31
Call by value
main ( ) Output
{
int a = 10, b=20; x = 20 y = 10
swap(a,b); a =10 b =20
printf (“\na = % d b = % d”, a,b);
} Note:
swap(int x, int y) With this method the changes
{ made to the formal arguments
int t; in the called function have no
t = x; effect on the values of actual
x = y; argument in the calling
y = t; function
printf ( “\n x = % d y = % d” , x, y);
}
Department of ISE BMS Institute of Technology & Mgmt 32
CALL BY REFERENCE
• The addresses of actual arguments in the calling
function are copied into formal arguments of the
called function.
• This means that using these addresses we would
have an access to the actual arguments and
hence we would be able to manipulate them.
• Change in formal arguments affect the actual
arguments

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 33
Call by reference
main ( ) output
{ x=20 y=10
int a = 10, b =20; a = 20 b =10
swap (&a, &b);
printf (“\n a = %d b= %d”, a, b);
}
swap (int *x, int * y)
{
int t;
t = *x
*x = *y;
*y = t;
printf(“\n x=%d y=%d”,*x,*y);
}
Department of ISE BMS Institute of Technology & Mgmt 34
Passing entire array as
#include <stdio.h> arguments
float average(float a[]); // fn prototype
int main(){
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument in fn call. */
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[]) // array var should be used as arg to receive the elements
{
int i;
float avg, sum=0.0;
for(i=0;i<6;++i){
sum+=a[i];
}
avg =(sum/6);
return avg;
} Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 35
Passing arrays using Call by
#include <stdio.h>
value
disp( char ch) // display function definition
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'j'};
for (int x=0; x<=10; x++)
{
/* passing each element one by one using subscript*/
disp (arr[x]); // fn call
}

return 0;
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt 36
Passing array using call by
reference
#include <stdio.h>
disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<=10; i++)
{ /* passing element’s address*/
disp (&arr[i]);
}
return 0;
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Sorting of elements using functions
#include<stdio.h>
int main()
void bubble_sort(int a[],int n)
{
{
int a[10],i,n;
int i,j,temp;
printf("enter num of elements\n");
for(i=0;i<n-1;i++)
scanf("%d",&n);
{
printf("enter the elements of array\n");
for(j=0;j<n-(i+1);j++)
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(a[j]>a[j+1])
bubble_sort(a,n);
{
printf("the sorted array is \n");
temp=a[j];
for(i=0;i<n;i++)
a[j]=a[j+1];
printf("%d\n",a[i]);
a[j+1]=temp;
return 0;
}
}
}
}
}
Department of ISE BMS Institute of Technology & Mgmt
Passing Multidimensional array to functions

#include <stdio.h> void Function(int c[2][2])


void Function(int c[2][2]); // prototype {
int main( ) /* Instead to above line, void
{ Function(int c[][2]){ is also valid */
int c[2][2],i,j; int i,j;
printf("Enter 4 numbers:\n"); printf("Displaying:\n");
for(i=0;i<2;++i) for(i=0;i<2;++i)
for(j=0;j<2;++j){ for(j=0;j<2;++j)
scanf("%d",&c[i][j]); printf("%d\n",c[i][j]);
} }
Function(c); // 2d array passed
return 0;
}
Department of ISE BMS Institute of Technology & Mgmt 39
Module-4
Recursive Functions
Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M

Department of ISE BMS Institute of Technology & Mgmt


Recursion
• Recursive function is a function that calls itself from its
own body.
• The function keeps on calling itself till a particular
condition holds true.
• add(N+add(n-1))
Properties of Recursion
• There is a criteria or condition that governs the execution
of recursive function. Without this condition, it will work
in an endless manner. This condition is also called the
base case of recursion.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pgm to calculate factorial using
recursion

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pgm to calculate factorial using
recursion
#include<stdio.h>
int factorial (int ); //function prototyping
int main()
{ int num,result;
printf("\nEnter a number : ");
scanf("%d",&num);
result= factorial(num); // fn call
printf("\nFactorial of %d is %d",num,result);
return 0;
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Continue..
int factorial(int value)
{
int ans;
if( (value==0) || (value==1) )
return(1);
else
ans = value* factorial(value-1);
//call to itself
return(ans);
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Program for Sum of N number
With Recursive call

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Fibonacci series using
Recursion
#include<stdio.h> int fibbo(int x)
int fibbo(int x); { if(x==1 || x==0)
void main() return 1;
{ else
int n,i; {
printf("Enter the number of return(fibbo(x-1)+ fibbo(x-2));
terms in series\n"); }
scanf("%d",&n); }
printf("Fibonacci series:\n");
for(i=1;i<=n;i++)
printf("%ld\t",fibbo(i));
} Department of ISE BMS Institute of Technology & Mgmt
Void and parameter less functions
/*C program to check whether a number entered by user is
prime or not using function with no arguments and no return
value*/
#include <stdio.h>
void prime(); // fn prototype no parameter no return
int main()
{
prime(); //No argument is passed to prime()
return 0;
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
void prime()
{ /* There is no return value to calling function main(). Hence,
return type of prime() is void */
int num,i,flag=0;
printf("Enter positive integer enter to check: \n");
scanf("%d",&num);
for(i=2;i<=num/2;++i)
{
if(num%i==0)
{
flag=1;
}
}
if (flag==1)
printf("%d is not prime",num); else printf("%d is prime",num); }
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Lab Program-12
Square Root of Given Number
Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M

Department of ISE BMS Institute of Technology & Mgmt


Lab Program-12
• Develop a program to find the square root of
a given number N and execute for all possible
inputs with appropriate messages.
• Note: Don’t use library function sqrt(n).

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Lab Program-15
Binary to Decimal Conversion
Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M

Department of ISE BMS Institute of Technology & Mgmt


•Purpose: This program demonstrates RECURSION.
•Procedure: Input binary number and call the recursive
function convert for translating binary number to
decimal number.
•Input: A binary number bin.
•Expected Output: Decimal number

Department of ISE BMS Institute of Technology & Mgmt


Implement Recursive functions for
Binary to Decimal Conversion
#include <stdio.h>
int convert(int);
int main()
{
int dec, bin;
printf("Enter a binary number: ");
scanf("%d", &bin);
dec = convert(bin);
printf("The decimal equivalent of %d is %d.\n", bin,dec);
return 0;
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Implement Recursive functions for Binary
to Decimal Conversion
int convert(int bin)
{
if (bin == 0)
{
return 0;
}
else
{
return (bin % 10 + 2 * convert(bin / 10));
}
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Lab Program-9
Compute Sin(x) using Taylor series
approximation
Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M

Department of ISE BMS Institute of Technology & Mgmt


Evaluating Sin(x) values without
build in function and comparing
result with build in function
• Develop a Program to compute Sin(x) using
Taylor series approximation .Compare your
result with the built- in Library function. Print
both the results with appropriate messages

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Program
/* Program to calculate sine value of given angle */
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define PI 3.142
int main()
{
int i, degree;
float x, sum=0,term,nume,deno;
clrscr();
printf("Enter the value of degree");
scanf("%d",&degree);
x = degree * (PI/180); //converting degree into radian
nume = x;
deno = 1;
i=2;

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Program
do
{
//calculating the sine value.
term = nume/deno;
nume = -nume*x*x;
deno = deno*i*(i+1);
sum=sum+term;
i=i+2;
} while (fabs(term) >= 0.00001); // Accurate to 4 digits
printf("The sine of %d is %.3f\n", degree, sum);
printf("The sine function of %d is %.3f", degree, sin(x));
return 0;
}

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Program

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Program

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Program

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Program

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Program

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Program

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Module-5
C Pointers
Prof. Swetha M S
ISE-BMSIT&M

Department of ISE BMS Institute of Technology & Mgmt


OBJECTIVES
• Pointer variable definitions and initialization
• Pointer operators
• Passing arguments to functions by reference
• Pointer expressions and pointer arithmetic
• Relationships between pointers and arrays
• Array of pointers
• Character pointer and functions
• Pointer to pointer

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointer Variable Definitions and
Initialization
• Contain memory addresses as their values
• Normal variables contain a specific value (direct reference)
Defn
• A pointer is a variable which contains the address of a variable that has a
specific value (indirect reference)

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointer Variable Definitions and
Initialization
• Pointer definitions
– * used with pointer variables
int *myPtr;
– Defines a pointer to an int (pointer of type int *)
– Multiple pointers require using a * before each variable
definition
int *myPtr1, *myPtr2;
– Can define pointers to any data type
– Initialize pointers to 0, NULL, or an address
• 0 or NULL – points to nothing
• 0 is the only integer value that can be assigned directly to a
pointer variable.
• Initializing a pointer to 0 is equivalent to initializing a pointer to
NULL, but NULL is preferred
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointer Operators
• & (address operator)
– Returns address of operand
int y = 5;
int *yPtr;
yPtr = &y; /* yPtr gets address of y */
yPtr “points to” y

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointer Operators
• * (indirection/dereferencing operator)
– Returns a synonym/alias of what its operand
points to
– *yptr returns y (because yptr points to y)
– * can be used for assignment
• Returns alias to an object
*yptr = 7; /* changes y to 7 */

– Dereferenced pointer (operand of *) must be an


lvalue (no constants)
• * and & are inverses
– They cancel eachofother
Department
Departmentof ISE
ISE
out
BMS Institute of Technology & Mgmt
1
2 /*Using the & and * operators */
3 #include <stdio.h>
4
5 int main( void )
6 {
7 int a; /* a is an integer */
 fig07_04.c
8
9
int *aPtr; /* aPtr is a pointer to an integer */
(1 of 2 )
10 a = 7;
11 aPtr = &a; /* aPtr set to address of a */
12
13 printf( "The address of a is %p"
14 "\nThe value of aPtr is %p", &a, aPtr );
If aPtr points to a, then &a and
15 aPtr have the same value.
16 printf( "\n\nThe value of a is %d"
17 "\nThe value of *aPtr is %d", a, *aPtr ); a and *aPtr have the same value
18
19 printf( "\n\nShowing that * and & are complements of "
20 "each other\n&*aPtr = %p"
21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr ); &*aPtr and *&aPtr have the same value
22
23 return 0; /* indicates successful termination */
24
25 } /* end main */

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
The address of a is 0012FF7C
The value of aPtr is 0012FF7C

The value of a is 7
The value of *aPtr is 7

Showing that * and & are complements of each other.


&*aPtr = 0012FF7C
*&aPtr = 0012FF7C

 fig07_04.c
(2 of 2 )
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Calling Functions by Reference
• Call by reference with pointer arguments
– Pass address of argument using & operator
– Allows you to change actual location in memory
– Arrays are not passed with & because the array name is
already a pointer
• * operator
– Used as alias/nickname for variable inside of function
void double( int *number )
{
*number = 2 * ( *number );
}

– *number used as nickname for the variable passed

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
/*Cube a variable using call-by-value */
#include <stdio.h>
int cubeByValue( int n ); /* prototype */
int main( void )
{
int number = 5;
printf( "The original value of number is %d", number );
/* pass number by value to cubeByValue */
number = cubeByValue( number );
printf( "\nThe new value of number is %d\n", number );
return 0;
}
int cubeByValue( int n )
{
return n * n * n;
}

The original value of number is 5


The new value of number is 125

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Call-by-reference with a pointer
argument Function prototype takes a pointer argument
#include <stdio.h>
void cubeByReference( int *nPtr ); /* prototype */
int main( void ) Function cubeByReference is
{ passed an address, which can be
int number = 5; the value of a pointer variable
printf( "The original value of number is %d", number );
/* pass address of number to cubeByReference */
cubeByReference( &number );
printf( "\nThe new value of number is %d\n", number );
return 0; In this program, *nPtr is
} number, so this statement
void cubeByReference( int *nPtr ) modifies the value of
number itself.
{
*nPtr = *nPtr *x*nPtr x *nPtr; /* cube *nPtr */
}

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Analysis of A Typical Call-by-Value

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Analysis of A Typical Call-by-Reference

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Bubble Sort Using Call-by-
reference
• Implement bubblesort using pointers
– Swap two elements
– swap function must receive address (using &) of
array elements
• Array elements have call-by-value default
– Using pointers and the * operator, swap can switch
array elements
• Psuedocode
Initialize array
print data in original order
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Bubble Sort Using Call-by-
reference
• Psuedocode
Initialize array
print data in original order
Call function bubblesort
print sorted array
Define bubblesort

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
1 /* Fig. 7.15: fig07_15.c
2 This program puts values into an array, sorts the values into
3 ascending order, and prints the resulting array. */
4 #include <stdio.h>
5 #define SIZE 10
6
7 void bubbleSort( int * const array, const int size ); /* prototype */  fig07_15.c
8
9 int main( void ) (1 of 3 )
10 {
11 /* initialize array a */
12 int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
13
14 int i; /* counter */
15
16 printf( "Data items in original order\n" );
17
18 /* loop through array a */
19 for ( i = 0; i < SIZE; i++ ) {
20 printf( "%4d", a[ i ] );
21 } /* end for */
22
23 bubbleSort( a, SIZE ); /* sort the array */
24
25 printf( "\nData items in ascending order\n" );
26
27 /* loop through array a */
28 for ( i = 0; i < SIZE; i++ ) {
29 printf( "%4d", a[ i ] );
30 } /* end for */ Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
31
32 printf( "\n" );
33
34 return 0; /* indicates successful termination */
35
36 } /* end main */
37
38 /* sort an array of integers using bubble sort algorithm */
39 void bubbleSort( int * const array, const int size )
40 {
41 void swap( int *element1Ptr, int *element2Ptr ); /* prototype */
42 int pass; /* pass counter */
43 int j; /* comparison counter */
44
45 /* loop to control passes */
46 for ( pass = 0; pass < size - 1; pass++ ) {
47
48 /* loop to control comparisons during each pass */
49 for ( j = 0; j < size - 1; j++ ) {
50
51 /* swap adjacent elements if they are out of order */
52 if ( array[ j ] > array[ j + 1 ] ) {
53 swap( &array[ j ], &array[ j + 1 ] );
54 } /* end if */
55
56 } /* end inner for */
57
58 } /* end outer for */  fig07_15.c
59
60 } /* end function bubbleSort */ (2 of 3 )
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointer Expressions and Pointer
Arithmetic
• Arithmetic operations can be performed on
pointers
– Increment/decrement pointer (++ or --)
– Add an integer to a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
– Operations meaningless unless performed on an
array

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointer Expressions and Pointer Arithmetic
• 5 element int array on machine with 4 byte
ints
– vPtr points to first element v[ 0 ]
• at location 3000 (vPtr = 3000)
– vPtr += 2; sets vPtr to 3008
• vPtr points to v[ 2 ] (incremented by 2), but the
machine has 4 byte ints, so it points to address 3008

| Array v and a pointer variable vPtr that points to v.


Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
The pointer vPtr after pointer
arithmetic

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointer Expressions and Pointer
Arithmetic
• Subtracting pointers
– Returns number of elements from one to the
other. If
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
– vPtr2 - vPtr would produce 2

• Pointer comparison ( <, == , > )


– See which pointer points to the higher numbered
array element
– Also, see if a pointer points to 0
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointer Expressions and Pointer
Arithmetic
• Pointers of the same type can be assigned to
each other
– If not the same type, a cast operator must be used
– Exception: pointer to void (type void *)
• Generic pointer, represents any type
• No casting needed to convert a pointer to void pointer
• void pointers cannot be dereferenced

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
OBJECTIVES
• Pointer variable definitions and initialization
• Pointer operators
• Passing arguments to functions by reference
• Using const qualifier with pointers
• Bubble sort using call-by-reference
• Sizeof operator
• Pointer expressions and pointer arithmetic
• Relationships between pointers and arrays
• Array of pointers
• Case study: Card shuffling and dealing simulation
• To use pointers to functions
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
The Relationship Between Pointers
and Arrays
• Arrays and pointers closely related
– Array name like a constant pointer
– Pointers can do array subscripting operations
• Define an array b[ 5 ] and a pointer bPtr
– To set them equal to one another use:
bPtr = b;
• The array name (b) is actually the address of first
element of the array b[ 5 ]
bPtr = &b[ 0 ]
• Explicitly assigns bPtr to address of first element of b
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
The Relationship Between Pointers
and Arrays
– Element b[ 3 ]
• Can be accessed by *( bPtr + 3 )
– Where n is the offset. Called pointer/offset notation
• Can be accessed by bptr[ 3 ]
– Called pointer/subscript notation
– bPtr[ 3 ] same as b[ 3 ]
• Can be accessed by performing pointer arithmetic on
the array itself
*( b + 3 )

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
1 /* Fig. 7.20: fig07_20.cpp
2 Using subscripting and pointer notations with arrays */
3
4 #include <stdio.h>
5
6 int main( void )
7 {  fig07_20.c
8 int b[] = { 10, 20, 30, 40 }; /* initialize array b */
9 int *bPtr = b; /* set bPtr to point to array b */ (1 of 3 )
10 int i; /* counter */
11 int offset; /* counter */
12
13 /* output array b using array subscript notation */
14 printf( "Array b printed with:\nArray subscript notation\n" );
15
16 /* loop through array b */
Array subscript notation
17 for ( i = 0; i < 4; i++ ) {
18 printf( "b[ %d ] = %d\n", i, b[ i ] );
19 } /* end for */
20
21 /* output array b using array name and pointer/offset notation */
22 printf( "\nPointer/offset notation where\n"
23 "the pointer is the array name\n" );
24 Pointer/offset notation
25 /* loop through array b */
26 for ( offset = 0; offset < 4; offset++ ) {
27 printf( "*( b + %d ) = %d\n", offset, *( b + offset ) );
28 } /* end for */
29

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
30 /* output array b using bPtr and array subscript notation */
31 printf( "\nPointer subscript notation\n" );
32
33 /* loop through array b */
Pointer subscript notation
34 for ( i = 0; i < 4; i++ ) {
35 printf( "bPtr[ %d ] = %d\n", i, bPtr[ i ] );
36 } /* end for */
37
38 /* output array b using bPtr and pointer/offset notation */
39 printf( "\nPointer/offset notation\n" );
40 Pointer offset notation
41 /* loop through array b */
42 for ( offset = 0; offset < 4; offset++ ) {
43 printf( "*( bPtr + %d ) = %d\n", offset, *( bPtr + offset ) );
44 } /* end for */
45
46 return 0; /* indicates successful termination */
47
48 } /* end main */

Array b printed with:


Array subscript notation
 fig07_20.c
b[ 0 ] = 10
b[ 1 ] = 20
(2 of 3 )
b[ 2 ] = 30
b[ 3 ] = 40
(continued on next slide… )

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
(continued from previous slide…)
Pointer/offset notation where
the pointer is the array name
*( b + 0 ) = 10
*( b + 1 ) = 20
*( b + 2 ) = 30
*( b + 3 ) = 40

Pointer subscript notation


bPtr[ 0 ] = 10
bPtr[ 1 ] = 20
bPtr[ 2 ] = 30
bPtr[ 3 ] = 40

Pointer/offset notation
*( bPtr + 0 ) = 10
*( bPtr + 1 ) = 20
*( bPtr + 2 ) = 30
*( bPtr + 3 ) = 40

 fig07_20.c
(3 of 3 )
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
1 /* Fig. 7.21: fig07_21.c
2 Copying a string using array notation and pointer notation. */
3 #include <stdio.h>
4
5 void copy1( char * const s1, const char * const s2 ); /* prototype */
6 void copy2( char *s1, const char *s2 ); /* prototype */
7
8 int main( void )
9 {
10 char string1[ 10 ]; /* create array string1 */
11 char *string2 = "Hello"; /* create a pointer to a string */
12 char string3[ 10 ]; /* create array string3 */
13 char string4[] = "Good Bye"; /* create a pointer to a string */
14
15 copy1( string1, string2 );
16 printf( "string1 = %s\n", string1 );
17
18 copy2( string3, string4 );
19 printf( "string3 = %s\n", string3 );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */
24

 fig07_21.c
(1 of 2 )
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
25 /* copy s2 to s1 using array notation */
26 void copy1( char * const s1, const char * const s2 )
27 {
28 int i; /* counter */
29
30 /* loop through strings */
31 for ( i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ ) {
32 ; /* do nothing in body */
33 } /* end for */
34
35 } /* end function copy1 */
36
37 /* copy s2 to s1 using pointer notation */
38 void copy2( char *s1, const char *s2 ) Condition of for loop
39 { actually performs an action
40 /* loop through strings */
41 for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ ) {
42 ; /* do nothing in body */
43 } /* end for */
44
45 } /* end function copy2 */

string1 = Hello
string3 = Good Bye

 fig07_21.c
(2 of 2 )
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Arrays of Pointers
• Arrays can contain pointers
• For example: an array of strings
char *suit[ 4 ] = { "Hearts", "Diamonds",
"Clubs", "Spades" };
– Strings are pointers to the first character
– char * – each element of suit is a pointer to a
char
– The strings are not actually stored in the array
suit, only pointers to the strings are stored

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointers to Functions
• Pointer to function
– Contains address of function
– Similar to how array name is address of first
element
– Function name is starting address of code that
defines function
• Function pointers can be
– Passed to functions
– Stored in arrays
– Assigned to other function pointers
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Pointers to Functions
• Example: bubblesort
– Function bubble takes a function pointer
• bubble calls this helper function
• this determines ascending or descending sorting
– The argument in bubble for the function pointer:
int ( *compare )( int a, int b )
tells bubble to expect a pointer to a function that takes
two ints and returns an int
– If the parentheses were left out:
int *compare( int a, int b )
• DefinesDepartment
a function
Departmentof
ofISE
ISE
that receives two integers and
BMS Institute of Technology & Mgmt
returns a pointer to a int
1 /* Fig. 7.26: fig07_26.c
2 Multipurpose sorting program using function pointers */
3
4
5
#include <stdio.h>
#define SIZE 10 Pointers to Functions
6 /* prototypes */
7 void bubble( int work[], const int size, int (*compare)( int a, int b ) );  fig07_26.c
8 int ascending( int a, int b );
9 int descending( int a, int b ); (1 of 4 )
10 bubble function takes a function
11 int main( void )
pointer as an argument
12 {
13 int order; /* 1 for ascending order or 2 for descending order */
14 int counter; /* counter */
15
16 /* initialize array a */
17 int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
18
19 printf( "Enter 1 to sort in ascending order,\n"
20 "Enter 2 to sort in descending order: " );
21 scanf( "%d", &order );
22
23 printf( "\nData items in original order\n" );
24
25 /* output original array */
26 for ( counter = 0; counter < SIZE; counter++ ) {
27 printf( "%5d", a[ counter ] );
28 } /* end for */
29

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
30 /* sort array in ascending order; pass function ascending as an
31 argument to specify ascending sorting order */
32 if ( order == 1 ) {
33 bubble( a, SIZE, ascending );
34 printf( "\nData items in ascending order\n" );
35 } /* end if */
36 else { /* pass function descending */
37 bubble( a, SIZE, descending );
38 printf( "\nData items in descending order\n" );
39 } /* end else */
depending on the user’s choice, the bubble
40
41 /* output sorted array */
function uses either the ascending or
42 for ( counter = 0; counter < SIZE; counter++ ) { descending function to sort the array
43 printf( "%5d", a[ counter ] );
44 } /* end for */
45
46 printf( "\n" );
47
48 return 0; /* indicates successful termination */
49
50 } /* end main */
51

 fig07_26.c
(2 of 4 )
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
52 /* multipurpose bubble sort; parameter compare is a pointer to
53 the comparison function that determines sorting order */
54 void bubble( int work[], const int size, int (*compare)( int a, int b ) )
55 {
56 int pass; /* pass counter */
57 int count; /* comparison counter */
58  fig07_26.c
59 void swap( int *element1Ptr, int *element2ptr ); /* prototype */
60 (3 of 4 )
61 /* loop to control passes */
62 for ( pass = 1; pass < size; pass++ ) {
63
64 /* loop to control number of comparisons per pass */
65 for ( count = 0; count < size - 1; count++ ) {
66
67 /* if adjacent elements are out of order, swap them */
68 if ( (*compare)( work[ count ], work[ count + 1 ] ) ) {
69 swap( &work[ count ], &work[ count + 1 ] );
70 } /* end if */
71
72 } /* end for */ Note that what the program considers
73 “out of order” is dependent on the
74 } /* end for */ function pointer that was passed to
75 the bubble function
76 } /* end function bubble */
77

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
78 /* swap values at memory locations to which element1Ptr and
79 element2Ptr point */
80 void swap( int *element1Ptr, int *element2Ptr )
81 {
82 int hold; /* temporary holding variable */
83
84 hold = *element1Ptr;  fig07_26.c
85 *element1Ptr = *element2Ptr;
86 *element2Ptr = hold; (4 of 4 )
87 } /* end function swap */
88
89 /* determine whether elements are out of order for an ascending
90 order sort */
91 int ascending( int a, int b ) Passing the bubble function ascending
92 { will point the program here
93 return b < a; /* swap if b is less than a */
94
95 } /* end function ascending */
96
97 /* determine whether elements are out of order for a descending
98 order sort */
99 int descending( int a, int b )
Passing the bubble function descending
100 {
101 return b > a; /* swap if b is greater than a */ will point the program here
102
103 } /* end function descending */

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Enter 1 to sort in ascending order,
Enter 2 to sort in descending order: 1

Data items in original order


2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89

Enter 1 to sort in ascending order,


Enter 2 to sort in descending order: 2

Data items in original order


2 6 4 8 10 12 89 68 45 37
Data items in descending order
89 68 45 37 12 10 8 6 4 2

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Module-5
Structures in C

Prof. Swetha M S
Structures
Defn:
• Is a user defined data type used to store values of different data types
under a common name .
• Collection of data of same or different data type
Eg:
• Library info: (Acc no, title, author, pub, price..)
• Student info: (rno, name, DOB, addr, marks..)

Department of ISE BMS Institute of Technology and Mgmt


Declaring Structures
struct tag
{
//member declarations;
data_type member_var1;
data_type member _var2;
….
};
Eg:
struct person
{
char name[10];
int age;
};
Department of ISE BMS Institute of Technology and Mgmt
Defining structure variable
Note:
• Declaration of structure only list its members, it does not allocate any
memory for member variables.
• Memory is allocated only when member variables were defined.
Syntax 1:
struct tag var_list;
Eg:
struct person p1,p2;

Department of ISE BMS Institute of Technology and Mgmt


Syntax 2:
struct tag
{
member declarations;
} var_list;

Eg:
struct person
{
char name[10];
int age;
} p1,p2;

Department of ISE BMS Institute of Technology and Mgmt


Note:
It is possible to omit structure name while declaration. Such structures
are called anonymous structures.
Eg:
struct
{
char name[10];
int age;
} p1,p2;

Department of ISE BMS Institute of Technology and Mgmt


Initializing structure variables
• Each structure variable contains a copy of all members of the structure.
1. struct person p1={“ bala”, 24};

Department of ISE BMS Institute of Technology and Mgmt


Accessing structure members
• We can access structure members using dot operator(.)
Syntax
struct_var . member name
2. Second approach of initializing structure variables
struct person p1;
strcpy(p1.name,”bala”);
P1.age=24;

Department of ISE BMS Institute of Technology and Mgmt


Eg pgm
#include<stdio.h> printf(“\n student details\n”);
main() printf(“Rollno: %d”,s1.rno);
{
struct student printf(“Name: %s”, s1.name);
{ printf(“Age: %d”, s1.age);
int rno; printf(“Grade: %c ”, s1.grade);
char name[10];
int age; return 0;
char grade; }
} s1; OUTPUT:
s1.rno=101;
strcpy(s1.name,”james”); student details
s1.age=24; Rollno: 101
s1.grade=‘A’;
Name: james
Age: 24
Grade:A
Eg pgm
#include<stdio.h> printf(“\n student details\n”);
main() printf(“Rollno: %d”,s1.rno);
{
struct student printf(“Name: %s”, s1.name);
{ printf(“Age: %d”, s1.age);
int rno; printf(“Grade: %c ”, s1.grade);
char name[10];
int age; return 0;
char grade; }
} s1; OUTPUT:
printf(“Enter Roll No:\n”);
scanf(“%d”, &s1.rno); student details
printf(“Enter Name :\n”); Rollno: 101
gets( s1.name);
Name: james
printf(“Enter Age:\n”);
scanf(“%d”, &s1.age); Age: 24
printf(“Enter Grade:\n”); Grade: A
scanf(“%c”, s1.grade);
Nested Structures
• A structure inside another structure is called nested structure.
2 ways
1. The complete definition of a structure is placed inside the definition
of another structure.
2. Structures are defined separately and variable of structure type is
declared inside another structure.

Department of ISE BMS Institute of Technology and Mgmt


Nested Structures
Ist Approach 2nd Approach
struct student struct date
{ {
int rno; int day,month,year;
char name[20]; };
struct date struct student
{ {
int day, month, year; int rno;
} dob; char name[20];
} stud1; struct date dob;
} stud1;
Accessing nested structure
• If a structure A has another Structure B nested inside it
struct A
{
struct B
{
}b;
}a;
Then b data members can be accessed by a.b.data member

Department of ISE BMS Institute of Technology and Mgmt


Eg
#include<stdio.h> void main()
struct Address {
{ char HouseNo[25];
int i;
char City[25];
char PinCode[25]; struct Employee E;
}; printf("\n\tEnter Employee Id : ");
struct Employee scanf("%d", &E.Id);
{ int Id;
char Name[25]; printf("\n\tEnter Employee Name : ");
float Salary; scanf("%s", &E.Name);
struct Address Add; printf("\n\tEnter Employee Salary : ");
}; scanf("%f", &E.Salary);
printf("\n\tEnter Employee House No : ");
scanf("%s",&E.Add.HouseNo);
printf("\n\tEnter Employee City : ");
scanf("%s",&E.Add.City);
printf("\n\tEnter Employee House No : ");
scanf("%s",&E.Add.PinCode);
printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployee House No : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployee House No : %s",E.Add.PinCode);
}
Department of ISE BMS Institute of Technology and Mgmt
OUTPUT
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Salary : 45000
Enter Employee House No : 4598/D
Enter Employee City : Delhi
Enter Employee Pin Code : 110056
Details of Employees
Employee Id : 101
Employee Name : Suresh
Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi
Employee Pin Code : 110056

Department of ISE BMS Institute of Technology and Mgmt


Arrays of Structure
• Arrays of structure type is required when you need to apply the same
structure to a set of objects.
Syntax
struct student
{
int rno;
char name[20];
} stud[3]; // arrays of structure

Department of ISE BMS Institute of Technology and Mgmt


#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
struct student s[10]; // Array of structure
int i;
printf("Enter information of students:\n");
for(i=0;i<10;++i)
{
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
Department of ISE BMS Institute of Technology and Mgmt
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<10;++i)
{
printf("\nInformation for roll number %d:\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
}
return 0;
}
Department of ISE BMS Institute of Technology and Mgmt
OUTPUT for Arrays of structure
Enter information of students:
For roll number 1
Enter name: Tom
Enter marks: 98

For roll number 2


Enter name: Jerry
Enter marks: 89
.
.
Displaying information of students:
Information for roll number 1:
Name: Tom
Marks: 98 . . .

Department of ISE BMS Institute of Technology and Mgmt


Structures and functions
In C, structure can be passed to functions by two methods:
• Pass by value (passing actual value as argument)
• Pass by reference (passing address of an argument)
Passing structure by value
A structure variable can be passed to the function as an
argument as normal variable.
If structure is passed by value, change made in structure variable
in function definition does not reflect in original structure
variable in calling function.

Department of ISE BMS Institute of Technology and Mgmt


Passing structure by reference
The address location of structure variable is passed to function
while passing it by reference.
If structure is passed by reference, change made in structure
variable in function definition reflects in original structure
variable in the calling function.

Department of ISE BMS Institute of Technology and Mgmt


Passing structure by value
#include <stdio.h>
struct student
{ char name[50]; int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration otherwise
compiler shows error */
int main()
{ struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as argument
return 0;
}
Department of ISE BMS Institute of Technology and Mgmt
void Display(struct student stu)
{
printf("\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
OUTPUT
Enter student's name: Kevin
Enter roll number: 149
Name: Kevin
Roll: 149

Department of ISE BMS Institute of Technology and Mgmt


Passing structure by reference

#include <stdio.h>
struct distance
{ int feet;
float inch; };
void Add(struct distance d1,struct distance d2, struct distance
*d3);
int main()
{ struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet);
Department of ISE BMS Institute of Technology and Mgmt
printf("Enter inch: ");
scanf("%f",&dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d",&dist2.feet);
printf("Enter inch: ");
scanf("%f",&dist2.inch);
Add(dist1, dist2, &dist3);
/*passing structure variables dist1 and dist2 by value whereas
passing structure variable dist3 by reference */
printf("\nSum of distances = %d\'-%.1f \"",dist3.feet, dist3.inch);
return 0;
}
Department of ISE BMS Institute of Technology and Mgmt
void Add(struct distance d1,struct distance d2, struct distance *d3)
{
/* Adding distances d1 and d2 and storing it in d3 */
d3->feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12)
{ /* if inch is greater or equal to 12, converting it to feet. */
d3->inch-=12;
++d3->feet;
}
}

Department of ISE BMS Institute of Technology and Mgmt


OUTPUT
First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5
Sum of distances = 18'-2.3"

Department of ISE BMS Institute of Technology and Mgmt


typedef
• Reserved keyword in c
• It allows you to create a new data type name for an existing data type.
• We can create a new data type name for primitive as well as user
defined data type.
Syntax:
typedef old_data_type new_data_type;

Department of ISE BMS Institute of Technology and Mgmt


typedef
Eg1: Eg2:
typedef int integer; struct emp
integer a,b,c; {
integer a[10]; int emp_id;
Typedef int raju
char name[10];
raju a; };
Raju b; typedef struct emp employee;
employee emp1,emp2;
Typedef eg
I int main( )
{
#include <stdio.h> Book book[10];
#include <string.h> strcpy( book.title, "C Programming");
typedef struct Books strcpy( book.author, "Nuha Ali");
{ strcpy( book.subject, "C Programming”);
char title[50]; book.book_id = 6495407;
char author[50]; printf( "Book title : %s\n", book.title);
char subject[100]; printf( "Book author : %s\n", book.author);
int book_id; printf( "Book subject : %s\n", book.subject);
} Book[10]; printf( "Book book_id : %d\n",book.book_id);
return 0;
}
typedef vs #define
• #define is a C-directive which is also used to define
the aliases for various data types similar
to typedef but with the following differences −

–typedef is limited to giving symbolic names to types only


where as #define can be used to define alias for values as
well, you can define 1 as ONE etc.
–typedef interpretation is performed by the compiler
whereas #define statements are processed by the pre-
processor.

Department of ISE BMS Institute of Technology and Mgmt


Unions
• Unions are similar to structures used to store values of different data
types.
union tag_name
{
data type1 var1;
data_type2 var2;
.
.
};

Department of ISE BMS Institute of Technology and Mgmt


Structure Union
1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a 2. When a variable is associated with a union,
structure, the compiler allocates the memory the compiler allocates the memory by
for each member. The size of structure is considering the size of the largest memory.
greater than or equal to the sum of sizes of So, size of union is equal to the size of largest
its members. The smaller members may end member.
with unused slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.
4. The address of each member will be in 4. The address is same for all the members of
ascending order This indicates that memory a union. This indicates that every member
for each member will start at different offset begins at the same offset value.
values.
5 Altering the value of a member will not 5. Altering the value of any of the member
affect other members of the structure. will alter other member values.
6. Individual member can be accessed at a 6. Only one member can be accessed at a
time time.
7. Several members of a structure can 7. Only the first member of a union can be
initialize at once. Department of ISE BMS Institute of Technology and Mgmt
initialized.
eg
struct stu
{
char c;
int l;
float p; // Total size: 7 bytes
};
union emp
{
char c[20];
int l;
float p; // total bytes : 4 bytes
};

Department of ISE BMS Institute of Technology and Mgmt


Lab Program -13. STRUCTURES
Implement structures to read, write, compute average-
marks and the students scoring above and below the
average marks for a class of N students
1) Program to maintain a record of student using structure
#include <stdio.h>
struct student
{
char usn[50];
char name[50];
int marks;
} s[10];
Department of ISE BMS Institute of Technology and Mgmt
void main()
{
int i,n,countav=0,countbv=0; float sum,average;
clrscr();
printf("Enter number of Students\n"); scanf("%d",&n);
printf("Enter information of students:\n");

2)Storing information

for(i=0;i<n;i++)
{
printf("Enter USN: ");
scanf("%s",s[i].usn);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("\n");
} Department of ISE BMS Institute of Technology and Mgmt
3)displaying information
printf("Displaying Information:\n\n");
for(i=0; i<n; i++)
{
printf("\nUSN: %s\n",s[i].usn); printf("Name: ");
puts(s[i].name);
printf("Marks: %d",s[i].marks); printf("\n");
}
for(i=0;i<n;i++)
{
sum=sum+s[i].marks;
}
average=sum/n;
printf("\nAverage marks: %f",average);

Department of ISE BMS Institute of Technology and Mgmt


countav=0;
countbv=0;
for(i=0;i<n;i++)
{
if(s[i].marks>=average)
countav++;
else
}
countbv++;
printf("\nTotal No of students above average= %d",countav);
printf("\nTotal No of students below average= %d",countbv);
}

Department of ISE BMS Institute of Technology and Mgmt


Output

Department of ISE BMS Institute of Technology and Mgmt


Module-5

Prof. Swetha M S
OBJECTIVES
• Pointer variable definitions and initialization
• Pointer operators
• Passing arguments to functions by reference
• Pointer expressions and pointer arithmetic
• Relationships between pointers and arrays
• Array of pointers
• Character pointer and functions
• Pointer to pointer

Department of ISE BMS Institute of Technology and Mgmt


POINTERS

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 43


8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 44
1
2 /*Using the & and * operators */
3 #include <stdio.h>
4
5 int main( void )
6 {
7 int a; /* a is an integer */
 fig07_04.c
8
9
int *aPtr; /* aPtr is a pointer to an integer */
(1 of 2 )
10 a = 7;
11 aPtr = &a; /* aPtr set to address of a */
12
13 printf( "The address of a is %p"
14 "\nThe value of aPtr is %p", &a, aPtr );
If aPtr points to a, then &a and
15 aPtr have the same value.
16 printf( "\n\nThe value of a is %d"
17 "\nThe value of *aPtr is %d", a, *aPtr ); a and *aPtr have the same value
18
19 printf( "\n\nShowing that * and & are complements of "
20 "each other\n&*aPtr = %p"
21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr ); &*aPtr and *&aPtr have the same value
22
23 return 0; /* indicates successful termination */
24
25 } /* end main */

Department of ISE BMS Institute of Technology and Mgmt


The address of a is 0012FF7C
The value of aPtr is 0012FF7C

The value of a is 7
The value of *aPtr is 7

Showing that * and & are complements of each other.


&*aPtr = 0012FF7C
*&aPtr = 0012FF7C

 fig07_04.c
(2 of 2 )
Department of ISE BMS Institute of Technology and Mgmt
Pointers and functions

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 47


8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 48
Cube a variable using call-by-value
#include <stdio.h>
int cubeByValue( int n ); /* prototype */
int main( void )
{
int number = 5;
printf( "The original value of number is %d", number );
/* pass number by value to cubeByValue */
number = cubeByValue( number );
printf( "\nThe new value of number is %d\n", number );
return 0;
}
int cubeByValue( int n )
{
return n * n * n;
}

The original value of number is 5


The new value of number is 125
Department of ISE BMS Institute of Technology and Mgmt
Call-by-reference with a pointer argument
Function prototype takes a pointer argument
#include <stdio.h>
void cubeByReference( int *nPtr ); /* prototype */
int main( void ) Function cubeByReference is
{ passed an address, which can be
int number = 5; the value of a pointer variable
printf( "The original value of number is %d", number );
/* pass address of number to cubeByReference */
cubeByReference( &number );
printf( "\nThe new value of number is %d\n", number );
return 0;
} In this program, *nPtr is
void cubeByReference( int *nPtr ) number, so this statement
{ modifies the value of
*nPtr = *nPtr x*nPtr x *nPtr; /* cube *nPtr */ number itself.
}

Department of ISE BMS Institute of Technology and Mgmt


Pointers and array

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 51


8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 52
8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 53
Pointers to Strings

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 54


8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 55
8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 56
Pointer to Pointer

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 57


8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 58
Address arithmetic

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 59


8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 60
8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 61
Advantages and disadvantages

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 62


8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 63
8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 64
8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 65
Lan Program 14- USE OF POINTERS

Develop a program using pointers to


compute the sum, mean and standard
deviation of all elements stored in an
array of n real numbers

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 66


The formula for standard deviation (SD)

• Step 1: Find the mean.


• Step 2: For each data point, find the square of its distance to the mean.
• Step 3: Sum the values from Step 2.
• Step 4: Divide by the number of data points.
• Step 5: Take the square root.

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 67


#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
float a[10], *ptr, mean, std, sum=0, sumstd=0;
int n,i;
clrscr();
printf("Enter the no of elements\n"); scanf("%d",&n);
printf("Enter the array elements\n"); for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 68
for(i=0;i<n;i++)
{
sum=sum+ *ptr; ptr++;
}
mean=sum/n; ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd + pow((*ptr - mean),2);
ptr++;
}
std= sqrt(sumstd/n);
printf("Sum=%.3f\t",sum); printf("Mean=%.3f\t",mean);
printf("Standard deviation=%.3f\t",std);
return 0;
} 8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 69
8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 70
Viva Question
1. Define pointer?
2. How do you declare a pointer variable?
3. What is * and &in pointer concept.
4. What are the advantages and disadvantages of using pointer?
5. Give the difference between static allocation and dynamic allocation of
memory space.
6. What is the effect of the ++ and --operators on pointer variable
7. Explain the pointers to arrays concept?

8/24/2020 Department of ISE BMS Institute of Technology and Mgmt 71


Module-5
Dynamic memory allocation

Prof Swetha M S
Assistant Professor
ISE-BMSIT&M

Department of ISE BMS Institute of Technology & Mgmt 5-1


Types of memory allocation

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Static vs Dynamic Memory
Definition
Allocation
Static memory allocation is a method of Dynamic memory allocation is a method of
allocating memory, and once the memory is allocating memory, and once the memory is
allocated, it is fixed. allocated, it can be changed.
Modification
In dynamic memory allocation, the
In static memory allocation, it is not
memory can be minimized or maximize
possible to resize after initial allocation.
accordingly.
Implementation
Static memory allocation is easy to Dynamic memory allocation is complex
implement. to implement.
Speed
In static memory, allocation execution is In dynamic memory, allocation execution
faster than dynamic memory allocation. is slower than static memory allocation.
Memory Utilization
Dynamic memory allocation allows
reusing the memory. The programmer can
In static memory allocation, cannot reuse
allocate more memory when required .
the unused memory.
He can release the memory when
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
necessary.
Disadvantages of static memory
allocation
• The exact size of array is unknown untill the
compile time.
• The size of array you have declared initially can
be sometimes insufficient and sometimes more
than required.

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Dynamic memory allocation
• Dynamic memory allocation allows a program to
obtain more memory space, while running or to
release space when no space is required.
Functions defined in (stdlib.h)
• malloc-stands for memory allocation.
• calloc-stands for contiguous allocation.
• realloc-stands for reallocation
• free- to release the space

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Dynamic memory allocation
Functions

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
malloc ()
• The malloc() function returns a pointer to an
area of memory with size of byte size. If the
space is insufficient, allocation fails and returns
NULL pointer.
Syntax
• ptr=(cast-type*)malloc(byte-size)
Eg:
• ptr=(int*)malloc(100*sizeof(int));

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
calloc ()
• The name calloc stands for "contiguous allocation". The
only difference between malloc() and calloc() is that,
malloc() allocates single block of memory whereas
calloc() allocates multiple blocks of memory each of
same size and sets all bytes to zero.
Syntax
• ptr=(cast-type*)calloc(n,element-size);
Eg:
• ptr=(float*)calloc(25,sizeof(float));

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
realloc ()
• If the previously allocated memory using malloc
and calloc is insufficient or more than sufficient.
Then, you can change memory size previously
allocated using realloc()
Syntax
• ptr=realloc(ptr,newsize);
Eg:
• ptr=realloc(ptr,100*sizeof(char));

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
free
• Dynamically allocated memory with either
calloc() or malloc() does not get return on its
own. The programmer must use free() explicitly
to release space.
Syntax
• free(ptr);

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Example pgm using malloc
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{ char *mem_alloc; /* memory allocated dynamically */
mem_alloc = malloc( 15 * sizeof(char) );
if(mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,“hai hello ");
}
printf("Dynamically allocated memory content : %s\n", mem_alloc );
free(mem_alloc);
}

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
O/P
• Dynamically allocated memory content: hai hello

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Example pgm using calloc
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{ char *mem_alloc; /* memory allocated dynamically */
mem_alloc = calloc( 15, sizeof(char) );
if(mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,“hai hello every one");
}
printf("Dynamically allocated memory content : %s\n", mem_alloc );
free(mem_alloc);
}

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
O/P
• Dynamically allocated memory content:
hai hello every one

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Example program for realloc
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{ char *mem_alloc; /* memory allocated dynamically */
mem_alloc = malloc( 20 * sizeof(char) );
if( mem_alloc == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,“hai hello every one");
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
printf("Dynamically allocated memory content : " \ "%s\n",
mem_alloc );
mem_alloc=realloc(mem_alloc,100*sizeof(char));
if( mem_alloc == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"space is extended upto 100 characters");
}
printf("Resized memory : %s\n", mem_alloc );
free(mem_alloc);
}

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Output
• Dynamically allocated memory content: hai hello
every one
• Resized memory: space is extended upto 100
characters

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
To find sum of n elements entered by user. To perform this program, allocate
memory dynamically using malloc() function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{ printf("Error! memory not allocated.");
exit(0);
}

Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt

You might also like