02/06/2020
1
RECURSION: FUNCTION CALLING ITSELF
Programming and Data Structure 1
Programming and Data Structure 2
Recursion
• A process by which a function calls itself repeatedly.
– Either directly.
• X calls X.
– Or cyclically in a chain.
• X calls Y, and Y calls X.
• Used for repetitive computations in which each action is stated in terms of a previous result.
fact(n) = n * fact (n-1)
02/06/2020
2
Programming and Data Structure 3
Contd.
• For a problem to be written in recursive form, two conditions are to be satisfied:
– It should be possible to express the problem in recursive form.
– The problem statement must include a stopping condition.
fact(n) = 1, if n = 0
= n * fact(n-1), if n > 0
Programming and Data Structure 4
• Examples:
– Factorial: fact(0) = 1
fact(n) = n * fact(n-1), if n > 0
– GCD: gcd (0, n) = n
gcd (m, 0) = m
gcd (m, n) = m, if m = n
gcd (m, n) = gcd (m%n, n), if m > n
gcd (m, n) = gcd (m, n%m), if m < n
– Fibonacci series (0, 1, 1, 2, 3, 5, 8, 13, ….) fib (0) = 0
fib (1) = 1
fib (n) = fib (n-1) + fib (n-2), if n > 1
02/06/2020
3
Example 1 :: Factorial
Programming and Data Structure 5
long int fact (n)
int n;
{
if (n == 0)
return (1);
else
return (n * fact(n-1));
}
Programming and Data Structure 6
Example 2 :: GCD
int gcd (m, n)
int m, n;
{
if (m == 0) return n;
if (n == 0) return m;
if (m == n) return (m);
if (m > n)
return gcd (m%n, n);
else
return gcd (m, n%m);
}
02/06/2020
4
Programming and Data Structure 7
• Mechanism of execution
– When a recursive program is executed, the recursive function calls are not executed immediately.
• They are kept aside (on a stack) until the stopping condition is encountered.
• The function calls are then executed in reverse order.
Programming and Data Structure 8
Example :: Calculating fact(4)
– First, the function calls will be processed: fact(4) = 4 * fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1 * fact(0)
– The actual values return in the reverse order: fact(0) = 1
fact(1) = 1 * 1 = 1
fact(2) = 2 * 1 = 2
fact(3) = 3 * 2 = 6
fact(4) = 4 * 6 = 24
02/06/2020
5
Programming and Data Structure 9
Example 3 :: Fibonacci number
• Fibonacci number f(n) can be defined as:
f(0) = 0 f(1) = 1
f(n) = f(n-1) + f(n-2), if n > 1
– The successive Fibonacci numbers are:
0, 1, 1, 2, 3, 5, 8, 13, 21, …..
• Function definition:
int f (int n)
{
if (n < 2) return (n);
else return (f(n-1) + f(n-2));
}
Programming and Data Structure 10
Tracing Execution
• How many times the function is called when evaluating f(4) ?
• Inefficiency:
– Same thing is computed several times.
f(4)
f(3) f(2)
f(1) f(2) f(0) f(1)
f(1) f(0)
called 9 times
02/06/2020
6
Performance Tip
• Avoid Fibonacci-style recursive programs which result in an exponential “explosion” of calls.
• Avoid using recursion in performance situations.
• Recursive calls take time and consume additional memory.
Programming and Data Structure 11
Fibonacci number: iterative version
Programming and Data Structure 12
#include <stdio.h>
int f (int x);
int main()
{
printf (“\n %d %d %d %d”, f(2), f(3), f(4), f(5));
}
int f (int n)
{
int a = 0, b = 1, temp, i;
for (i=2; i<=n; i++)
{
temp = a + b;
a = b;
b = temp;
}
return (b);
}
Output:
1 2 3 5
02/06/2020
7
Programming and Data Structure 13
Example 4 :: Towers of Hanoi Problem
5
4
3 2 1
LEFT CENTER RIGHT
Programming and Data Structure 14
• The problem statement:
– Initially all the disks are stacked on the LEFT pole.
– Required to transfer all the disks to the RIGHT pole.
• Only one disk can be moved at a time.
• A larger disk cannot be placed on a smaller disk.
– CENTER pole is used for temporary storage of disks.
02/06/2020
8
Programming and Data Structure 15
• Recursive statement of the general problem of n disks.
– Step 1:
• Move the top (n-1) disks from LEFT to CENTER.
– Step 2:
• Move the largest disk from LEFT to RIGHT.
– Step 3:
• Move the (n-1) disks from CENTER to RIGHT.
Programming and Data Structure 16
#include <stdio.h>
void transfer (int n, char from, char to, char temp);
main()
{
int n; /* Number of disks */
scanf (%d, &n);
transfer (n, ’L’, ’R’, ’C’);
}
void transfer (int n, char from, char to, char temp)
{
if (n > 0) {
transfer (n-1, from, temp, to);
printf (Move disk %d from %c to %c \n, n, from, to);
transfer (n-1, temp, to, from);
}
return;
}
02/06/2020
9
Programming and Data Structure 17
3
Move disk 1 from L to R
Move disk 2 from L to C
Move disk 1 from R to C
Move disk 3 from L to R
Move disk 1 from C to L
Move disk 2 from C to R
Move disk 1 from L to R
4
Move disk 1 from L to C
Move disk 2 from L to R
Move disk 1 from C to R
Move disk 3 from L to C
Move disk 1 from R to L
Move disk 2 from R to C
Move disk 1 from L to C
Move disk 4 from L to R
Move disk 1 from C to R
Move disk 2 from C to L
Move disk 1 from R to L
Move disk 3 from C to R
Move disk 1 from L to C
Move disk 2 from L to R
Move disk 1 from C to R
Programming and Data Structure 18
Move disk 5 from L to R
Move disk 1 from C to L
Move disk 2 from C to R
Move disk 1 from L to R
Move disk 3 from C to L
Move disk 1 from R to C
Move disk 2 from R to L
Move disk 1 from C to L
Move disk 4 from C to R
Move disk 1 from L to R
Move disk 2 from L to C
Move disk 1 from R to C
Move disk 3 from L to R
Move disk 1 from C to L
Move disk 2 from C to R
Move disk 1 from L to R
5
Move disk 1 from L to R
Move disk 2 from L to C
Move disk 1 from R to C
Move disk 3 from L to R
Move disk 1 from C to L
Move disk 2 from C to R
Move disk 1 from L to R
Move disk 4 from L to C
Move disk 1 from R to C
Move disk 2 from R to L
Move disk 1 from C to L
Move disk 3 from R to C
Move disk 1 from L to R
Move disk 2 from L to C
Move disk 1 from R to C
02/06/2020
10
Programming and Data Structure 19
Recursion vs. Iteration
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance
– Choice between performance (iteration) and good software engineering (recursion).
Programming and Data Structure 20
How are function calls implemented?
• The following applies in general, with minor variations that are implementation dependent.
– The system maintains a stack in memory.
• Stack is a last-in first-out structure.
• Two operations on stack, push and pop.
– Whenever there is a function call, the activation record gets pushed into the stack.
• Activation record consists of:
– the return address in the calling program,
– the return value from the function, and
– the local variables inside the function.
02/06/2020
11
Programming and Data Structure 21
main()
{
……..
x = gcd (a, b);
……..
}
int gcd (int x, int y)
{
……..
……..
return (result);
}
Return Addr
Return Value
Local Variables
Before call After call After return
STA
CK
Activation record
Programming and Data Structure 22
main()
{
……
x=ncr(a,b);
……
}
int ncr (int n,int r)
{
return (fact(n)/
fact(r)/fact(n-r));
}
LV1, RV1, RA1
Before call Call fact ncr returns
int fact (int n)
{
………
return(result);
}
3 times
LV1, RV1, RA1
fact returns
LV1, RV1, RA1
LV2, RV2, RA2
Call ncr
3 times
02/06/2020
12
Programming and Data Structure 23
What happens for recursive calls?
• What we have seen ….
– Activation record gets pushed into the stack when a function call is made.
– Activation record is popped off the stack when the function returns.
• In recursion, a function calls itself.
– Several function calls going on, with none of the function calls returning back.
• Activation records are pushed onto the stack continuously.
• Large stack space required.
• Activation records keep popping off, when the termination condition of recursion is reached.
Programming and Data Structure 24
• We shall illustrate the process by an example of computing factorial.
– Activation record looks like:
Return Addr
Return Value
Local
Variables
02/06/2020
13
Programming and Data Structure 25
Example:: main() calls fact(3)
int fact (n)
int n;
{
if (n == 0)
return (1);
else
return (n * fact(n-1));
}
main()
{
int n;
n = 3;
printf (”%d \n”, fact(n) ); }
Programming and Data Structure 26
RA .. main
-
n = 3
RA .. main
-
n = 3
RA .. fact
-
n = 2
RA .. main
-
n = 3
RA .. fact
-
n = 2
RA .. fact
-
n = 1
RA .. main
-
n = 3
RA .. fact
-
n = 2
RA .. fact
-
n = 1
RA .. fact
1
n = 0
RA .. main
-
n = 3
RA .. fact
-
n = 2
RA .. fact
1*1 = 1
n = 1
RA .. main
-
n = 3
RA .. fact
2*1 = 2
n = 2
RA .. main
3*2 = 6
n = 3
TRACE OF THE STACK DURING EXECUTION
main calls fact
fact returns to main
02/06/2020
14
Programming and Data Structure 27
Do Yourself
• Trace the activation records for the following version of Fibonacci
sequence.
#include <stdio.h>
int f (int n)
{
int a, b;
if (n < 2) return (n);
else {
a = f(n-1);
b = f(n-2);
return (a+b);
}
}
main() {
printf(Fib(4) is: %d \n, f(4));
}
Return Addr
(either main,
or X, or Y)
Return Value
Local
Variables
(n, a, b)
X
Y
main
Storage Class of Variables
02/06/2020
15
Programming and Data Structure 29
What is Storage Class?
• It refers to the permanence of a variable, and its scope within a program.
• Four storage class specifications in C: – Automatic: auto
– External: extern
– Static: static
– Register: register
Programming and Data Structure 30
Automatic Variables
• These are always declared within a function and are local to the function in which they are declared.
– Scope is confined to that function.
• This is the default storage class specification. – All variables are considered as auto unless explicitly
specified otherwise.
– The keyword auto is optional.
– An automatic variable does not retain its value once control is transferred out of its defining function.
02/06/2020
16
Programming and Data Structure 31
#include <stdio.h>
int factorial(int m)
{
auto int i;
auto int temp=1;
for (i=1; i<=m; i++)
temp = temp * i;
return (temp);
}
main()
{
auto int n;
for (n=1; n<=10; n++)
printf (%d! = %d \n,
n, factorial (n));
}
Programming and Data Structure 32
Static Variables
• Static variables are defined within individual functions and have the same scope as automatic variables.
• Unlike automatic variables, static variables retain their values throughout the life of the program.
– If a function is exited and re-entered at a later time, the static variables defined within that function will retain their previous values.
– Initial values can be included in the static variable declaration.
• Will be initialized only once.
• An example of using static variable: – Count number of times a function is called.
02/06/2020
17
Programming and Data Structure 33
#include <stdio.h>
int factorial (int n)
{
static int count=0;
count++;
printf (n=%d, count=%d \n, n, count);
if (n == 0) return 1;
else return (n * factorial(n-1));
}
main()
{
int i=6;
printf (Value is: %d \n, factorial(i));
}
EXAMPLE 1
Programming and Data Structure 34
• Program output: n=6, count=1
n=5, count=2
n=4, count=3
n=3, count=4
n=2, count=5
n=1, count=6
n=0, count=7
Value is: 720
02/06/2020
18
Programming and Data Structure 35
#include <stdio.h>
int fib (int n)
{
static int count=0;
count++;
printf (n=%d, count=%d \n, n, count);
if (n < 2) return n;
else return (fib(n-1) + fib(n-2));
}
main()
{
int i=4;
printf (Value is: %d \n, fib(i));
}
EXAMPLE 2
Programming and Data Structure 36
• Program output:
n=4, count=1 n=3, count=2
n=2, count=3
n=1, count=4
n=0, count=5
n=1, count=6
n=2, count=7
n=1, count=8
n=0, count=9
Value is: 3 [0,1,1,2,3,5,8,….]
f(4)
f(3) f(2)
f(1) f(2) f(0) f(1)
f(1) f(0)
02/06/2020
19
Programming and Data Structure 37
Register Variables
• These variables are stored in high-speed registers within the CPU.
– Commonly used variables may be declared as register variables.
– Results in increase in execution speed.
– The allocation is done by the compiler.
Programming and Data Structure 38
External Variables
• They are not confined to single functions.
• Their scope extends from the point of definition through the remainder of the program.
– They may span more than one functions.
– Also called global variables.
• Alternate way of declaring global variables.
– Declare them outside the function, at the beginning.
02/06/2020
20
Programming and Data Structure 39
#include <stdio.h>
int count=0; /** GLOBAL VARIABLE **/
int factorial (int n)
{
count++;
printf (n=%d, count=%d \n, n, count);
if (n == 0) return 1;
else return (n * factorial(n-1));
}
main() {
int i=6;
printf (Value is: %d \n, factorial(i));
printf (Count is: %d \n, count);
}
SOME EXAMPLES ON RECURSION
Programming and Data Structure 40
02/06/2020
21
GCD Computation … Correct Version #include <stdio.h>
int gcd (m, n)
int m, n;
{
if (m == 0) return n;
if (n == 0) return m;
if (m == n) return (m);
if (m > n)
return gcd (m%n, n);
else
return gcd (m, n%m);
}
int main()
{
int num1, num2;
scanf ("%d %d", &num1, &num2);
printf ("\nGCD of %d and %d is %d", num1, num2, gcd(num1,num2));
}
Programming and Data Structure 41
GCD of 12 and 12 is 12
GCD of 15 and 0 is 15
GCD of 0 and 25 is 25
GCD of 156 and 66 is 6
GCD of 75 and 925 is 25
Compute power ab
// Compute a to the power b
#include <stdio.h>
long int power (int a, int b)
{
if (b == 0) return (1);
else return (a * power(a,b-1));
}
int main()
{
int x, y;
long int result;
scanf ("%d %d", &x, &y);
result = power (x, y);
printf ("\n%d to the power %d is %ld", x, y, result);
}
Programming and Data Structure 42
3 to the 4 is 81
2 to the power 16 is 65536
2 to the power 8 is 256
17 to the power 4 is 83521
436 to the power 0 is 1
02/06/2020
22
Sum of digits of a number
// Find sum of the digits of a number
#include <stdio.h>
int digitsum (int num)
{
int digit;
if (num == 0) return (0);
else {
digit = num % 10;
return (digit + digitsum(num/10));
}
}
int main()
{
int a;
scanf ("%d", &a);
printf ("\nSum of digits of %d is %d", a, digitsum(a));
}
Programming and Data Structure 43
Sum of digits of 25 is 7
Sum of digits of 23863 is 22
Sum of digits of 11111 is 5
Sum of digits of 0 is 0
Sum of digits of 9999 is 36
Decimal to Binary // Print a decimal number in binary
#include <stdio.h>
void dec2bin (int n)
{
if (n == 0) return;
else {
dec2bin (n/2);
printf ("%2d", n%2);
}
}
int main()
{
int dec;
scanf ("%d", &dec);
printf ("\nBinary of %d is",
dec);
dec2bin (dec);
}
Programming and Data Structure 44
Binary of 25 is 1 1 0 0 1
Binary of 12 is 1 1 0 0
Binary of 128 is 1 0 0 0 0 0 0 0
Binary of 254 is 1 1 1 1 1 1 1 0
02/06/2020
1
Arrays in C
Programming and Data Structure 2
Basic Concept
• Many applications require multiple data items that have common characteristics.
– In mathematics, we often express such groups of data items in indexed form:
x1, x2, x3, …, xn
• Why are arrays essential for some applications?
– Take an example.
– Finding the minimum of a set of numbers.
02/06/2020
2
Programming and Data Structure 3
if ((a <= b) && (a <= c))
min = a;
else
if (b <= c)
min = b;
else
min = c;
if ((a <= b) && (a <= c) && (a <= d))
min = a;
else
if ((b <= c) && (b <= d))
min = b;
else
if (c <= d)
min = c;
else
min = d;
3 numbers
4 numbers
Programming and Data Structure 4
The Problem
• Suppose we have 10 numbers to handle.
• Or 20.
• Or 100.
• How to tackle this problem?
• Solution:
– Use arrays.
02/06/2020
3
Programming and Data Structure 5
Using Arrays
• All the data items constituting the group share the same name.
int x[10];
• Individual elements are accessed by specifying the index.
x[0] x[1] x[2] x[9]
x is a 10-element one-dimensional array
Programming and Data Structure 6
• The name of the array also denotes the starting address of the array in memory.
– Example: int x[10];
x[0], x[1], x[2], … indicates the contents of the successive array locations.
x indicates the starting address in memory for the array.
02/06/2020
4
Programming and Data Structure 7
An Example
#include <stdio.h>
main()
{
int x[10];
x[0] = 15;
x[1] = x[0] + 5;
printf (”\n%d %d %d %u \n”, x[0], x[1], x[2], x);
}
Output:
15 20 1107384350 3221224640
Garbage Address
Declaring Arrays
• Like variables, the arrays that are used in a program must be declared before they are used.
• General syntax:
type array-name[size];
– type specifies the data type of element that will be contained in the array (int, float, char, etc.).
– size is an integer constant which indicates the maximum number of elements that can be stored inside the array.
• Example: int marks[5];
– marks is an array containing a maximum of 5 integers.
Programming and Data Structure 8
02/06/2020
5
Programming and Data Structure 9
• Examples:
int x[10]; char line[80];
float points[150];
char name[35];
• If we are not sure of the exact size of the array, we can define an array of a large size.
int marks[50];
though in a particular run we may only be using, say, 10 elements.
Programming and Data Structure 10
How an array is stored in memory?
• Starting from a given memory location, the successive array
elements are allocated space in consecutive memory
locations.
x: starting address of the array in memory
k: number of bytes allocated per array element
– Element a[i] :: allocated memory location at address x + i*k
– First array index assumed to start at zero.
Array a
x x+k x+2k
int a[10];
02/06/2020
6
Programming and Data Structure 11
Accessing Array Elements
• A particular element of the array can be accessed by specifying two things:
– Name of the array.
– Index (relative position) of the element in the array.
• In C, the index of an array starts from zero.
• Example:
– An array is defined as int x[10];
– The first element of the array x can be accessed as x[0], fourth element as x[3], tenth element as x[9], etc.
Programming and Data Structure 12
Contd.
• The array index must evaluate to an integer between 0 and n-1 where n is the number of elements in the array.
• Any integer expression can be given as the index.
a[x+2] = 25; b[3*x-y] = a[10-x] + 5;
02/06/2020
7
Programming and Data Structure 13
A Warning
• In C, while accessing array elements, array bounds are not checked.
• Example: int marks[5];
:
:
marks[8] = 75;
– The above assignment would not necessarily cause an error.
– Rather, it may result in unpredictable program results.
Programming and Data Structure 14
Initialization of Arrays
• General form:
type array_name[size] = {list of values};
• Examples:
int marks[5] = {72, 83, 65, 80, 76};
char name[4] = {’A’, ’m’, ’i’, ’t’};
• Some special cases:
– If the number of values in the list is less than the number of elements, the remaining elements are automatically set to zero. float total[5] = {24.2, -12.5, 35.1};
total[0]=24.2, total[1]=-12.5, total[2]=35.1,
total[3]=0, total[4]=0
02/06/2020
8
Programming and Data Structure 15
Contd.
– The size may be omitted. In such cases the compiler automatically allocates enough space for all initialized elements.
int flag[] = {1, 1, 1, 0};
char name[] = {’A’, ’m’, ’i’, ’t’};
Programming and Data Structure 16
Example 1: Find the minimum of a set of 10 numbers
#include <stdio.h>
main()
{
int a[10], i, min;
for (i=0; i<10; i++)
scanf (%d, &a[i]);
min = 99999; /* or, min=a[0] */
for (i=0; i<10; i++)
{
if (a[i] < min)
min = a[i];
}
printf (\n Minimum is %d, min);
}
02/06/2020
9
Programming and Data Structure 17
Example 1: Find the minimum of a set of 10 numbers
#include <stdio.h>
main()
{
int a[10], i, min;
for (i=0; i<10; i++)
scanf (%d, &a[i]);
min = a[0];
for (i=0; i<10; i++)
{
if (a[i] < min)
min = a[i];
}
printf (\n Minimum is %d, min);
}
Programming and Data Structure 18
#include <stdio.h>
#define size 10
main()
{
int a[size], i, min;
for (i=0; i<size; i++)
scanf (%d, &a[i]);
min = a[0];
for (i=0; i<size; i++)
{
if (a[i] < min)
min = a[i];
}
printf (\n Minimum is %d, min);
}
Alternate
Version 1
Change only one line to change the
problem size
02/06/2020
10
Programming and Data Structure 19
#include <stdio.h>
main()
{
int a[100], i, min, n;
scanf (%d, &n);
/* Number of elements */
for (i=0; i<n; i++)
scanf (%d, &a[i]);
min = a[0];
for (i=0; i<n; i++)
{
if (a[i] < min)
min = a[i];
}
printf (\n Minimum is %d, min);
}
Alternate
Version 2
Define an array of large size and use only the required
number of elements
Programming and Data Structure 20
Example 2: Computing gpa
#include <stdio.h>
#define nsub 6
main()
{
int grade_pt[nsub], cred[nsub], i,
gp_sum=0, cred_sum=0;
float gpa;
for (i=0; i<nsub; i++)
scanf (%d %d, &grade_pt[i],&cred[i]);
for (i=0; i<nsub; i++)
{
gp_sum += grade_pt[i] * cred[i];
cred_sum += cred[i];
}
gpa = (float) gp_sum / cred_sum;
printf (\n GPA is: %f, gpa);
}
Handling two arrays at the same time
02/06/2020
11
Things you cannot do
• You cannot
– use “=” to assign one array variable to another:
a = b; /* a and b are arrays */
– use “==” to directly compare array variables:
if (a == b) ………
– directly scanf or printf arrays:
printf (”……”, a);
Programming and Data Structure 21
int a[20], b[20];
Programming and Data Structure 22
How to copy the elements of one array to another?
• By copying individual elements:
int a[25], b[25];
……
for (j=0; j<25; j++)
a[j] = b[j];
02/06/2020
12
Programming and Data Structure 23
How to read the elements of an array?
• By reading them one element at a time.
int a[25]; ……
for (j=0; j<25; j++)
scanf (%f, &a[j]);
• The ampersand (&) is necessary.
• The elements can be entered all in one line or in different lines.
Programming and Data Structure 24
How to print the elements of an array?
• By printing them one element at a time.
for (j=0; j<25; j++)
printf (\n %f, a[j]);
– The elements are printed one per line.
printf (\n); for (j=0; j<25; j++)
printf ( %f, a[j]);
– The elements are printed all in one line (starting with a new line).
02/06/2020
13
Passing Arrays to a Function
How to pass arrays to a function?
• An array name can be used as an argument to a function.
– Permits the entire array to be passed to the function.
– The way it is passed differs from that for ordinary variables.
• Rules:
– The array name must appear by itself as argument, without brackets or subscripts.
– The corresponding formal argument is written in the same manner.
• Declared by writing the array name with a pair of empty brackets.
Programming and Data Structure 26
02/06/2020
14
Programming and Data Structure 27
An Example with 1-D Array
main()
{
int n;
float list[100], avg;
:
avg = average(n,list);
:
}
float average(a,x)
int a;
float x[];
{
:
sum = sum + x[i];
}
We can also write
float x[100];
But the way the function is written makes it general; it works with arrays of any size.
Programming and Data Structure 28
main()
{
int n;
float list[100], avg;
:
avg = average(n,list);
:
}
float average(int a, float x[])
{
:
sum = sum + x[i];
}
Same program, with the parameter types specified in the same line as the function definition.
02/06/2020
15
Programming and Data Structure 29
main()
{
int n, i;
float list[100], avg;
scanf (“%d”, &n);
for (i=0; i<n; ++)
scanf (%d, &list[i]);
avg = average (n, list);
printf (\nAverage is: %d, avg);
}
float average(int a, float x[])
{
float sum = 0; int index;
for (index=0; index<a; index++)
sum = sum + x[i];
return sum;
}
The Actual Mechanism
• When an array is passed to a function, the values of the array elements are not passed to the function.
– The array name is interpreted as the address of the first array element.
– The formal argument therefore becomes a pointer to the first array element.
– When an array element is accessed inside the function, the address is calculated using the formula stated before.
– Changes made inside the function are thus also reflected in the calling program.
Programming and Data Structure 30
02/06/2020
16
Programming and Data Structure 31
Contd.
• Passing parameters in this way is called
call-by-reference.
• Normally parameters are passed in C using
call-by-value.
• Basically what it means?
– If a function changes the values of array elements, then these changes will be made to the original array that is passed to the function.
Programming and Data Structure 32
Example: Parameter passed as a value
#include <stdio.h>
void swap (int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
main()
{
int x,y;
x=10; y=15;
printf(x=%d y=%d \n, x, y);
swap(x,y);
printf(x=%d y=%d \n, x, y);
}
Output: x=10 y=15
x=10 y=15
02/06/2020
17
Programming and Data Structure 33
Example: Minimum of a set of numbers
#include <stdio.h>
int minimum (int x[], int y);
main()
{
int a[100], i, n;
scanf (%d, &n);
for (i=0; i<n; i++)
scanf (%d, &a[i]);
printf (\n Minimum is %d,
minimum(a,n));
}
int minimum (x, size)
int x[], size;
{
int i, min = x[0];
for (i=0;i<size;i++)
if (min > x[i])
min = x[i];
return (min);
}
Parameter x passed by reference, size by value.
Programming and Data Structure 34
Example: Square each element of array
#include <stdio.h>
void square (int a[], int b);
main()
{
int a[100], i, n;
scanf (%d, &n);
for (i=0; i<n; i++)
scanf (”%d”, &a[i]);
square (a, n);
printf (\nNew array is:);
for (i=0; i<n; i++)
printf ( %d, a[i]);
}
void square (x,size)
int x[], size;
{
int i;
for (i=0;i<size;i++)
x[i] = x[i] * x[i];
return;
}
02/06/2020
18
Introduction to Pointers
• What is the concept?
– Pointer is a variable which stores the address of memory location of another variable.
– When declared, we must specify the data type of the variable being pointed to.
– Examples:
int *p;
float *x, *y;
char *flag;
Programming and Data Structure 35
• A pointer variable can be assigned the address of another variable. int a, *p;
a=10;
p = &a; /* Address of ‘a’ assigned to ‘p’ */
printf (”%d %d”, a, *p);
/* Will print “10 10” */
• Point to note:
– Array name indicates pointer to first array element. int num[10], *xyz;
xyz = num; /* Points to x[0] */
Programming and Data Structure 36
02/06/2020
19
– When an integer expression E is added to or subtracted from a pointer, actually scale factor times E is added or subtracted.
• Scale factor indicates size of the data item being pointed to in number of bytes.
• Scale factor for char is 1, int is 4, float is 4, double is 8, etc.
int a, *p;
p = &a; /* p is assigned address of ‘a’
(say, 2500) */
p++; /* p will become 2504 */
p = p – 10; /* p will become 2464 */
Programming and Data Structure 37
Programming and Data Structure 38
• Consider the declaration:
int x[5] = {1, 2, 3, 4, 5}; int *p;
– Suppose that the base address of x is 2500, and each integer requires 4 bytes.
Element Value Address
x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516
02/06/2020
20
Programming and Data Structure 39
Contd.
Both x and &x[0] have the value 2500.
p = x; and p = &x[0]; are equivalent.
• Relationship between p and x: p = &x[0] = 2500
p+1 = &x[1] = 2504
p+2 = &x[2] = 2508
p+3 = &x[3] = 2512
p+4 = &x[4] = 2516
*(p+i) gives the
value of x[i]
• An example:
int x[ ] = {1,2,3,4,5,6,7,8,9,10};
int *p;
p = x + 3; /* Point to 4th element of x */
printf (%d, *p); /* Will print 4 */
printf (%d, *(p+5));
/* Will print 9 */
printf (%d %d, p[3], p[-1]);
/* Will print 7 and 3 */
Programming and Data Structure 40
02/06/2020
21
Programming and Data Structure 41
Example: function to find average
#include <stdio.h>
main()
{
int x[100], k, n;
scanf (”%d”, &n);
for (k=0; k<n; k++)
scanf (”%d”, &x[k]);
printf (”\nAverage is %f”, avg (x, n));
}
float avg (array, size)
int array[], size;
{
int *p, i , sum = 0;
p = array;
for (i=0; i<size; i++)
sum = sum + *(p+i);
return ((float) sum / size);
}
Programming and Data Structure 42
Example: SWAP revisited
#include <stdio.h>
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
main()
{
int x, y;
x=10; y=15;
printf (x=%d y=%d \n, x,y);
swap (&x, &y);
printf (x=%d y=%d \n, x,y);
}
Output: x=10 y=15
x=15 y=10
02/06/2020
22
Character String
What we should learn about strings
– Representation in C
– String Literals
– String Variables
– String Input/Output
• printf, scanf, gets, fgets, puts, fputs
– String Functions
• strlen, strcpy, strncpy, strcmp, strncmp, strcat, strncat, strchr, strrchr, strstr, strspn, strcspn, strtok
– Reading from/Printing to Strings
• sprintf, sscanf
Programming and Data Structure 44
02/06/2020
23
Programming and Data Structure 45
Introduction
• A string is an array of characters.
– Individual characters are stored in memory in ASCII code.
– A string is represented as a sequence of characters terminated by the null (‘\0’) character.
‘\0’ l e H o l “Hello”
String Literals
• String literal values are represented by sequences of characters between double quotes (“)
• Examples
– represents empty string
– hello
• a versus ‘a’
– ‘a’ is a single character value (stored in 1 byte) as the ASCII value for the letter, a.
– a is an array with two characters, the first is a, the second is the character value \0.
46 Programming and Data Structure
02/06/2020
24
Referring to String Literals
• String literal is an array, can refer to a single character from the literal as a character
• Example:
printf(”%c”, ”hello”[1]);
outputs the character ‘e’
• During compilation, C creates space for each string literal (number of characters in the literal + 1)
47 Programming and Data Structure
Duplicate String Literals
• Each string literal in a C program is stored at a different location.
– Even if the string literals contain the same string, they are not equal (in the == sense)
• Example:
char string1[6] = hello;
char string2[6] = hello;
– but string1 does not equal string2 (they are stored in different memory locations).
48 Programming and Data Structure
02/06/2020
25
Programming and Data Structure 49
Declaring String Variables
• A string is declared like any other array:
char string-name[size];
– size determines the number of characters in string_name.
• When a character string is assigned to a character array, it automatically appends the null character (‘\0’) at the end of the string.
– size should be equal to the number of characters in the string plus one.
Programming and Data Structure 50
Examples
char name[30]; char city[15];
char dob[11];
• A string may be initialized at the time of declaration.
char city[15] = Calcutta; char city[15] = {'C', 'a', 'l', 'c', 'u',
't', 't', 'a’, ’\0'};
char dob[] = 12-10-1975;
Equivalent
02/06/2020
26
Changing String Variables
• Cannot change string variables connected to string constants, but can change pointer variables that are not tied to space.
• Example:
char *str1 = hello; /* str1 unchangeable */
char *str2 = goodbye; /* str2 unchangeable */
char *str3; /* Not tied to space */
str3 = str1; /* str3 points to same space as str1 */
str3 = str2;
51 Programming and Data Structure
Changing String Variables (cont)
• Can change parts of a string variable:
char str1[6] = hello;
str1[0] = 'y’; /* str1 is now “yello” */
str1[4] = '\0’; /* str1 is now “yell” */
• Have to stay within limits of the array.
– Responsibility of programmer.
Programming and Data Structure 52
02/06/2020
27
Programming and Data Structure 53
Reading Strings from the Keyboard
• Two different cases will be considered:
– Reading words
– Reading an entire line
Programming and Data Structure 54
Reading “words”
• scanf can be used with the “%s” format specifier.
char name[30];
:
scanf (%s, name);
– The ampersand (&) is not required before the
variable name with %s.
• Because name represents an address.
– The problem here is that the string is taken to be upto
the first white space (blank, tab, carriage return, etc.)
• If we type Rupak Biswas
• name will be assigned the string Rupak
02/06/2020
28
Programming and Data Structure 55
Reading a “line of text”
• In many applications, we need to read in an entire line of
text (including blank spaces).
• We can use the getchar() function for the purpose.
Programming and Data Structure 56
char line[81], ch;
int c = 0;
:
:
do
{
ch = getchar();
line[c] = ch;
c++;
}
while (ch != '\n');
c = c – 1;
line[c] = '\0';
Read characters until CR (‘\n’) is encountered
Make it a valid string
02/06/2020
29
Programming and Data Structure 57
Reading a line :: Alternate Approach
char line[81];
:
:
scanf (%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ], line);
char line[81];
:
:
scanf (%[^\n], line);
Reads a string containing uppercase
characters and blank spaces
Reads a string containing any characters
More on String Input
• Edit set input %[ListofChars]
– ListofChars specifies set of characters (called scan set)
– Characters read as long as character falls in scan set
– Stops when first non scan set character encountered
– Any character may be specified except ]
– Putting ^ at the start to negate the set (any character BUT list is
allowed)
• Examples: scanf (%[+0123456789], Number);
scanf (%[^\n], Line); /* read until newline char */
Programming and Data Structure 58
02/06/2020
30
Programming and Data Structure 59
Writing Strings to the Screen
• We can use printf with the “%s” format specification.
char name[50];
:
:
printf (\n %s, name);
Input / Output Example
#include <stdio.h>
void main( )
{
char LastName[11];
char FirstName[11];
printf(Enter your name (last, first): );
scanf(%10s%*[^,],%10s, LastName, FirstName);
printf(Nice to meet you %s %s\n, FirstName, LastName);
}
60 Programming and Data Structure
02/06/2020
31
String Functions
Programming and Data Structure 62
Processing Character Strings
• There exists a set of C library functions for character string manipulation.
– strcpy :: string copy
– strlen :: string length
– strcmp :: string comparison
– strtcat :: string concatenation
• It is required to add the line #include <string.h>
02/06/2020
32
Programming and Data Structure 63
strcpy()
• Works like a string assignment operator. char *strcpy (char *str1, char *str2);
– Assigns the contents of str2 to str1.
– Returns address of the destination string.
• Examples:
strcpy (city, Calcutta); strcpy (city, mycity);
• Warning:
– Assignment operator do not work for strings.
city = Calcutta ; INVALID
Programming and Data Structure 64
strlen()
• Counts and returns the number of characters in a string. int strlen (char *str);
• Example: len = strlen (string);
/* Returns an integer */
–The null character (‘\0’) at the end is not counted.
–Counting ends at the first null character.
02/06/2020
33
Programming and Data Structure 65
char city[15];
int n;
:
:
strcpy (city, Calcutta);
n = strlen (city);
n is assigned 8
Programming and Data Structure 66
strcmp()
• Compares two character strings. int strcmp (char *str1, char *str2);
– Compares the two strings and returns 0 if they are identical; non-zero otherwise.
• Examples:
if (strcmp(city, Delhi) == 0) { …… }
if (strcmp(city1, city2) != 0)
{ …… }
02/06/2020
34
• Actually, the function returns the difference in ASCII
values of the first letter of mismatch.
– Less than 0
• If the ASCII value of the character they differ at is smaller for
str1, or str2 is longer than str1
– Greater than 0
• If the ASCII value of the character they differ at is greater for
str1, or str1 is longer than str2
– Equal to 0
• If the two strings are identical
Programming and Data Structure 67
strcmp examples: strcmp(hello, hello) -- returns 0
strcmp(yello, hello) -- returns value > 0
strcmp(Hello, hello) -- returns value < 0
strcmp(hello, hello there) -- returns value < 0
strcmp(some diff, some dift) -- returns value < 0
• Expression for determining if two strings s1, s2 hold the same string value: !strcmp(s1, s2)
Programming and Data Structure 68
02/06/2020
35
String Comparison (strncmp)
Sometimes we only want to compare first n chars: int strncmp(char *s1, char *s2, int n)
Works the same as strcmp except that it stops at the nth character
looks at less than n characters if either string is shorter than n
strcmp(some diff, some DIFF) -- returns value > 0
strncmp(some diff, some DIFF,4) -- returns 0
Programming and Data Structure 69
String Comparison (ignoring case)
int strcasecmp(char *str1, char *str2)
• similar to strcmp except that upper and lower case characters
(e.g., ‘a’ and ‘A’) are considered to be equal
int strncasecmp(char *str1, char *str2, int n)
• version of strncmp that ignores case
Programming and Data Structure 70
02/06/2020
36
Programming and Data Structure 71
strcat()
• Joins or concatenates two strings together. char *strcat (char *str1, char *str2);
– str2 is appended to the end of str1.
– The null character at the end of str1 is removed, and str2 is joined at that point.
• Example:
strcpy(name1, Amit );
strcpy(name2, Roy);
strcat(name1, name2);
‘\0’ i m A t
‘\0’ y o R
i m A t ‘\0’ y o R
Programming and Data Structure 72
Example:: count uppercase
/* Read a line of text and count the number of
uppercase letters */
#include <stdio.h>
#include <string.h>
main()
{
char line[81];
int i, n, count=0;
scanf (%[^\n], line);
n = strlen (line);
for (i=0; i<n; i++)
if (isupper(line[i]) count++;
printf (\n The number of uppercase letters in
the string %s is %d, line, count);
}
02/06/2020
37
Programming and Data Structure 73
Example:: compare two strings
#include <stdio.h>
int my_strcmp (char s1[],char s2[])
{
int i=0;
while(s1[i]!='\0' && s2[i]!='\0'){
if (s1[i]!=s2[i]) return(s1[i]-s2[i]);
else i++;
}
return(s1[i]-s2[i]);
}
Parameters passed as character array
Programming and Data Structure 74
main()
{
char string1[100],string2[100];
printf(Give two strings \n);
scanf(%s %s, string1, string2);
printf (Comparison result: %d \n, my_strcmp(string1,string2));
}
Give two strings IITKGP IITMUMBAI
Comparison result: -2
Give two strings KOLKATA KOLKATA
Comparison result: 0
02/06/2020
38
Searching for a Character/String
char *strchr (char *str, int ch)
• returns a pointer to the first occurrence of ch in str
• returns NULL if ch does not occur in str
• can subtract original pointer from result pointer to
determine which character in array
char *strstr (char *str, char *searchstr)
• similar to strchr, but looks for the first occurrence of the
string searchstr in str
char *strrchr (char *str, int ch)
• similar to strchr except that the search starts from the end of
string str and works backward
Programming and Data Structure 75
Printing to a String
• The sprintf function allows us to print to a string argument
using printf formatting rules.
• First argument of sprintf is string to print to, remaining
arguments are as in printf.
Example:
char buffer[100];
sprintf (buffer, %s, %s, LastName, FirstName);
if (strlen(buffer) > 15)
printf(Long name %s %s\n, FirstName, LastName);
Programming and Data Structure 76
02/06/2020
39
Reading from a String
• The sscanf function allows us to read from a string argument
using scanf rules
• First argument of sscanf is string to read from, remaining
arguments are as in scanf
Example: char buffer[100] = A10 50.0;
sscanf (buffer, %c%d%f, &ch, &inum, &fnum);
/* puts ‘A’ in ch, 10 in inum and 50.0 in fnum */
Programming and Data Structure 77
Example: Duplicate Removal
Write a C function that takes a string as an argument and
modifies the string so as to remove all consecutive
duplicate characters, e.g., mississippi -> misisipi
void remove_duplicates (char word[]) {
int k, j;
char prev = '\0';
for (k = j = 0; word[k]!='\0'; k++) {
if (prev != word[k]) word[j++] = word[k];
prev = word[k];
}
word[j] = '\0';
}
Programming and Data Structure 78