c-programming-class 3
TRANSCRIPT
-
8/14/2019 C-Programming-Class 3
1/52
1
Session 03
Arrays, Strings and Functions
-
8/14/2019 C-Programming-Class 3
2/52
2
Session Objectives
To learn about array declaration and manipulation To learn about matrix operation using two dimensional arrays
To learn about string handling using arrays.
To learn about functions and function declaration in C
To about passing values to the functions
-
8/14/2019 C-Programming-Class 3
3/52
3
Session Topics
Accessing the array elements and array initialization Single and multidimensional array
Strings and string variables: Reading and Printing a
string
Functions in C and function definitions
Passing arguments to a function
Functions and arrays
-
8/14/2019 C-Programming-Class 3
4/52
4
Arrays
An array lets you declare and work with a collection of
values of the same type. For example, you might want tocreate a collection of five integers.
Example :int a, b, c, d, e;
Using arrays it could be declared as below.
int a[5];
This reserves memory for an array that to hold five integer
values The five separate integers inside this array are accessed
by an index. All arrays start at index 0 and go to (n-1) inC. For example:
int a[5];
a[0] = 12;
a[1] = 9;
a[2] = 14;
a[3] = 5;
a[4] = 1;
You need to make a declaration beforeusing an array and to specify its data type,its name and, in most cases
Make sure the array has a valid name
-
8/14/2019 C-Programming-Class 3
5/52
5
Arrays
Arrays are storage structures in memory that can help store multiple dataitems having a common characteristic.
An array is referred to only by a single name, although they have multiple
data items
The individual data items can be of any type, like integers, float or characters.
But inside one array, all the data items must be of a single type If we have an array of 50 elements,all of them must be of integer type or
of any one type
We cannot have the first 20 being integers while the rest are float type
Character arrays have a special property...
Each element of the array can hold one character. But if you end the array
with theNULL CHARACTER, denoted by \0 (that is, backslash and zero),
you'll have what is known as a STRING CONSTANT. The null character
marks the end of a string
-
8/14/2019 C-Programming-Class 3
6/52
6
Initializing Arrays
You can assign values to the array in several ways this example demonstrates
int main() {int arrayOfInts1[8] = {1, 2, 3, 4, 5, 6, 7, 8};
int arrayOfInts2[8];
int arrayOfInts3[] = {1,2,3,4,5, 6,7,8}; /* an unsized array */
int arrayOfInts4[10];int i; arrayOfInts2[0] = 1;
arrayOfInts2[1] = 2;
arrayOfInts2[2] = 3;
arrayOfInts2[3] = 4;
arrayOfInts2[4] = 5;
arrayOfInts2[5] = 6;arrayOfInts2[6] = 7;
arrayOfInts2[7] = 8;
for(i=0 ; i
-
8/14/2019 C-Programming-Class 3
7/52
7
Arrays One of the feature about array indexing is that, you can use a loop to
manipulate the index. For example, the following code initializes all of the
values in the array to 0:int a[5];
int i;
for (i=0; i
-
8/14/2019 C-Programming-Class 3
8/52
8
Multi-Dimensional Arrays
An array's DIMENSION is the number of indices required toreference an element.
For example, arrayOfInts[0] is the first element. The index is 0 -
there is only 1 index so arrayOfInts is one dimensional.
what about 2D?int array2D[3][5];
This tells the computer to reserve enough memory space for an
array with 15, that is, 3 x 5 elements.
If you ever wanted to find out how much memory your arraysoccupy (1D or multidimensional), you can use the sizeof()
operator.
-
8/14/2019 C-Programming-Class 3
9/52
9
Example of a 2D Array
main()
{
int t,i,num[3][4];
for(t=0;t
-
8/14/2019 C-Programming-Class 3
10/52
10
Memory Allocation of a 2D Array
1211109
8765
4321
0 1 2 3
0
1
2
num[t][i]
-
8/14/2019 C-Programming-Class 3
11/52
11
3D Array
A three dimensional array can be thought of as an array of arrays ofarrays.
Example:
static int [2][2][2]={
{
{1,2},{3,4}
}
{
{5,6},
{7,8}}
}
-
8/14/2019 C-Programming-Class 3
12/52
12
Memory Allocation of a 3D Array
87654321
0th 2-D Array 1st 2-D Array
-
8/14/2019 C-Programming-Class 3
13/52
13
An Introduction to Strings
Strings in C are an array of charecters terminated with a nullcharacter, '\0',.
This means that the length of a string is the number of
characters it contains plus one to store the null character. Examples:char string_1 = "Hello";
char string_2[ ] = "Hello";
char string_3[6] = "Hello";
One can use the string format specifier, %s, to handle strings.
-
8/14/2019 C-Programming-Class 3
14/52
14
Reading Strings
One possible way to read in a string is by using scanf. However,the problem with this, is that if you were to enter a string whichcontains one or more spaces, scanf would finish reading when itreaches a space, or if return is pressed.
We could use thegets function...gets takes just one argument - a char pointer, or the name of a
char array, but don't forget to declare the array / pointer variablefirst!
What's more, is that it automatically prints out a newlinecharacter, making the output a little neater
-
8/14/2019 C-Programming-Class 3
15/52
15
Writing Strings
Like with printf and scanf, if you want to use gets( ) and puts( )
you'd have to include the stdio.h header file.
puts( ) is similar to gets in the way that it takes one argument - a
char pointer. This also automatically adds a newline character
after printing out the string.
-
8/14/2019 C-Programming-Class 3
16/52
16
Strings: An Example
#include
void main()
{
char array1[50],array2[];
printf("Now enter another string less than 50");printf(" characters with spaces: \n");
gets(array1);
printf("\nYou entered: ");
puts(array1);
printf("\nTry entering a string less than 50");
printf(" characters, with spaces: \n");
scanf("%s", array2);
printf("\nYou entered: %s\n", array2);
}
-
8/14/2019 C-Programming-Class 3
17/52
17
Output
Now enter another string less than 50 characters withspaces:hello world
You entered: hello world
Try entering a string less than 50 characters, withspaces:hello world
You entered: hello
-
8/14/2019 C-Programming-Class 3
18/52
18
String Functions defined instring.h
strlen(str)---Returns length of the stringstr.
strcpy(str1,str2)---Copies the stringstr2 to stringstr1.
strncpy(str1,str2,n)---Copies at most n charecters of string
str2 to stringstr1.
strcat(str1,str2)---Append stringstr2 to stringstr1.
strncat(str1,str2,n)---Append first n charecters of stringstr2 in stringstr1.
strcmp(str1,str2)---Compare two stringsstr1 andstr2.
-
8/14/2019 C-Programming-Class 3
19/52
19
String Functions defined instring.h
strstr(str1,str2)---Finds the occurrence of stringstr2 instringstr1.
Strset(str1,c)---Sets all occurrence instr1 to the characteridentified by c.
strchr(str,c)---Scans the stringstrfor the first occurrenceof characterc.
strrchr(str,c)---Find the last occurrence of the charactercin stringstr.
strlwr(str)---Converts the stringstrto lowercase. strupr(str)---Converts the stringstrto uppercase.
strrev(str)---Reverses the stringstr.
-
8/14/2019 C-Programming-Class 3
20/52
20
What are Functions?
A function can be thought of as a mini-program, where you can pass in
information, execute a group of statements and return an optional value.
A function is CALLED (orINVOKED) when you need to branch off from
the program flow and execute the group of statements within that function.
Once the statements in the function are executed, program flow resumes
from the place where you called your function.
You've already encountered a few functions: main, printf and scanf.
The main function is special, in the way that it's called automatically when
the program starts.
In C, and other programming languages, you can create your own functions.
-
8/14/2019 C-Programming-Class 3
21/52
21
Function Features
Functions have 5 main features:
1. TheDATA TYPEis the data type of theRETURNVALUEof thefunction.
2. TheNAMEis required as an identifier to the function, so that thecomputer knows which function is called. Naming of functionsfollows the same set of rules as the naming of variables.3. Functions can takeARGUMENTS- a function might need extrainformation for it to work. Arguments are optional.4. The functionBODYis surrounded by curly brackets and contains
the statements of the function.5. TheRETURN VALUEis the value that is passed back to the mainprogram. Functions exit whenever you return a value. If the functiondoes not return a value, we put the void keyword before the functionname.
-
8/14/2019 C-Programming-Class 3
22/52
22
Why Functions?
Allows a large program to be broken down into smaller, manageable, self
contained parts
Allows formodularization of a complex task
Functions are the only way in which modularization can be achieved in C
Avoids the need for repeated programming of the same instructions needed by
various programs or parts of a program
Decomposition of a large program through functions enhances logical clarity
Programmers may build their own set of functions in a customized library
Writing programs using functions allows the separation of machine dependent
portions from others, enhancingportability of programs
-
8/14/2019 C-Programming-Class 3
23/52
23
Defining Functions
Every function in C has the form
type name (argument list, // if any)
{
declarations, statements, and/or expressions
}
The set of arguments in a function header is optional.
Each argument is preceded by its type declaration
data-type name (type arg1, type arg2, ...); If a function does not take any inputs the header will have
a function name followed by ( ).
-
8/14/2019 C-Programming-Class 3
24/52
24
The Function Body
The function body is a set of statements enclosed between { }.
These set of statements define the task carried out by thefunction.
This function body, like any other compound statement, cancontain any type of statements assignment statement
compound statements
function calls
anything that is a valid statement
The body must contain at least one return statement.
The return statement helps in passing the single value result backto the calling program.
-
8/14/2019 C-Programming-Class 3
25/52
25
The return Statement
The general form of the return statement is
return (expression);
This contains the keyword return followed by an optional expression.
The value of the expression is returned to the calling part of theprogram.
Since an expression can result in only one value, a function can alsoreturn only one value.
If the expression is omitted, the return statement does not transfer anyvalue to the calling program, but just transfers control to the calling
program.
Such functions are defined as void.
void functionName() {statements;
return;
}
-
8/14/2019 C-Programming-Class 3
26/52
26
The return Statement (Contd)
void functionName(int x, int y, int z) {
if (x > y) {
statements;
return;
else if (x > z)
statements;return;
}
The above code fragment illustrates the use of return in void functions.
The return statement causes the calling program to start execution
from the statement immediately following the function call. A function body can contain one or more return statements.
-
8/14/2019 C-Programming-Class 3
27/52
27
Function Definition:An Example
int max(int x, int y)
{
if (x >= y)
return (x);else
return (y);
}
A function called max is defined that returns an int. The function body is fairly simple as it just checks which
of the variables in greater and returns that value
-
8/14/2019 C-Programming-Class 3
28/52
28
Invoking & Using Functions A function can be invoked by specifying the name of the function followed by the list of
arguments separated by commas. This is also called a call to the functionor afunction call.
If a function does not require any arguments, just write the name of the function with ( )
as in filler( );
The function call can happen in a simple expression or part of a complex expression.
The arguments in the function call are called as actual arguments.
The arguments used in the function definition are called asformal arguments.
There is a one-to-one match of the list and type of the formal arguments with the actual
arguments.
The value of each actual parameter will be passed as input to the called function through
the corresponding formal parameter.
We already made use of a function as return ((x * Y)/gcd(x,y));
A function not returning anything can appear as a standalone statement such as
printf(...);
-
8/14/2019 C-Programming-Class 3
29/52
29
Call by Value
void some(int m,int n)
{
m=100;
n=200;
}
void main()
{
int a,b;
a=10;
b=20;
some(a,b);
printf(a = %d and b = %d,a,b);
}
Called function
Calling function
-
8/14/2019 C-Programming-Class 3
30/52
30
Call by Value:Sequence of steps
Start
a=10
b=20
some(a,b)
void some(m,n)
m=100
n=100
write a,b
Stop
10
20
a
b
1000
1004
100
2000
200
2004m
n
Calling
FunctionCalled
Function
10
20
-
8/14/2019 C-Programming-Class 3
31/52
31
Call by Value: Sequence of steps
Execution starts from the calling function.
After executing the statements a=10,b=20the values of 10 and 20 willbe copied into memory locations()(Assume 1000 and 1004).
The function some() is invoked with two parameters a andb.
The control is now transferred to the called function some().
Memory is allocated for theformal parameters m and n(Assume 2000 and
2004). When the statementsm=100,n=200 are executed, the earlier values of 10
and 20 are replaced with 100 and 200.
Control is transferred from the called function to the calling function to the
point from where it has been invoked earlier.
The copy of actual parameters(formal parameters) is changed and actualparameters are un-affected.
Execution is stopped.
-
8/14/2019 C-Programming-Class 3
32/52
32
Call by Reference
void some(int *m,int *n)
{
*m=100;
*n=200;
}
void main()
{
int a,b;
a=10;
b=20;
some(&a,&b);
printf( a = %d and b = %d,a,b);
}
Calling function
Called function
-
8/14/2019 C-Programming-Class 3
33/52
33
Call by Reference:Sequence of steps
Start
a=10
b=20
some(&a,&b)
void some(m,n)
m=100
n=100
write a,b
Stop
200
m
n
Calling
FunctionCalled
Function
100
1000
1004
10
20
1000
2000
2004
2000
a
b 200
m
n
-
8/14/2019 C-Programming-Class 3
34/52
34
Call by Reference:Sequence of steps
Execution starts from the calling function.
After executing the statements a=10,b=20the values of 10 and 20 will becopied into memory locations()(Assume 1000 and 1004).
The function some() is invoked with two parameters a andb.
The control is now transferred to the called function some().
Memory is allocated for theformal parameters m and n(Assume 2000 and
2004).Since the addresses are passed as parameters,these addresses arecopied into the locations 2000 and 2004 respectively.
When the statements *m=100,*n=200 the memory location pointed to bemi.e,the contents pointing to 1000 which in this case is 10 is replaced by
100.
Control is transferred from the called function to the calling function to thepoint from where it has been invoked earlier.
The actual parameters can be changed by formal parameters throughpointers indirectly.
Execution is stopped.
-
8/14/2019 C-Programming-Class 3
35/52
35
What is Recursion?
Recursion is the name given for expressing anything in terms of itself. Afunction which contains a call to itself or a call to another function, whicheventually causes the first function to be called is known asRECURSIVE FUNCTION.
Each time a function is called, a new set of local variables and formal
parameters are allocated on thestack and execution starts from thebeginning of the function using these new value.
The call to itself is repeated till a base condition is reached. Once a basecondition or a terminal condition is reached, the function returns a resultto the previous copy of the function.
A sequence of returns ensure that the solution to the original problem is
obtained.
-
8/14/2019 C-Programming-Class 3
36/52
36
Case Study: Factorial ofn
Design Process
The series can be multiplied pictorially as shown below:
1 * 1 * 2 * 3 * nprod
prod
prod
prod
Recursive Technique
1 if n = 0
Fact(n) = n * fact(n-1) otherwise
-
8/14/2019 C-Programming-Class 3
37/52
37
Program to find the factorial ofn
int fact(int n)
{
if (n==0) return 1; /* 0! = 1 */
return n*fact(n-1); /* n!=n*(n-1)! */
}
void main()
{
int n;
printf(Enter value for n\n);
scanf(%d,&n);printf(The factorial of %d = %d\n,n,fact(n));
}
-
8/14/2019 C-Programming-Class 3
38/52
38
Tower of Hanoi
There are three towers.
N gold disks, with decreasing sizes, placedon the source tower.
You need to move all of the disks from thesource tower to the destination tower.
Larger disks can not be placed on top ofsmaller disks.
The third tower can be used to temporarilyhold disks.
RULES
-
8/14/2019 C-Programming-Class 3
39/52
39
Tower of Hanoi
To create an algorithm to solve this problem.
It is convenient to generalize the problem to N-disk.
AIM
SOLUTION
First we move the N-1 disks from first tower to
third tower.
Then we move the Nth disk to the second tower.
Thirdly we move the N-1 disks from temporarytower to destination tower.
-
8/14/2019 C-Programming-Class 3
40/52
40
Tower of Hanoi
Source DestinationTemporary
-
8/14/2019 C-Programming-Class 3
41/52
41
Tower of Hanoi
(0,0,0)
-
8/14/2019 C-Programming-Class 3
42/52
42
Tower of Hanoi
(0,0,1)
-
8/14/2019 C-Programming-Class 3
43/52
43
Tower of Hanoi
(0,1,1)
-
8/14/2019 C-Programming-Class 3
44/52
44
Tower of Hanoi
(0,1,0)
-
8/14/2019 C-Programming-Class 3
45/52
45
Tower of Hanoi
(1,1,0)
-
8/14/2019 C-Programming-Class 3
46/52
46
Tower of Hanoi
(1,1,1)
-
8/14/2019 C-Programming-Class 3
47/52
47
Tower of Hanoi
(1,0,1)
-
8/14/2019 C-Programming-Class 3
48/52
48
Tower of Hanoi
(1,0,0)
-
8/14/2019 C-Programming-Class 3
49/52
49
Advantages and Disadvantages of Recursion
Clearer and simple versions ofalgorithms can be created.
Recursive definition can be
easily transferred into arecursive function.
Separate copy of the functionvariables are created for eachcall and definitely consumes lot
of memory.Most of the time is spent in pushing and popping thenecessary items from the stackand so consumes more time tocompute the result.
They often execute slowlywhen compared to theiriterative counterpart because othe overhead of the repeatedfunction calls.
Advantages Disadvantages
-
8/14/2019 C-Programming-Class 3
50/52
50
Iteration v/s Recursion
Uses repetition structures such
as for,while loops.
It is counter controlled and the
body of the loop terminates
when the termination condition
is failed.
They execute much faster and
occupy less memory and can be
designed easily.
Uses selection structures such
as if-else,switch statements.
It is terminated when a base
condition.The terminal
condition is gradually reached
by invocation of the same
function repeatedly.
It is expensive in terms of
processor time and memory
usage.
Iteration Recursion
-
8/14/2019 C-Programming-Class 3
51/52
51
Summary
An array lets you declare and work with a collection of values of the
same type. One of the feature about array indexing is that, you can use a loop to
manipulate the index.
A three dimensional array can be thought of as an array of arrays of
arrays.
Strings in C are an array of charecters terminated with a null
character, '\0',.
A function can be thought of as a mini-program, where you can pass
in information, execute a group of statements and return an optional
value.
Recursion is the name given for expressing anything in terms of itself.
A function which contains a call to itself or a call to another function.
-
8/14/2019 C-Programming-Class 3
52/52
Thank You!