0% found this document useful (0 votes)
8 views50 pages

Module 2 - Arrays & Functions

Uploaded by

balram.2022
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
8 views50 pages

Module 2 - Arrays & Functions

Uploaded by

balram.2022
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 50

Array &

Strings
Need of Array Variable
 Suppose we need to store rollno of the student in the integer variable.
Declaration
int rollno;
 Now we need to store rollno of 100 students.
Declaration
int rollno101, rollno102, rollno103,
rollno104...;
 This is not appropriate to declare these many integer variables.
e.g. 100 integer variables for rollno.
 Solution to declare and store multiple variables of similar type is an
array.
 An array is a variable that can store multiple values.
Definition: Array
 An array is a fixed size sequential collection of elements of same data
type grouped under single variable name.

[0] [1] [2] … [99]


int rollno[100
];

Fixed Size Sequential Same Data type Single Name


Here, the size of an It is indexed to 0 to 99 in All the elements (0-99) All the elements (0-99)
array is 100 (fixed) to sequence will be integer variables will be referred as a
store rollno common name rollno
Declaring an array
Syntax  By default array index
data-type variable- starts with 0.
name[size];  If we declare an array of
size 5 then its index
Integer Array [0] [1] [2] [3] [4] ranges from 0 to 4.
int mark[5];  First element will be
store at mark[0] and last
integer element will be stored at
mark[4] not mark[5].
[0] [1] [2] [3] [4]
 Like integer and float
Float Array
array we can declare
float avg[5]
;
array of type char.

float
Initialing and Accessing an Array
Declaring, initializing and accessing single integer variable
int mark=90; //variable mark is initialized with value 90
printf("%d",mark); //mark value printed

Declaring, initializing and accessing integer array variable


int mark[5]={85,75,76,55,45}; //mark is initialized with 5 values
printf("%d",mark[0]); //prints 85
printf("%d",mark[1]); //prints 75
printf("%d",mark[2]); //prints 65
printf("%d",mark[3]); //prints 55
printf("%d",mark[4]); //prints 45

[0] [1] [2] [3] [4]


mark[5] 85 75 65 55 45
Read(Scan) Array Elements
Reading array without loop Reading array using loop
1 void main() 1 void main()
2 { 2 {
3 int mark[5]; 3 int mark[5],i;
printf("Enter array element="); for(i=0;i<5;i++)
4 4
scanf("%d",&mark[0]); {
5 printf("Enter array element="); 5 printf("Enter array element=");
6 scanf("%d",&mark[1]); 6 scanf("%d",&mark[i]);
7 printf("Enter array element="); 7 }
8 scanf("%d",&mark[2]); 8 for(i=0;i<5;i++)
9 printf("Enter array element="); 9 {
10 scanf("%d",&mark[3]); 10 printf("%d",mark[i]);
11 printf("Enter array element="); 11 }
scanf("%d",&mark[4]); }
12 12
13 printf("%d",mark[0]);
14 printf("%d",mark[1]);
15 printf("%d",mark[2]);
16 printf("%d",mark[3]); [0] [1] [2] [3] [4]
17 printf("%d",mark[4]);
mark[5] 85 75 65 55 45
18 }
Multi Dimensional Array
Declaring 2 Dimensional Array
Syntax  A two dimensional array
data-type variable-name[x][y]; can be seen as a table
with ‘x’ rows and ‘y’
Declaration
columns.
int data[3][3]; //  The row number ranges
This array can hold 9 elements from 0 to (x-1) and
column number ranges
int data[3][3]; from 0 to (y-1).
Column-0 Column-1 Column-2

data[0] data[0] data[0]


Row-0
[0] [1] [2]
data[1] data[1] data[1]
Row-1
[0] [1] [2]
data[2] data[2] data[2]
Row-2
[0] [1] [2]
Initialing and Accessing a 2D Array: Example-1
Program
1 int data[3][3] = {
2 {1,2,3}, //row 0 with 3 elements
3 {4,5,6}, //row 1 with 3 elements
4 {7,8,9} //row 2 with 3 elements
5 }; Column-0 Column-1 Column-2
6 printf("%d",data[0][0]); //1
7 printf("%d",data[0][1]); //2 Row-0 1 2 3
8 printf("%d\n",data[0][2]); //3
9 Row-1 4 5 6
10 printf("%d",data[1][0]); //4
11 printf("%d",data[1][1]); //5 Row-2 7 8 9
12 printf("%d\n",data[1][2]); //6
13
14 printf("%d",data[2][0]);//7
15 printf("%d",data[2][1]); //8
16 printf("%d",data[2][2]); //9
1 // data[3][3]
2 can be initialized like this also
int data[3][3]={{1,2,3},{4,5,6},{7,8,9}};
Initialing and Accessing a 2D Array: Example-2
Program
1 int data[2][4] = {
2 {1,2,3,4}, //row 0 with 4 elements
3 {5,6,7,8}, //row 1 with 4 elements
4 };
5 printf("%d",data[0][0]); //1
6 printf("%d",data[0][1]); //2 Col-0 Col-1 Col-2 Col-3
7 printf("%d",data[0][2]); //3
8 printf("%d\n",data[0][3]); //4 Row-0 1 2 3 4
9
10 printf("%d",data[1][0]); //5 Row-1 5 6 7 8
11 printf("%d",data[1][1]); //6
12 printf("%d",data[1][2]); //7
13 printf("%d",data[1][3]); //8

1 // data[2][4]
2 can be initialized like this also
int data[2][4]={{1,2,3,4},{5,6,7,8}};
Read(Scan) 2D Array Elements
Program
1 void main(){
2 int data[3][3],i,j;
3 for(i=0;i<3;i++)
4 {
5 for(j=0;j<3;j++)
6 { Output
7 printf("Enter array element="); Enter array element=1
8 scanf("%d",&data[i][j]); Enter array element=2
9 } Enter array element=3
10 } Enter array element=4
11 for(i=0;i<3;i++) Enter array element=5
12 { Enter array element=6
13 for(j=0;j<3;j++) Enter array element=7
14 { Enter array element=8
15 printf("%d",data[i][j]); Enter array element=9
16 } 123
17 printf("\n"); 456
18 } 789
19 }
Develop a program to count number of positive, negative and zero
elements from 3 X 3 matrix
Program
1 void main(){
2 int data[3][3],i,j,pos=0,neg=0,zero=0; Output
3 for(i=0;i<3;i++) Enter array element=9
4 { Enter array element=5
5 for(j=0;j<3;j++) Enter array element=6
6 { Enter array element=-3
7 printf("Enter array element="); Enter array element=-7
8 scanf("%d",&data[i][j]); Enter array element=0
9 if(data[i][j]>0) Enter array element=11
10 pos=pos+1; Enter array element=13
11 else if(data[i][j]<0) Enter array element=8
12 neg=neg+1; positive=6,negative=2,zero
13 else =1
14 zero=zero+1;
15 }
16 }
17 printf("positive=%d,negative=%d,zero=
18 %d",pos,neg,zero);
}
Practice Programs
1. Develop a program to perform addition of two matrix.
2. Develop a program to perform multiplication of two matrix.
String
(Character Array)
Definition: String
 A String is a one-dimensional array of characters terminated by a
null('\0').
[0] [1] [2] … [9]
char name[10]
;

 Each character in the array occupies one byte of memory, and the last
character must always be null('\0').
 The termination character ('\0') is important in a string to identify
where the string ends.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10 D A R S H A N \0
]
Declaring & Initializing String
Declaration
char name[10]
;
Initialization method 1:
char name[10]={'D','A','R','S','H','A','N','
\0'};
Initialization method 2:
char name[10]="DARSHAN";
//'\
0' will be automatically inserted at the end in this type of declarati
on.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10 D A R S H A N \0
]
Read String: scanf()
Program
Output
1 void main()
2 { Enter name: Vellore
3 char name[10]; Name=Vellore
4 printf("Enter name:"); Output
5 scanf("%s",name);
Enter name: VIT Chennai
6 printf("Name=%s",name);
Name=VIT
7 }

 There is no need to use address of (&) operator in scanf to store a


string.
 As string name is an array of characters and the name of the array, i.e.,
name indicates the base address of the string (character array).
 scanf() terminates its input on the first whitespace(space, tab, newline
etc.) encountered.
Read String: gets()
Program
1 #include<stdio.h> Output
2 void main() Enter name:Vellore
3 { Institute
4 char name[10]; Name=Vellore Institute
5 printf("Enter name:");
6 gets(name); //
7 read string including white spaces
8 printf("Name=%s",name);
}
 gets(): Reads characters from the standard input and stores them as a
string.
 puts(): Prints characters from the standard.
 scanf(): Reads input until it encounters whitespace, newline or End
Of File(EOF) whereas gets() reads input until it encounters newline
or End Of File(EOF).
 gets(): Does not stop reading input when it encounters whitespace
instead it takes whitespace as a string.
String Handling Functions : strlen()
 C has several inbuilt functions to operate on string. These functions are
known as string handling functions.
 strlen(s1): returns length of a string in integer

Program
1 #include <stdio.h> Output
2 #include <string.h> //header file for string functions Enter string: VIT
3 void main() Chennai
4 { 11
5 char s1[10];
6 printf("Enter string:");
7 gets(s1);
8 printf("%d",strlen(s1)); // returns length of s1 in in
9 teger
}
String Handling Functions: strcmp()
 strcmp(s1,s2): Returns 0 if s1 and s2 are the same.
 Returns less than 0 if s1<s2.
 Returns greater than 0 if s1>s2.
Program
1 void main() Output
2 { Enter string-
3 char s1[10],s2[10]; 1:Computer
4 printf("Enter string-1:"); Enter string-
5 gets(s1); 2:Computer
6 printf("Enter string-2:"); Output
Strings are same
7 gets(s2); Enter string-
8 if(strcmp(s1,s2)==0) 1:Computer
9 printf("Strings are same"); Enter string-
10 else 2:Computer
11 printf("Strings are not same"); Strings are same
12 }
String Handling Functions
For examples consider: char s1[]="Their",s2[]="There";
Syntax Description
strcpy(s1,s2) Copies 2nd string to 1st string.
strcpy(s1,s2) copies the string s2 in to string s1 so s1 is now “There”. s2
remains unchanged.

strcat(s1,s2) Appends 2nd string at the end of 1st string.


strcat(s1,s2); a copy of string s2 is appended at the end of string s1. Now
s1 becomes “TheirThere”

strchr(s1,c) Returns a pointer to the first occurrence of a given character in the string s1.
printf("%s",strchr(s1,'i'));
Output : ir

strstr(s1,s2) Returns a pointer to the first occurrence of a given string s2 in string s1.
printf("%s",strstr(s1,"he"));
Output : heir
String Handling Functions (Cont…)
For examples consider: char s1[]="Their",s2[]="There";
Syntax Description
strrev(s1) Reverses given string.
strrev(s1); makes string s1 to “riehT”
strlwr(s1) Converts string s1 to lower case.
printf("%s",strlwr(s1)); Output :
their
strupr(s1) Converts string s1 to upper case.
printf("%s",strupr(s1)); Output : THEIR
strncpy(s1,s2,n Copies first n character of string s2 to string s1
) s1=""; s2="There";
strncpy(s1,s2,2);
printf("%s",s1); Output : Th
strncat(s1,s2,n Appends first n character of string s2 at the end of string s1.
) strncat(s1,s2,2);
printf("%s", s1); Output :
TheirTh
String Handling Functions (Cont…)
For examples consider: char s1[]="Their",s2[]="There";
Syntax Description
strncmp(s1,s2,n Compares first n character of string s1 and s2 and returns similar result as
) strcmp() function.
printf("%d",strcmp(s1,s2,3));
Output : 0
strrchr(s1,c) Returns the last occurrence of a given character in a string s1.
printf("%s",strrchr(s2,'e')); Output
: ere
Functions
What is Function?
 A function is a group of statements that perform a specific task.
 It divides a large program into smaller parts.
 A function is something like hiring a person to do a specific job for you.
 Every C program can be thought of as a collection of these functions.
 Program execution in C language starts from the main function.
Syntax
void main()
{
// body part
}

 Why function ?
 Avoids rewriting the same code over and over.
 Using functions it becomes easier to write programs and keep track of what they
doing.
Types of Function
Function

Library Function User Defined Function (UDF)

Predefined or inbuilt Created by User


Declarations inside header files Programmer need to declare it
Eg. printf() – stdio.h Eg. findSimpleInterest()
pow() – math.h areaOfCircle()
strcmp() – string.h
Program Structure for Function
 When we use a user-defined function program structure is divided into
three parts.
Function Structure
void func1(); Function Prototype

void main()
{
....
func1(); Function call
}

void func1()
{
.... Function definition
//function body
....
}
Function Prototype
 A function Prototype also know as function declaration.
 A function declaration tells the compiler about a function name and how to call the
function.
 It defines the function before it is being used or called.
 A function prototype needs to be written at the beginning of the program.

Syntax Example
return-type function-name (arg-1, arg 2, void addition(int, int);
…);
Function Definition
 A function definition defines the functions header and body.
 A function header part should be identical to the function prototype.
 Function return type
 Function name
 List of parameters
 A function body part defines function logic.
 Function statements

Syntax Example
return-type function-name (arg-1, arg 2, void addition(int x, int y)
…) {
{ printf("Addition is=%d“,
//... Function body (x+y)); }
}
WAP to add two number using add(int, int)
Function
Program Output
1 #include <stdio.h> Addition is = 11
2 void add(int, int); // function declaration
3
4 void main()
5 {
6 int a = 5, b = 6;
7 add(a, b); // function call
8 }
9
10 void add(int x, int y) // function definition
11 {
12 printf("Addition is = %d", x + y);
13 }
Actual parameters and Formal parameters
 Values that are passed to the called function from the main function
are known as Actual parameters.
 The variables declared in the function prototype or definition are
known as Formal parameters.
 When a method is called, the formal parameter is temporarily "bound"
to the actual parameter.

Actual parameters Formal parameters


void main() void add(int x, int y) // x and y are
{ formal parameters.
int a = 5, b = 6; {
add(a, b); // a and b are the printf("Addition is = %d", x + y);
actual parameters in this
call. }
}
Return Statement
 If function is returning a value to calling function, it needs to use the
keyword return.
 The called function can only return one value per call.

Syntax
return;
Or

return (expression);
WAP to find maximum number from two number
Program Output
1 #include <stdio.h> Max value is : 200
2 int max(int a, int b);
3 void main()
4 {
5 int a = 100;
6 int b = 200;
7 int maxvalue;
8 maxvalue = max(a, b);
9 printf("Max value is : %d\n",
10 maxvalue);
11 }
12 int max(int a, int b)
13 {
14 if (a > b)
15 return a; // return a
16 else
17 return b; // return b
18 }
Category of Function
(1) Function with no argument and but no return value
No
void main() Input void fun1()
{ {
..... .....
No return .....
fun1();
value .....
.....
} }

(2) Function with no argument and returns value


No
void main() Input int fun1(void)
{ {
..... .....
a = fun1() Function .....
..... result return b;
} }
Category of Function cont.
(3) Function with argument and but no return value
Value of
void main() Argument void fun1(int
{ f)
..... {
fun1(a); No Return .....
..... value .....
} .....
}
(4) Function with argument and returns value
Value of
void main() Argument int fun1(int
{ f)
..... {
b = Function .....
fun1(a); Result .....
..... return e;
} }
Storage Classes
 Storage class decides the scope, lifetime and memory allocation of
variable.
 Scope of a variable is the boundary within which a variable can be
used.
Storage
Storage
Initial
Scope Life Example
Specifier Value

Automatic Stack Garbage Within block End of block int a;


{auto} auto int a;

Register CPU Garbage Within block End of block


register int var;
{register} register

External Data Zero Global Till end of program extern int var;
{extern} segment Multiple file

static extern int


Static Data Zero Within block Till end of program
var;
{static} segment
static int var;
Static Example
Program Output
1 #include <stdio.h> Counter = 1
2 int incrementCounter(); Counter = 2
3
4 void main()
5 {
6 printf("Counter = %d \n",
7 incrementCounter());
8 printf("Counter = %d \n",
9 incrementCounter());
10 }
11
12 int incrementCounter()
13 {
14 static int count = 0; // static variable
15 count++;
return count;
}
Advantages of Function
 Using function we can avoid rewriting the same logic or code again and
again in a program.
 We can track or understand large program easily when it is divide into
functions.
 It provides reusability.
 It help in testing and debugging because it can be tested for errors
individually in the easiest way.
 Reduction in size of program due to code of a function can be used
again and again, by calling it.
Recursion
What is Recursion?
 Any function which calls itself is called recursive function and such
function calls are called recursive calls.
 Recursion cannot be applied to all problems, but it is more useful for
the tasks that can be defined in terms of a similar subtask.
 It is idea of representing problem a with smaller problems.
 Any problem that can be solved recursively can be solved iteratively.
 When recursive function call itself, the memory for called function
allocated and different copy of the local variable is created for each
function call.
 Some of the problem best suitable for recursion are
 Factorial
 Fibonacci
 Tower of Hanoi
Working of Recursive function
Working
void func1();

void main()
{
....
func1();
.... Function
} call

void func1()
{ Recursive
.... function call
func1();
....
}
Properties of Recursion
 A recursive function can go infinite like a loop. To avoid infinite running
of recursive function, there are two properties that a recursive function
must have.
 Base Case or Base criteria
 It allows the recursion algorithm to stop.
 A base case is typically a problem that is small enough to solve directly.
 Progressive approach
 A recursive algorithm must change its state in such a way that it moves forward
to the base case.
Recursion - factorial example
 The factorial of a integer n, is Recursive trace
product of
 n * (n-1) * (n-2) * …. * 1 Final Ans 5 *24 = 120
 Recursive definition of factorial Fact(5)
 n! = n * (n-1)! return 4 * 6 = 24
call
 Example
 3! = 3 * 2 * 1 Fact(4)
 3! = 3 * (2 * 1) return 3 * 2 = 6
call
 3! = 3 * (2!)
Fact(3)
return 2 * 1 = 2
call
Fact(2)
return 1
call
Fact(1)
WAP to find factorial of given number using
Recursion
Program Output
1 #include <stdio.h> Enter the number? 5
2 int fact(int); factorial = 120
3 void main()
4 {
5 int n, f;
6 printf("Enter the number?\n");
7 scanf("%d", &n);
8 f = fact(n);
9 printf("factorial = %d", f);
10 }
11 int fact(int n)
12 {
13 if (n == 0)
14 return 1;
15 else if (n == 1)
16 return 1;
17 else
18 return n * fact(n - 1);
19 }
Recursion - Fibonacci example
 A series of numbers , where Recursive trace
next number is found by adding
the two number before it. Fib(4) Final Ans. 3

 Recursive definition of return 1


return 2
Fibonacci
 Fib(0) = 0 Fib(3) Fib(2)
 Fib(1) = 1
return 1 return 1 return 0
 Fib(n) = Fib(n-1) + Fib(n-2) return 1
 Example Fib(2) Fib(1) Fib(1) Fib(0)
 Fib(4) = Fib(3) + Fib(2)
 Fib(4) = 3 return 1 return 0
Fib(1) Fib(0)
WAP to Display Fibonacci Sequence
Program Program contd.
1 #include <stdio.h> 15 int fibonacci(int n)
2 int fibonacci(int); 16 {
3 void main() 17 if (n == 0 || n == 1)
4 { 18 return n;
5 int n, m = 0, i; 19 else
6 printf("Enter Total terms\n"); 20 return (fibonacci(n - 1)
7 scanf("%d", &n); + fibonacci(n - 2));
8 printf("Fibonacci series\n"); 21 }
9 for (i = 1; i <= n; i++)
10 { Output
11 printf("%d ", fibonacci(m)); Enter Total terms
12 m++;
13 } 5
14 } Fibonacci series
0 1 1 2 3
Recursion - Decimal to Binary example
 To convert decimal to binary, Recursive trace
divide decimal number by 2 till
dividend will be less then 2 Final Ans 13%2 + 10*110 = 1101
 To convert decimal 13 to binary decToBin(13)
 13/2 = 6 reminder 1 return 6%2 + 10*11 = 110
 call
6/2 = 6 reminder 0
 3/2 = 3 reminder 1 decToBin(6)
 1/2 = 1 reminder 1 return 3%2 + 10*1 = 11
call
 Recursive definition of Decimal decToBin(3)
to Binary return 1%2 + 10*0 = 1
 decToBin(0) = 0 call
 decToBin(n) = n%2 + 10* decToBin(1)
decToBin(n/2) return 0
call
 Example
decToBin(0)
 decToBin(13) = 13%2 + 10
decToBin(6)
WAP to Convert Decimal to Binary
Program Output
1 #include <stdio.h> Enter a decimal number: 12
2 int convertDecimalToBinary(int);
3 void main() The binary equivalent = 110
4 { 0
5 int dec, bin;
6 printf("Enter a decimal number: ");
7 scanf("%d", &dec);
8 bin = convertDecimalToBinary(dec);
9 printf("The binary equivalent = %d \
10 n",bin);
11 }
12 int convertDecimalToBinary(int dec)
13 {
14 if (dec == 0)
15 return 0;
16 else
return (dec % 2 + 10 *
17 convertDecimalToBinary(dec / 2));
}
WAP to Convert Binary to Decimal
Program Output
1 #include <stdio.h> Enter a binary number: 101
2 int convertBinaryToDecimal(int b, int c, int t);
3 void main() Decimal value of 101 is 5
4 {
5 unsigned int binary, decimal;
6 printf("Enter a binary number: ");
7 scanf("%d", &binary);
8 decimal = convertBinaryToDecimal(binary, 1, 0);
9 printf("Decimal value of %d is %d", binary,
10 decimal);
11 }
12 int convertBinaryToDecimal(int b, int c, int t)
13 {
14 if (b > 0)
15 {
16 t += (b % 10) * c;
17 convertBinaryToDecimal(b / 10, c * 2, t);
18 }
19 else
20 return t;
}
Practice Programs
1) Write a program to find factorial of a given number using recursion.
2) WAP to convert decimal number into binary using recursion.
3) WAP to use recursive calls to evaluate F(x) = x – x3/3! + x5/5! – x7/7! +
… + xn/n!

You might also like