Unit 2
Unit 2
Unit 2
AIML Programming in C
UNIT-II
ARRAYS, STRINGS AND FUNCTIONS: Introduction to Arrays: Declaration, Initialization,
Single dimensional array, Two-dimensional arrays, Array Manipulations; String operations:
length, compare, concatenate, copy; Functions: General form of a function, Function Arguments,
Built-in functions, return statement, Recursion.
2.1 IntroductiontoArrays
An array is a collection of data that holds fixed number of values of same type. For
example: if you want to store marks of 100 students, you can create an array for it.
float marks[100];
The size and type of arrays cannot be changed after its declaration.
2.1.1 Declaration
How to declare an array in C?
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold
5 floating-point values.
Elements of an Array and How to access them?
You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element ismark [0], second element is
mark [1] and so on.
1
CS1206 Common to CSE, IT,ADS. AIML Programming in C
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Example: C Arrays
// Program to find the average of n (n < 10) numbers using arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
2
CS1206 Common to CSE, IT,ADS. AIML Programming in C
sum += marks[i];
}
average = sum/n;
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
int testArray[10];
3
CS1206 Common to CSE, IT,ADS. AIML Programming in C
4 {
5 int i,number[5];
6 clrscr();
7 printf(“Enter 5 number \n”);
8 for(i=0;i<5;i++)
9 scanf(“%d”,&numbers[i]);
10 printf(“Array elements are \n”);
11 for(i=0;i<5;i++)
12 printf(“%d\n”,numbers[i]);
13 getch();
14 return 0;
15 }
Output :
4
6
7
3
2
Array elements are
4
6
7
3
2
It’s a very common error to try to refer to non-existent numbers[ 5], element. C does not do
much hand holding. It is invariably up to the programmer to make sure that programs are
free from errors. This is especially true with arrays. C does not complain if you try to write to
elements of an array which do not exist!
For example: If you wrote: numbers[5] = 6; C would happily try to write 6 at the location
which would have corresponded to the sixth element, had it been declared that way.
Unfortunately this would probably be memory taken up by some other variable or perhaps even
by the operating system. The result would be either:
The value in the incorrect memory location would be corrupted with
unpredictable consequences.
The value would corrupt the memory and crash the program completely!
The second of these tends to be the result on operating systems with proper memory protection.
Writing over the bounds of an array is a common source of error. Remember that the array limits
run from zero to the size of the array minus one.
Out of bounds access :
I would be doing well, that really shows the range of valid indices, please check often.
10, when the number of elements, all the indices of 10 or more is illegal. Also, whether any size
of negative indices is also illegal.
These errors are detected at compile time is not. It is an error at run time. However, there is no
guarantee that the error reliably. Sometimes works correctly (seems to be moving.) This is the
“luck ran” instead of “bad luck worked” so, please, as no doubt.
4
CS1206 Common to CSE, IT,ADS. AIML Programming in C
The best way to see these principles is by use of an example, so load the program and display it
on your monitor.
The elements of an array can also be initialized in the array declaration by following the
declaration with an equal sign and a comma-separated list (enclosed in braces)
of initializers.
Example:
1 #include <stdio.h>
2 #include <conio.h>
3 int main( )
4 {
5 char name[7]; /* define a string of characters */
6 name[0] = 'A';
7 name[1] = 's';
8 name[2] = 'h';
9 name[3] = 'r';
10 name[4] = 'a';
11 name[5] = 'f';
12 name[6] = '\0'; /* Null character - end of text */
13 name[7] = ‘X’;
14 clrscr();
15 printf("My name is %s\n",name);
16 printf("First letter is %c\n",name[0]);
17 printf("Fifth letter is %c\n",name[4]);
18 printf("Sixth letter is %c\n",name[5]);
19 printf("Seventh letter is %c\n",name[6]);
20 printf("Eight letter is %c\n",name[7]);
21 getch();
22 return 0;
23 }
The following program initializes an integer array with five values and prints the array.
1 #include <stdio.h>
2 #include <conio.h>
3 int main()
4 {
5 int numbers[]={1,2,3,4,5};
6 int i;
7 clrscr();
8 printf("Array elements are\n");
9 for(i=0;i<=4;i++)
10 printf("%d\n",numbers[i]);
11 getch();
12 return 0;
13 }
If there are fewer initializers than elements in the array, the remaining elements are
initialized to zero. For example, the elements of the array n could have been initialized to
zero with the declaration int n[10] = {0}; which explicitly initializes the first element to
zero and initializes the remaining nine
5
CS1206 Common to CSE, IT,ADS. AIML Programming in C
elements to zero because there are fewer initializers than there are elements in the array. It is
important to remember that arrays are not automatically initialized to zero. The
programmer must at least initialize the first element to zero for the remaining elements to be
automatically zeroed. This method of initializing the array elements to 0 is performed at
compile time for static arrays and at run time for automatic arrays.
2.3:Example
Computing mean, median and mode
What is mean ?
Mean is same as average. The mean is found by adding up all of the given data and
dividing by the number of elements.
Example: Mean of 1,2,3,4,5 is
(1+2+3+4+5 )/5 = 15/3 = 3
What is Median ?
The median is the middle number in an ordered list (ascending or descending). First you
arrange the numbers in orders in ascending order, then you find the middle number and
save it as median
Example:
12345
Median is 3
What is Mode ?
Mode is the element which happens most number of time in the list. If no element
happens more than once, all elements are considered as mode.
Algorithm
1. Start
2. Declare an array a[20], sum =0,i=0,j=0,z=0
3. Read number of terms n
4. Repeat step 5 & 6 while (i<n)
5. sum=sum+a[i]
6. next i
7. mean=sum/n
8. if(n%2=0)
median=(a[n/2]+a[n/2-1])/2 else
median=a[n/2]
9. print mean and median
10. repeat step 11 & 12 when i=0 to n, j=0 to i
11. if a[i]=a[j], then b[i]++
12. if b[i]>z, then z=b[i]
13. For i=0 to n if b[i]=z, print b[i]
14. end
Program:
#include <stdio.h>
main()
{ int i,j,x,k=0,n,a[20],z=0,b[20];
float sum=0, t,mean,medn,mod;
printf(“\n Enter the no. of elements (Max 20)\n”);
6
CS1206 Common to CSE, IT,ADS. AIML Programming in C
scanf(“%d”,&n);
printf(“Enter the elements\n”);
for(i=0;i
{scan (“%d”,&a[i]);}
for(i=0;i
{sum=sum+a[i];}
printf(“Sum: %f”,sum);
mean=sum/n;
}
for(i=0;i
{ for (j=i+1;j
{ if (a[i]>a[j])
{ t=a[i];a[i]=a[j];a[j]=t; }
}
}
if (n%2==0)
medn=(a[n/2]+a[(n/2)-1])/2; else
medn=a[n/2];
for(i=0;i
{ for ( j=0; j<i; j++ )
{ if (a[i]==a[j])
b[i]++;
}
}
for(i=0;i<n;i++)
{ if (b[i]>z)
z=b[i];
}
printf(“Mean :%f \n Median : %f \n Mean : “, mean, medn);
for I i=0; i<n; i++)
{ if (b[i]==z)
printf(“%d\t”, a[i]);
}
}
7
CS1206 Common to CSE, IT,ADS. AIML Programming in C
The following figure illustrates a two dimensional array, matrix. The array contains three rows
and tree columns, so it is said to be a 3-by-3 array. In general, an array with m rows and
n columns is called an m-by-n array.
[0][1] [2]
[0]10
[1]
[2] 10
Every element in array matrix is identified by an element name of the form matrix[ i ][ j]; matrix
is the name of the array, and i and j are the subscripts that uniquely identify each element in
matrix . Notice that the names of the elements in the first row all have a first subscript of 0; the
names of the elements in the third column all have a second subscript of 2.
In the case of Two-dimensional array, during declaration the maximum number of rows and
maximum number of column should be specified for processing all array elements. The
implementation of the array stores all the elements in a single contiguous block of memory. The
other possible implementation would be a combination of several distinct one-dimensional
arrays. That’s not how C does it. In memory, the array is arranged with the elements of
the rightmost index next to each other. In other words, matrix[1][1] comes right before
matrix[1][2] in memory.
The following array:
[0][1] [2]
[0]1 2 3
[1]4 5 6
[2]7 8 9
would be stored:
1 23 45 67 89
EXAMPLE
:
1 #include<stdio.h>
2 #include<conio.h>
3 int main()
4 {
5 int matrix [3][3],i,j,r,c;
6 clrscr();
7 printf(“Enter the order of matrix\n”);
8 scanf(“%d%d”,&r,&c);
9 printf(“Enter elements of %d * %d matrix \n”,r,c);
10 for(i=0;i<r;i++)
11 for(j=0;j<c;j++)
12 scanf(“%d”,&matrix[i][j]);
13 printf(“Given matrix:\n”);
14 for(i=0;i<r;i++)
15 {
16 for(j=0;j<c;j++)
17 printf(“%d\t”,matrix[i][j]);
18 printf(“\n”);
19 }
20 printf(“%d\t”,matrix[2][2]);
8
CS1206 Common to CSE, IT,ADS. AIML Programming in C
21 getch();
22 return 0;
23 }
Output :
Enter the order of matrix
2
2
Enter elements of 2*2 matrix
1
2
3
4
Given matrix :
1 2
3 4
2.5 Example
Matrix Operations (Addition, Scaling, Determinant and Transpose)
/* Write a Program to implement the following operations on the matrices :
1. Addition
2. Subtraction
3. Multiplication
4. Transpose */
#include<stdio.h>
#include<conio.h>
int main()
{
int m,n,a[20][20],b[20][20],i,j,sum[20][20],sub[20][20],opt,tr[20][20],opt1,ch,e,f;
printf("Note : For Addition or Subtraction , no. of rows and columns should be same and for
transpose of matrices , your first matrices entered should be the desired matrices .\n");
printf("Enter the no. of rows: ");
scanf("%d",&m);
printf("Enter the no. of columns: ");
scanf("%d",&n);
printf("Enter the Data Elements of first matrices\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
} printf("Enter the no. of rows for second matrices: ");
scanf("%d",&e);
printf("Enter the no. of columns: ");
scanf("%d",&f);
printf("Enter the Data Elements of second matrices\n");
9
CS1206 Common to CSE, IT,ADS. AIML Programming in C
for(i=0;i<e;i++)
{
for(j=0;j<f;j++)
{
scanf("%d",&b[i][j]);
}
}
do
{
if(m==e&&n==f)
{
printf("Enter 1 for addtion or subtraction of matrices\n");
if(n==e){printf("Enter 2 for multiplication of matrices\n");}
printf("Enter 3 for transpose of first matrices\n");
}
else if(m!=n&&n==e)
{
printf("Enter 2 for multiplication of matrices\n");
printf("Enter 3 for transpose of matrices\n");
}
else
{
printf("Enter 3 for transpose of first matrices\n");
}
scanf("%d",&ch);
switch(ch)
{
case 1 :
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum[i][j]=a[i][j]+b[i][j];
sub[i][j]=a[i][j]-b[i][j];
}
}
printf("Enter 1 for Addition or 2 for Subtraction: ");
scanf("%d",&opt);
switch(opt)
{
case 1 :
printf("The resultant matrices is :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",sum[i][j]);
10
CS1206 Common to CSE, IT,ADS. AIML Programming in C
}
printf("\n");
}
break;
case 2 :
printf("The resultant matrices is :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",sub[i][j]);
}
printf("\n");
}
}
break;
case 2 :
printf("The resultant matrices is : \n");
int k;
for(i=0;i<m;i++)
{
for(j=0;j<f;j++)
{ sum[i][j]=0;
for(k=0;k<m;k++)
{
sum[i][j]+=a[i][k]*b[k][j];
}
printf("%d\t",sum[i][j]);
}
printf("\n");
}
break;
case 3 :
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
tr[j][i]=a[i][j];
}
}
printf("The resultant matrices is :\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%3d",tr[i][j]);
}
printf("\n");
}
11
CS1206 Common to CSE, IT,ADS. AIML Programming in C
break; }}
while(ch>0);
getch();
}
2.6 StringsOperation
Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the '\0' at the end of the string when it initializes the
array. Let us try to print the above mentioned string −
#include <stdio.h>
int main () {
12
CS1206 Common to CSE, IT,ADS. AIML Programming in C
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string
s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in
string s1.
int main () {
13
CS1206 Common to CSE, IT,ADS. AIML Programming in C
return 0;
}
When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
14
CS1206 Common to CSE, IT,ADS. AIML Programming in C
int main()
{
... .. ...
... .. ...
functionName();
.. .. ...
... .. ...
}
The execution of a C program begins from the main() function.
When the compiler encounters functionName(); inside the main function, control of the program
jumps to
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes
inside the function definition are executed.
A function is a block of code that performs a specific task.
C allows you to define functions according to your need. These functions are known as user-
defined functions. For example:
Suppose, you need to create a circle and color it depending upon the radius and color. You can
create two functions to solve this problem:
createCircle() function
color() function
int main()
{
int n1,n2,sum;
printf("sum = %d",sum);
return 0;
}
15
CS1206 Common to CSE, IT,ADS. AIML Programming in C
In the above example, int addNumbers(int a, int b); is the function prototype which provides
following information to the compiler:
1. name of the function is addNumbers()
2. return type of the function is int
3. two arguments of type int are passed to the function
The function prototype is not needed if the user-defined function is defined before the
main() function.
2.7.2 Function definition
Function definition contains the block of code to perform a specific task i.e. in this case, adding
two numbers and returning it.
When a function is called, the control of the program is transferred to the function definition.
And, the compiler starts executing the codes inside the body of a function.
In the above example, function call is made using addNumbers(n1,n2); statement inside the
main().
16
CS1206 Common to CSE, IT,ADS. AIML Programming in C
The type of arguments passed to a function and the formal parameters must match,
otherwise the compiler throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should
be of float type.
A function can also be called without passing an argument.
Return Statement
The return statement terminates the execution of a function and returns a value to the
calling function. The program control is transferred to the calling function after return
statement.
In the above example, the value of variable result is returned to the variable sum in
the main() function
17
CS1206 Common to CSE, IT,ADS. AIML Programming in C
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type specified in function
prototype and function definition must match.
18
CS1206 Common to CSE, IT,ADS. AIML Programming in C
Remember, function name is an identifier and should be unique. This is
just an overview on user-defined function.
User-defined Function in C programming
Types of user-defined Functions
Advantages of user-defined function
1. The program will be easier to understand, maintain and debug.
2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can be
divided among many programmers.
For better understanding of arguments and return value from the function, user-
defined functions can be categorized as:
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.
The 4 programs below check whether an integer entered by the user is a prime number or not.
And, all these programs generate the same output.
void checkPrimeNumber();
int main()
{
checkPrimeNumber(); // no argument is passed to prime()
return 0;
}
// return type of the function is void becuase no value is returned from the function void
checkPrimeNumber()
{
int n, i, flag=0;
if (flag == 1)
printf("%d is not a prime number.", n);
19
CS1206 Common to CSE, IT,ADS. AIML Programming in C
else
printf("%d is a prime number.", n);
}
The checkPrimeNumber() function takes input from the user, checks whether it is a prime
number or not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside the main()function
indicates that no argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.
int main()
{
int n, i, flag = 0;
// no argument is passed to the function
// the value returned from the function is assigned to n n =
getInteger();
return 0;
}
// getInteger() function returns integer entered by the user int
getInteger()
{
int n;
return n;
}
20
CS1206 Common to CSE, IT,ADS. AIML Programming in C
The empty parentheses in n = getInteger(); statement indicates that no argument is passed to
the function. And, the value returned from the function is assigned to n. Here, the
getInteger() function takes input from the user and returns it. The code to check whether a
number is prime or not is inside the main() function.
Example #3: Argument passed but no return value
#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main()
{
int n;
return 0;
}
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
The integer value entered by the user is passed to checkPrimeAndDisplay()function. Here, the
checkPrimeAndDisplay() function checks whether the argument passed is a prime number or
not and displays the appropriate message.
21
CS1206 Common to CSE, IT,ADS. AIML Programming in C
int main()
{
int n, flag;
if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
return 0;
}
22
CS1206 Common to CSE, IT,ADS. AIML Programming in C
23
CS1206 Common to CSE, IT,ADS. AIML Programming in C
c. srand() used to set the starting point for rand()
List Of Inbuilt C Functions In Math.h File:
“math.h” header file supports all the mathematical related functions in C language. All the
arithmetic functions used in C language are given below.
List Of Inbuilt C Functions In Math.h File:
“math.h” header file supports all the mathematical related functions in C language. All the
arithmetic functions used in C language are given below.
Function Description
24
CS1206 Common to CSE, IT,ADS. AIML Programming in C
String
functions Description
25
CS1206 Common to CSE, IT,ADS. AIML Programming in C
26
CS1206 Common to CSE, IT,ADS. AIML Programming in C
2.9 Recursion
Recursion is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
NumberFactorial
The following example calculates the factorial of a given number using a recursive
function −
#include <stdio.h>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
Fibonacci Series
The following example generates the Fibonacci series for a given number using a
recursive function −
#include <stdio.h>
int fibonacci(int i) {
27
CS1206 Common to CSE, IT,ADS. AIML Programming in C
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
return 0;
}
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34
28