Computer Hardware and Software BMS
Computer Hardware and Software BMS
INTRODUCTION TO COMPUTER
HARDWARE AND SOFTWARE
Swetha M S
Asst. Professor
Dept. of ISE
BMSIT&M
Integrated circuits
Third. Keyboard, monitor and operating system
(ICs)
ULSI Nano
Fifth Mainly unclear
technology.
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.
Types of
Computers
•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
Subnotebook Palmtop
•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
• Advantage
• Speed
• Disadvantage
• Generate a large
amount of heat
during operation
DATA INFORMATION
• SOFTWARE is the non-tangible part that tells the computer how to do its
job.
•A letter
•A number
•A special character or symbol, or
•A space
1 petabyte (PB) 1024 terabytes Space used for rendering of film Avatar
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.
#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
}
$ 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'
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
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
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
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);
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
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)
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
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
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]
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
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Declaration of one dimensional
Array
Syntax: Datatype array_name[index];
• int marks[5]; mem2* 5=10 bytes
• float avg [3]; mem4*3=12 bytes
• char name[5]; mem1*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
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
for(i=0;i<=n-1;i++) for(i=0;i<=n-1;i++)
{ {
scanf(“%d”,&a[i]); printf(“%d”,a[i]);
} }
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]
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
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};
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;
}
}
Strings
Prof. Swetha M S
Assistant Professor
ISE-BMSIT& M
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
Department
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
Reading and displaying strings
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
Departmentof
ofISE
ISE BMS Institute of Technology & Mgmt
String Manipulation functions
#include<string.h>
String manipulation functions:
Function Work of Function
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
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
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
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
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
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
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
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
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",°ree);
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
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 */
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
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 );
}
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;
}
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
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
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 */
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/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
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..)
Eg:
struct person
{
char name[10];
int age;
} p1,p2;
#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;
}
}
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);
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
The value of a is 7
The value of *aPtr is 7
fig07_04.c
(2 of 2 )
Department of ISE BMS Institute of Technology and Mgmt
Pointers and functions
Prof Swetha M S
Assistant Professor
ISE-BMSIT&M
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