0% found this document useful (0 votes)
17 views42 pages

C Programming - Lecture Notes - Part - Two

The lecture notes cover arrays and strings in computer programming, detailing the definition, declaration, and initialization of one-dimensional and multi-dimensional arrays. It includes example programs for various operations such as finding the greatest and least numbers, sorting, and matrix operations. Additionally, it introduces strings as arrays of characters in C programming.

Uploaded by

Berhanu Sufa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views42 pages

C Programming - Lecture Notes - Part - Two

The lecture notes cover arrays and strings in computer programming, detailing the definition, declaration, and initialization of one-dimensional and multi-dimensional arrays. It includes example programs for various operations such as finding the greatest and least numbers, sorting, and matrix operations. Additionally, it introduces strings as arrays of characters in C programming.

Uploaded by

Berhanu Sufa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lecture Notes

on

Computer Programming
[Subject Code: CT 401]

Part Two
(Chapter 7-9)

by
Er. Bikal Adhikari
(B.E., [Link]. Engg.)
Lecturer, Kathford Int’l College of Engineering and Management
Chapter 7
Arrays and Strings
Course Outline:- -6 Hours
7.1 Defining an Array
7.2 One-dimensional Arrays
7.3 Multi-dimensional Arrays
7.4 Strings and string manipulation
7.5 Passing Array and String to function

Arrays:-
The grouping of similar types of variables is known as array. Arrays are very useful in
programming because it helps to decrease the number of variable names used in the program.
Declaring/Defining one dimensional array:-
The syntax of declaring one dimensional array is:
data_type array_name[size];
Examples:
int a[10];
The above statement declares an array of integers with size 10 and creates 10 integer variable
in a contiguous memory locations. They are a[0], a[1], a[2], a[3], a[4], a[5], …a[9].
Consider next statement,
float b[34];
The above statement declares an array of float variables with size 34 and creates 34 fractional
variables in contiguous memory locations. They are b[0], b[1], b[2], b[3], b[4], b[5], …b[33].
Similarly, we can create an array of any data types such as character, long integer, double,
long double etc depending upon our need. It is to be noted that the index of an array is always
an integer irrespective of the data type and the index of an array always starts from 0. This
implies, if size of an array is say 40, then the index ranges from 0 to 39.
Initializing one dimensional arrays:-
Array can be initialized as following:-
int a[] = {1,2,3,5,6,9,10};
the above statement declares an array of integers with name “a” and initializes its elements
i.e. a[0] to 1, a[1] to 2, a[2] to 3, a[3] to 5, a[4] to 6, a[5] to 9 and a[6] to 10. The size of array
is 7.
We can also observe that it is not necessary to explicitly state size when we simultaneously
declare and initialize an array. The compiler automatically gives the size to array.
float b[] = {1.90, 2.98,5.57, 6.67};
the above statement declares an array of floating numbers with name “b” and initializes it
elements i.e. b[0] to 1.90, b[1] to 2.98, b[2] to 5.57 and b[3] to 6.67. Here, the size of array b
is 4.
We can also write above statements by explicitly stating the size as following:
int a[7] = {1,2,3,5,6,9,10};
float b[4] = {1.90, 2.98,5.57, 6.67};

Computer Programming [CT 401] Page Number: 39 Prepared by: Bikal Adhikari
Some important programs on one dimensional Array:-
WAP to create two arrays viz. integer array and float array. Your program must
initialize the integer array to the values 1, 2, 3, 5, 6, 9, and 10 respectively. Similarly, it
must initialize float array to the values 1.90, 2.98, 5.57, and 6.67 respectively. Finally
display these initialized values.
#include<stdio.h>

int main()
{
int i;
int a[] = {1,2,3,5,6,9,10};
float b[] = {1.90, 2.98,5.57, 6.67};
printf("Printing integer array:\n");
for(i=0;i<=6;i++)
{
printf("%d\n",a[i]);
}
printf("Printing floating array:\n");
for(i=0;i<=3;i++)
{
printf("%f\n",b[i]);
}
return 0;
}
Note:
In the above program instead of following statements:
int a[] = {1,2,3,5,6,9,10};
float b[] = {1.90, 2.98,5.57, 6.67};
we could have written following:
int a[7] = {1,2,3,5,6,9,10};
float b[4] = {1.90, 2.98,5.57, 6.67};

WAP to calculate the sum and average of n integer numbers entered by the user using
array.
#include<stdio.h>

int main()
{
int n,a[10],sum=0,average,i;
printf("Enter number of terms:");
scanf("%d",&n);
for(i=0;i<n;i++)
{

Computer Programming [CT 401] Page Number: 40 Prepared by: Bikal Adhikari
scanf("%d",&a[i]);
sum=sum+a[i];
}
average=sum/n;
printf("Sum = %d and average =%d",sum,average);
return 0;
}

WAP to find greatest number among 10 numbers entered by the user


#include<stdio.h>

int main()
{
int a[10],i,greatest;
printf("Enter ten integers numbers:\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
greatest=a[0];
for(i=0;i<10;i++)
{
if(a[i]>greatest)
{
greatest=a[i];
}
}
printf("The greatest number is %d",greatest);
return 0;
}

WAP to find a greatest number among n numbers entered by the user


#include<stdio.h>

int main()
{
int a[10],n,i,greatest;
printf("Enter the number of terms:");
scanf("%d",&n);
printf("Enter %d integers numbers:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

Computer Programming [CT 401] Page Number: 41 Prepared by: Bikal Adhikari
greatest=a[0];
for(i=0;i<n;i++)
{
if(a[i]>greatest)
{
greatest=a[i];
}
}
printf("The greatest number is %d",greatest);
return 0;
}

WAP to find a least number among 10 numbers entered by the user


#include<stdio.h>

int main()
{
int a[10],i,least;
printf("Enter ten integers numbers:\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
least=a[0];
for(i=0;i<10;i++)
{
if(a[i]<least)
{
least=a[i];
}
}
printf("The least number is %d",least);
return 0;
}

WAP to find a least number among n numbers entered by the user


#include<stdio.h>

int main()
{
int n,a[20],least,i;
printf("Enter the number of terms:");
scanf("%d",&n);
for(i=0;i<n;i++)

Computer Programming [CT 401] Page Number: 42 Prepared by: Bikal Adhikari
{
printf("Enter:");
scanf("%d",&a[i]);
if(a[i]<least)
least=a[i];
}
printf("The least number is %d",least);
return 0;
}

WAP to sort n numbers entered by the user in ascending order.


#include<stdio.h>

int main()
{
int n,a[10],i,j,temp;
printf("Enter number of terms:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("The entered number in ascending order is as follows:\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
return 0;
}

Computer Programming [CT 401] Page Number: 43 Prepared by: Bikal Adhikari
WAP to sort n numbers entered by the user in descending order.
#include<stdio.h>

int main()
{
int a[20],n,i,j,temp;
printf("Enter number of terms:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("The entered number in descending order is as follows:\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
return 0;
}

Multi-dimensional arrays:-
The arrays having two or more than two indices are known as multi-dimensional arrays. In
two dimensional arrays, there are two indices.
Declaring a two dimensional array:
int a[3][3];
The above statement declares 3 × 3 = 9 values in the following order:
a[0][0], a[0][1], a[0][2],
a[1][0], a[1][1], a[1][2],
a[2][0], a[2][1], a[2][2]

Computer Programming [CT 401] Page Number: 44 Prepared by: Bikal Adhikari
Initializing two dimensional array:-
Two dimensional arrays can be initialized in the same way as we initialized one dimensional
array.
For example:
int a[3][3] = {1,2,3,4,5,6,7,8,9};
The above statement initializes the elements of a,
a[0][0], a[0][1], a[0][2],
a[1][0], a[1][1], a[1][2],
a[2][0], a[2][1], a[2][2]
respectively to
123
456
789
Some important programs on two dimensional Array:-
WAP to initialize a three by three matrix to
123
456
789
and display the initialized matrix.
#include<stdio.h>

int main()
{
int a[3][3]={1,2,3,4,5,6,7,8,9};
int i,j;
printf("The initialized matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
return 0;
}
Note:
To improve the code readability, the statement
int a[3][3]={1,2,3,4,5,6,7,8,9};
can be written as:
int a[3][3]={1,2,3,
4,5,6,
7,8,9};

Computer Programming [CT 401] Page Number: 45 Prepared by: Bikal Adhikari
WAP to read and display a matrix entered by the user
#include<stdio.h>

int main()
{
int a[3][3],i,j;
printf("Enter a 3 by 3 matrix:\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
printf("The entered matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
return 0;
}

Write a program to input a 3x3 matrix from user and display its transpose.
#include<stdio.h>

int main()
{
int a[3][3],c[3][3],i,j;
printf("Enter a matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
c[j][i]=a[i][j];
}
}
printf("Entered matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{

Computer Programming [CT 401] Page Number: 46 Prepared by: Bikal Adhikari
printf("%d ",a[i][j]);
}
printf("\n");
}

printf("Transposed matrix is:\n");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}

WAP to input two 3 x 3 matrix from the user and display the sum matrix.
#include<stdio.h>

int main()
{
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter first matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter second matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{

Computer Programming [CT 401] Page Number: 47 Prepared by: Bikal Adhikari
c[i][j]=a[i][j]+b[i][j];
}
}

printf("The sum matrix is:\n");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}

WAP to multiply two 3x3 matrices entered by the user and display the product.
#include<stdio.h>

int main()
{
int a[3][3],b[3][3],c[3][3],i,j,k,sum;
printf("Enter first Matrix:\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
printf("Enter Second Matrix:\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum=0;
for(k=0;k<3;k++)
{
sum = sum + a[i][k]*b[k][j];
}
c[i][j]=sum;

Computer Programming [CT 401] Page Number: 48 Prepared by: Bikal Adhikari
}
}
printf("The product matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}

WAP in C to multiply two matrices of different order entered by the user and display
the product. Your program should input orders of two matrices from the user and
check if the matrix multiplication is compatible.
#include<stdio.h>
#include<stdlib.h>

int main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,sum;
int m1,m2,n1,n2;
printf("Enter the order of first matrix m1 x n1:\n");
scanf("%d%d",&m1,&n1);
printf("Enter the order of second matrix m2 x n2:\n");
scanf("%d%d",&m2,&n2);
if(n1!=m2)
{
printf("The matrix multiplication is not possible!\n");
printf("Exiting...");
exit(1);
}
printf("Enter first Matrix:\n");
for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
{
scanf("%d",&a[i][j]);
}
printf("Enter Second Matrix:\n");
for(i=0;i<m2;i++)
for(j=0;j<n2;j++)
{

Computer Programming [CT 401] Page Number: 49 Prepared by: Bikal Adhikari
scanf("%d",&b[i][j]);
}
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
sum=0;
for(k=0;k<n1;k++)
{
sum = sum + a[i][k]*b[k][j];
}
c[i][j]=sum;
}
}
printf("The product matrix is:\n");
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}

Strings:-
In C programming language, string is defined as an array of characters. The syntax for
defining a string is:
char string_variable[size];
For example:
char str[20];
The above statement declares a string variable or character array with identifier str and size
20.
char name[10];
The above statement declares a string variable or character array with identifier name and
size 10.
Initializing a string:
Similar to initialization of integer or float arrays, string variable can be initialized by
initializing the character array.
For example:-
char str1[]="Pokhara";
char str2[]={'P','o','k','h','a','r','a','\0'};

Computer Programming [CT 401] Page Number: 50 Prepared by: Bikal Adhikari
WAP to initialize two strings str1 and str2 to Pokhara by using different methods and
display the initialized values of str1 and str2.
#include<stdio.h>

int main()
{
char str1[8]="Pokhara";
char str2[8]={'P','o','k','h','a','r','a','\0'};
printf("The initialized strings are: %s and %s",str1,str2);
return 0;
}

WAP to input a string from the user and display it in console


#include<stdio.h>

int main()
{
char name[20];
printf("Enter name:");
scanf("%s",name);
printf("Hello %s, this is from C Programming Console",name);
return 0;
}

WAP to read string with white space and display it in console


#include<stdio.h>

int main()
{
char name[100],ch;
int i=0;
printf("Enter a name:");
do
{
ch=getchar();
name[i]= ch;
i++;
}while(ch!='\n');
printf("Hello %s, this is from c programming console",name);
return 0;
}

Computer Programming [CT 401] Page Number: 51 Prepared by: Bikal Adhikari
WAP to input string from the user and display it in console by accessing individual
characters
#include<stdio.h>

int main()
{
char str[100];
int i=0;
printf("Enter a string:");
scanf("%s",str);
printf("The entered string is: ");
while(str[i]!='\0')
{
printf("%c",str[i]);
i++;
}
return 0;
}

String Handling Functions:-


Following are the some of the string handling functions used in C programming language:
1) strlen()
The syntax of this function is as follows:
integer_variable = strlen(str);
Where, str is a string variable
It computes length of the string str and returns its length which can be assigned to
some integer variable.
2) strrev()
The syntax of this function is as follows:
strrev(str);
Where, str is a string variable
It reverses the content of str and keeps the reversed value in str itself.
3) strcat()
The syntax of this function is as follows:
strcat(str1,str2);
where, str1 and str2 are string variables.
It concatenates two string str1 and str2 and stores the concatenated string on str1.
4) strcpy()
The syntax of this function is as follows:
strcpy(str1,str2);

Computer Programming [CT 401] Page Number: 52 Prepared by: Bikal Adhikari
where, str1 and str2 are string variables.
It copies the contents of str2 into str1.
5) strcmp()
The syntax of this function is as follows:
strcmp(str1,str2);
where, str1 and str2 are string variables.
Returns 0 if both strings are equal
Returns 1 if str1 is greater than str2
Returns -1 if str1 is less than str2

WAP to find the length of a string entered by the user using library function
#include<stdio.h>
#include<string.h>

int main()
{
int length;
char str[20];
printf("Enter a string:");
scanf("%s",str);
length=strlen(str);
printf("The length of entered string is %d",length);
return 0;
}

WAP to concatenate two strings entered by the user using the library function.
#include<stdio.h>
#include<string.h>

int main()
{
char str1[20];
char str2[20];
printf("Enter first string:");
scanf("%s",str1);
printf("Enter second string:");
scanf("%s",str2);
strcat(str1,str2);
printf("The concatenated string is: %s",str1);
return 0;
}

Computer Programming [CT 401] Page Number: 53 Prepared by: Bikal Adhikari
WAP to reverse a string entered by the user using library function
#include<stdio.h>
#include<string.h>

int main()
{
char str[30],rstr[30];
printf("Enter a string:");
scanf("%s",&str);
strrev(str);
strcpy(rstr,str);
printf("The reversed string is:%s",rstr);
return 0;
}

WAP to check a string entered by the user is Palindrome or not by using the library
function
#include<stdio.h>
#include<string.h>

int main()
{
char str[30],rstr[30];
printf("Enter a string to test: ");
scanf("%s",str);
strcpy(rstr,str);
strrev(rstr);
if(strcmp(str,rstr)==0)
printf("Palindrome");
else
printf("Not palindrome");
return 0;
}

WAP to sort names of n employees in ascending order (Alphabetical order)


#include<stdio.h>
#include<string.h>

int main()
{
char empname[20][20],temp[20];
int n,i,j;
printf("Enter number of employees:");
scanf("%d",&n);

Computer Programming [CT 401] Page Number: 54 Prepared by: Bikal Adhikari
for(i=0;i<n;i++)
{
gets(empname[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(empname[i],empname[j])>0)
{
strcpy(temp,empname[j]);
strcpy(empname[j],empname[i]);
strcpy(empname[i],temp);
}
}
}
printf("The entered names in ascending order is:\n");
for(i=0;i<n;i++)
{
puts(empname[i]);
}
return 0;
}

Useful string programs without using library functions


WAP to display the ASCII value of the character entered by the user
#include<stdio.h>

int main()
{
char ch;
printf("Enter a character:");
scanf("%c",&ch);
printf("ASCII Value of %c is %d",ch,ch);
return 0;
}

WAP to convert a string entered in lower case into uppercase without library function
#include<stdio.h>

int main()
{
char str[40];

Computer Programming [CT 401] Page Number: 55 Prepared by: Bikal Adhikari
int i=0;
printf("Enter a string:");
scanf("%s",str);
while(str[i]!='\0')
{
str[i] = str[i] -32;
i++;
}
printf("The string in upper case: %s",str);
return 0;
}

WAP to convert a string entered in upper case into lower case without library function
#include<stdio.h>

int main()
{
char str[40];
int i=0;
printf("Enter a string:");
scanf("%s",str);
while(str[i]!='\0')
{
str[i] = str[i] + 32;
i++;
}
printf("The string in lower case: %s",str);
return 0;
}

WAP to find the length of a string entered by the user without using library function
#include<stdio.h>

int main()
{
char str[40];
int i=0,length;
printf("Enter a string:");
scanf("%s",str);
while(str[i]!='\0')
{
i++;
}
length=i;

Computer Programming [CT 401] Page Number: 56 Prepared by: Bikal Adhikari
printf("The length of the entered string is %d",length);
return 0;
}

WAP to copy a string without using library function


#include<stdio.h>

int main()
{
char str1[40],str2[40];
int i=0;
printf("Enter a string:");
scanf("%s",str1);
while(str1[i]!='\0')
{
str2[i] = str1[i];
i++;
}
printf("The copied string is %s",str2);
return 0;
}

WAP to concatenate two strings entered by the user without using library function
#include<stdio.h>

int main()
{
char str1[20],str2[20],str[40];
int i=0,j=0,len1,len2;
printf("Enter first string:");
scanf("%s",str1);
printf("Enter second string:");
scanf("%s",str2);

while(str1[i]!='\0')
{
str[i] = str1[i];
i++;
}
while(str2[j]!='\0')
{
str[i] = str2[j];
i++;
j++;

Computer Programming [CT 401] Page Number: 57 Prepared by: Bikal Adhikari
}
printf("The concatenated string is %s",str);
return 0;
}

WAP to reverse a string entered by the user without using library function
#include<stdio.h>

int findlength(char str[])


{
int i=0;
while(str[i]!='\0')
{
i++;
}
return i;
}

int main()
{
char str[20],rstr[20];
int i,length;
printf("Enter a string to be reversed:");
scanf("%s",str);
length=findlength(str);
for(i=0;i<length;i++)
{
rstr[i]=str[length-i-1];
}
printf("The reversed string is %s",rstr);
return 0;
}

WAP to check whether a string entered by the user is palindrome or not without using
library function
#include<stdio.h>

int findlength(char str[])


{
int i=0;
while(str[i]!='\0')
{
i++;
}

Computer Programming [CT 401] Page Number: 58 Prepared by: Bikal Adhikari
return i;
}

int main()
{
char str[20],rstr[20];
int i,length,flag=1;
printf("Enter a string :");
scanf("%s",str);
length=findlength(str);
for(i=0;i<length;i++)
{
rstr[i]=str[length-i-1];
}
i=0;
while(i<length)
{
if(str[i]!=rstr[i])
{
flag=0;
break;
}
else
flag=1;
i++;
}
if(flag==1)
printf("Entered string is palindrome");
else
printf("Entered string is not palindrome");
return 0;
}

WAP to compare two strings entered by the user without using library function
#include<stdio.h>

int main()
{
char str1[20],str2[20];
int i=0,value;
printf("Enter first string:");
scanf("%s",str1);
printf("Enter second string:");
scanf("%s",str2);

Computer Programming [CT 401] Page Number: 59 Prepared by: Bikal Adhikari
while(str1[i]==str2[i])
{
if(str1[i]=='\0')
value=0; i++;
}
value=str1[i]-str2[i];
if(value==0)
printf("Two strings are equal.");
else if(value<0)
printf("String 1 is alphabetically before string 2");
else
printf("String 2 is alphabetically before string 1");
return 0;
}

WAP to sort names of n employees entered by the user in ascending order without using
library function
#include<stdio.h>

int comparestring(char str1[],char str2[])


{
int i=0,value;
while(str1[i]==str2[i])
{
if(str1[i]=='\0')
value=0;
}
value=str1[i]-str2[i];
return value;
}

void copystring(char *s, const char *p)


{
while ((*s++=*p++)!='\0')
{
}
}

int main()
{
char ename[40][40],temp[40];
int n,i,j;
printf("Enter the number of employees:");
scanf("%d",&n);

Computer Programming [CT 401] Page Number: 60 Prepared by: Bikal Adhikari
printf("Enter names of %d employees:\n",n);
for(i=0;i<n;i++)
{
gets(ename[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(comparestring(ename[i],ename[j])>0)
{
copystring(temp,ename[i]);
copystring(ename[i],ename[j]);
copystring(ename[j],temp);
}
}
}
printf("Employees name in sorted order is:\n");
for(i=0;i<n;i++)
{
puts(ename[i]);
}
return 0;
}

Passing Array and String to function:


Arrays and strings can be passed to function in similar way as the basic data types are passed
to the function.
For array, suppose we have declared an array “a” by following statement.
int array_variable[size];
The array can be passed to function using following syntax:
function_name(array_variable_name);
or
function_name(&array_variable_name[0]);
Example:-
findGreatest(a);
findGreatest(&a[0]);
Each of the above statements pass entire array to the function findGreatest().
For string, suppose we have declared a string variable using following syntax:
char string_variable[size];
The string_variable can be passed to a function using following syntax:
function_name(string_variable);

Computer Programming [CT 401] Page Number: 61 Prepared by: Bikal Adhikari
Example:
char str[20]; /*Declares a string str*/
scanf(“%s”,str); /*Input a string into str*/
length = findLength(str); /*Calculate and assigns to length*/
Read the following example programs carefully to gain insights on passing array and string to
function:

WAP to find the largest number among n numbers entered by the user by passing array
to function
#include<stdio.h>

int findGreatest(int [],int);

int main()
{
int a[10],n,i,greatest;
printf("Enter the number of terms:");
scanf("%d",&n);
printf("Enter %d integers numbers:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
greatest = findGreatest(a,n);
printf("The greatest number is %d",greatest);
return 0;
}

int findGreatest(int a[],int n)


{
int g,i;
g=a[0];
for(i=0;i<n;i++)
{
if(a[i]>g)
{
g=a[i];
}
}
return g;
}

Computer Programming [CT 401] Page Number: 62 Prepared by: Bikal Adhikari
WAP to find the length of the entered string by passing it to a user defined function.
#include<stdio.h>
int findLength(char []);

int main()
{
int length;
char str[20];
printf("Enter a string:");
scanf("%s",&str);
length = findLength(str);
printf("The length of entered string is %d",length);
return 0;
}

int findLength(char p[])


{
int i=0;
while(p[i]!='\0')
{
++i;
}
return i;
}

Computer Programming [CT 401] Page Number: 63 Prepared by: Bikal Adhikari
Chapter 8
Structures
Course Outline:- -4 Hours
8.1 Introduction
8.2 Processing a Structure
8.3 Arrays of Structures
8.4 Arrays within Structures
8.5 Structures and Function
Introduction to Structure:
Structure is a collection of dissimilar types of data. Use of structure in programs makes the
programs more readable and efficient.
The syntax for defining a structure is as follows:-

struct structure_name
{
type variable_name1;
type variable_name1;
type variable_name1;
type variable_name1;
};

Example:
struct student
{
char name[20];
int roll;
int marks;
char address[30];
};
The above example shows how a structure definition can be written. The above code defines
a new structure with name student embedding different variable like name, roll, marks and
address.
After a structure is defined, it can be declared in any function as follows:
struct structure_name variable_name;
Example:
struct student s;
The above statement declares a structure variable s of type student. The struct is the
keyword.
The structure variable can also be declared along with the definition as follows:-
struct student
{
char name[20];
int roll;
int marks;

Computer Programming [CT 401] Page Number: 64 Prepared by: Bikal Adhikari
char address[30];
}s;
Accessing Structure Elements
Each element of structure can be accessed by using dot (.) operator. If we have defined a
structure called student and have declared it as follows:
struct student s;
Each element of s can be accessed by using dot operator as follows:
[Link], [Link], [Link] etc.
Each of these can be treated as a separate variable. We can input value into them using
functions like scanf() and display their values using functions like printf() as follows:
scanf(“%s”, [Link]);
printf(“%s”, [Link]);
WAP to input name, roll, marks and address of a student and display the entered
information using the concept of structure
#include<stdio.h>

struct student
{
int roll;
char name[20];
float marks;
char address[40];
};

int main()
{
struct student s;
printf("Enter the details of the student:\n");
printf("Enter name:");
scanf("%s",[Link]);
printf("Enter roll:");
scanf("%d",&[Link]);
printf("Enter marks:");
scanf("%f",&[Link]);
printf("Enter address:");
scanf("%s",[Link]);
printf("The entered details of student is:\n");
printf("Name Roll Marks Address\n");
printf("%s %d %f %s",[Link],[Link],[Link],[Link]);
return 0;
}

Computer Programming [CT 401] Page Number: 65 Prepared by: Bikal Adhikari
Array of Structure
One can create an array of structure like we created an array of basic types.
For example:
struct student s[48];
The above statement declares/creates an array of structure called student with size 48. This
means 48 structures ranging from s[0], s[1],…. up to s[39] has been created at once.
The member can be accessed as s[0].name, s[0].roll, s[0].address, s[1].name, s[1].roll,
s[1].address, etc.

WAP to input and display the details of n number of students entered by the user

#include<stdio.h>

struct student
{
int roll;
char name[20];
float marks;
char address[40];
};

int main()
{
struct student s[48];
int n,i;
printf("Enter the number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the details of the student:\n");
printf("Enter name:");
scanf("%s",s[i].name);
printf("Enter roll:");
scanf("%d",&s[i].roll);
printf("Enter marks:");
scanf("%f",&s[i].marks);
printf("Enter address:");
scanf("%s",s[i].address);
}
printf("The entered details of %d students are:\n",n);
printf("Name Roll Marks Address\n");
for(i=0;i<n;i++)
printf("%s %d %f %s\n",s[i].name,s[i].roll,s[i].marks,s[i].address);

Computer Programming [CT 401] Page Number: 66 Prepared by: Bikal Adhikari
return 0;
}
Structures and Functions:
Structures can be passed to function similar to passing basic types to the function. Carefully
examine following examples to gain insights on passing structures to the function:

WAP to demonstrate passing structure to function.


#include<stdio.h>

struct student
{
char name[20];
int roll;
float marks;
char address[50];
long int ph;
};

void display(struct student);

int main()
{
struct student s;
printf("Enter name, roll no., marks, address and phone number of student:\n");
scanf("%s%d%f%s%ld",&[Link],&[Link],&[Link],&[Link],&[Link]);
display(s);
return 0;
}

void display(struct student p)


{
printf("Name Roll No. Marks Address Phone Number:\n");
printf("%s %d %f %s %ld\n",[Link],[Link],[Link],[Link],[Link]);
}

WAP to demonstrate passing structure to function by reference.


#include<stdio.h>

struct student
{
char name[20];
int roll;
float marks;
char address[50];

Computer Programming [CT 401] Page Number: 67 Prepared by: Bikal Adhikari
long int ph;
};

void display(struct student *);

int main()
{
struct student s;
printf("Enter name, roll no., marks, address and phone number of student:\n");
scanf("%s%d%f%s%ld",&[Link],&[Link],&[Link],&[Link],&[Link]);
display(&s);
return 0;
}

void display(struct student *p)


{
printf("Name Roll No. Marks Address Phone Number:\n");
printf("%s %d %f %s %ld\n",p->name,p->roll,p->marks,p->address,p->ph);
}

WAP to demonstrate passing array of structure to function.


#include<stdio.h>

struct student
{
char name[20];
int roll;
float marks;
char address[50];
long int ph;
};

void display(struct student [],int);

int main()
{
int n,i;
struct student s[48];
printf("Enter number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter name, roll no., marks, address and phone number of student:\n");

Computer Programming [CT 401] Page Number: 68 Prepared by: Bikal Adhikari
scanf("%s%d%f%s%ld",&s[i].name,&s[i].roll,&s[i].marks,&s[i].address,&s[i].ph);
}
display(s,n);
return 0;
}

void display(struct student p[], int n)


{
int i;
printf("Name Roll No. Marks Address Phone Number:\n");
for(i=0;i<n;i++)
{
printf("%s %d %f %s %ld\n",p[i].name,p[i].roll,p[i].marks,p[i].address,p[i].ph);
}
}
Structure within structure or Nested Structure:-
When a structure has a member of another type of structure, it is called nested structure.
Carefully examine following program to get an insight on nested structure:
WAP to demonstrate the concept of nested structure
#include<stdio.h>

struct class
{
char section;
int standard;
};

struct student
{
int roll;
char name[20];
struct class c;
};

int main()
{
struct student s;
printf("Enter Name:");
scanf("%s",&[Link]);
printf("Enter Roll:");
scanf("%d",&[Link]);
printf("Enter Standard:");

Computer Programming [CT 401] Page Number: 69 Prepared by: Bikal Adhikari
scanf("%d",&[Link]);
printf("Enter Section:");
scanf("%s",&[Link]);
printf("\n Name Roll No. Standard Section\n");
printf("%10s%9d%10d%8c",[Link],[Link],[Link],[Link]);
return 0;
}
Array within Structure:
When an array is a member of a structure, it is called array within structure. Carefully
examine following example to gain insights on array within structure:
WAP using structure to input name, roll, address, phone number and marks in 5
subjects of a student. Use the concept of array within structure to store marks of five
subjects. Finally display information of each student with percentage.
#include<stdio.h>

struct student
{
char name[20];
int roll;
float marks[5];
char address[50];
};

void display(struct student p[],int);

int main()
{
int n,i;
struct student s[48];
printf("Enter number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter name, roll no., and address of a student:\n");
scanf("%s%d%s",&s[i].name,&s[i].roll,&s[i].address);
printf("Enter marks in Physics:");
scanf("%f",&s[i].marks[0]);
printf("Enter marks in Mathematics:");
scanf("%f",&s[i].marks[1]);
printf("Enter marks in Chemistry:");
scanf("%f",&s[i].marks[2]);
printf("Enter marks in Biology:");
scanf("%f",&s[i].marks[3]);

Computer Programming [CT 401] Page Number: 70 Prepared by: Bikal Adhikari
printf("Enter marks in English:");
scanf("%f",&s[i].marks[4]);
}
display(s,n);
return 0;
}

void display(struct student p[],int n)


{
int i,j;
float sum[48];
for(i=0;i<n;i++)
{
for(j=0;j<5;j++)
{
sum[i]=sum[i] + p[i].marks[j];
}
}
printf(" ****************Subjects********************\n");
printf(" Name|Roll No. Address|Phy|Math|Chem|Bio|English|Percentage\n");
for(i=0;i<n;i++)
{
printf("%10s%9d%11s%4.0f%5.0f%5.0f%4.0f%8.0f%11.2f\n",p[i].name,p[i].roll,p[i].addres
s,p[i].marks[0],p[i].marks[1],p[i].marks[2],p[i].marks[3],p[i].marks[4],(sum[i]/5));
}
}

Computer Programming [CT 401] Page Number: 71 Prepared by: Bikal Adhikari
Chapter 9
Pointers
Course Outline:- -4 Hours
9.1 Introduction
9.2 Pointer declaration
9.3 Pointer arithmetic
9.4 Pointer and Array
9.5 Passing Pointers to a Function
9.6 Pointers and Structures

Introduction:
Pointers are the special types of variables that can hold or store the memory location of other
variable. Using the concept of pointer it is possible to write a very powerful and optimized
code that can be run using very less memory space especially for a resource constraint
environment.
Pointer Declaration:
The general syntax for declaring a pointer variable is:
type *variable_name;
Example: int a;
The above statement declares an integer variable called a. The compiler automatically creates
a memory location for this variable. Let’s suppose it is 2020. If we assign 5 to a by following
statement: a = 5;
the value 5 will load in memory location 2020. i.e. into a.
int *ptr;
The above statement declares a pointer variable of integer type. Complier creates a memory
location for pointer variable too. Suppose it is 5002. It can point to any integer variable.
ptr = &a;
The above statement assigns memory address of integer variable a to pointer variable ptr. The
value of ptr becomes 2020, which is the memory address of variable a. Here the pointer
variable ptr is said to have pointed to variable a.
5 a
2020
2022
2024

2026

5000
2020 ptr
5002
5004

Computer Programming [CT 401] Page Number: 72 Prepared by: Bikal Adhikari
Once pointer variable points to another variable, it can access its value using dereference
operator. For example:

int a, *ptr;
a =5;
ptr = &a;
Then the value of ptr is the memory address of a. i.e. 2020 where as the value of *ptr is the
value at the pointed memory address i.e. value at 2020 i.e. value of a.
Following example program illustrates the concept of pointer:
WAP in C to illustrate the concept of pointers
#include<stdio.h>

int main()
{
int a=5;
int *ptr;/*Declaring a pointer variable ptr.*/
ptr = &a; /*Assigning memory address of a to ptr.*/
printf("Value of a = %d\n",a);
printf("Memory location of a = %d\n",&a);
printf("Value of ptr = %d\n", ptr);
printf("Value of variable pointed by ptr = %d", *ptr);
return 0;
}

WAP in C to find the sum of two integers using the concept of pointer
#include<stdio.h>

int main()
{
int a,b,*p,*q;
printf("Enter a:");
scanf("%d",&a);
printf("Enter b:");
scanf("%d",&b);
p=&a;
q=&b;
printf("The sum of %d and %d is %d.",a,b,(*p+*q));
return 0;
}
Note:
We can create pointer to data types other than integer types. The data type of pointer and the
variable being pointed must be same. This means a pointer to a float variable must be of type
float.

Computer Programming [CT 401] Page Number: 73 Prepared by: Bikal Adhikari
Advantages of using pointer:
Following are the advantages of using pointer:
i Pointers provide direct access to memory
ii Pointers provide a way to return more than one value to the functions
iii Reduces the storage space and complexity of the program
iv Reduces the execution time of the program
v Provides an alternate way to access array elements
vi Pointers can be used to pass information back and forth between the calling function
and called function.
vii Pointers allow us to perform dynamic memory allocation and deallocation.
viii Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.
ix Pointers allow us to resize the dynamically allocated memory block.
x Addresses of objects can be extracted using pointers

Pointer Arithmetic:-
2020 ptr

2021
2022 ptr + 1
2023

3000

3001
3002
Suppose a pointer ptr is pointing an integer variable at memory location 2020. Suppose each
memory location can store 8 bits (i.e. 1 byte) of data. Then it would take two consecutive
memory locations 2020 and 2021 to store the integer data assuming an integer data takes 2
bytes of memory. One can perform arithmetic operations on the ptr variable. The statement,
ptr = ptr +1;
increases the value of ptr to 2022 instead of 2021. This is because the pointer always points
to starting address of a variable rather than intermediate one.
The statement,
ptr = ptr + 2;
increases the value of ptr to 2024.
Similarly, we can perform the decrement operations like (ptr-1), (ptr-2) etc on the pointer
variables.

Computer Programming [CT 401] Page Number: 74 Prepared by: Bikal Adhikari
WAP in C to illustrate the concept of pointer arithmetic
#include<stdio.h>

int main()
{
int a[10],*ptr,i;
ptr = &a[0];
printf("Enter 10 numbers:\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
printf("Displaying the values using pointer:\n");
for(i=0;i<10;i++)
{
printf("%d ",*ptr);
ptr=ptr+1;
}
return 0;
}
Relationship between pointer and array:-
In C, array has strong relationship with pointers.
a[0] 2020 a

2021
a[1] 2022 a+1
2023

a[2] 2024 a+2

2025
a[3] 2026 a+3

and so on..
Suppose we have an array a stored in consecutive memory locations from 2020 onwards as
shown in the figure. The base address of the array is represented by
&a[0] or simply by array name a.
This means &a[0] or a represents base address of the array which is 2020 in our example.
Thus, a is pointer to the base element a[0].
Incrementing a by 1( a + 1) it becomes pointer to the element a[1].
In general,
(a+ i) denotes a pointer to the element a[i] of an array.

Computer Programming [CT 401] Page Number: 75 Prepared by: Bikal Adhikari
WAP in C to illustrate the relationship between the array and pointer
#include<stdio.h>

int main()
{
int a[10],*ptr,i;
ptr = &a[0];
printf("Enter 10 numbers:\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
printf("Displaying the values using pointers:\n");
for(i=0;i<10;i++)
{
printf("%d ",*(a+i));
}
return 0;
}

Passing Pointer to function:-


Pointers can be passed to the function in similar ways which we used in passing basic types.
Following example program illustrates the concept of passing pointer to the function.
WAP in C to illustrate the concept of passing pointer to the function

#include<stdio.h>

void displayarray(int *);

int main()
{
int i,a[10],*ptr;
ptr=&a[0];
printf("Enter 10 numbers:\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
displayarray(ptr);
return 0;
}

void displayarray(int *p)

Computer Programming [CT 401] Page Number: 76 Prepared by: Bikal Adhikari
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",*p);
p=p+1;
}
}

Pointer to function:-
In C, it is possible for a pointer variable to point to a function apart from other data types. If a
pointer points to a function, it can be used to call that function without explicitly using
function name in the function call. Closely examine following program to gain the insights:
WAP to illustrate the concept of pointer to a function
#include<stdio.h>

int addition(int , int);

int main()
{
int a,b,sum;
int (*ptr) (int,int);
ptr=&addition;
printf("Enter first number:");
scanf("%d",&a);
printf("Enter second number:");
scanf("%d",&b);
sum=ptr(a,b); /*Function Call*/
printf("The sum is %d",sum);
return 0;
}

int addition(int p, int q)


{
int s;
s = p + q;
return s;
}

Computer Programming [CT 401] Page Number: 77 Prepared by: Bikal Adhikari
Pointers and Structures:-
Pointers can be used to pass structure by reference to the function. Examine the following
example program carefully:
WAP to input and display the details of n number of students entered by the user by
passing structure to the function
#include<stdio.h>

struct student
{
int roll;
char name[20];
float marks;
char address[40];
};

void display(struct student *);

int main()
{
struct student s;
printf("Enter the details of the student:\n");
printf("Enter name:");
scanf("%s",[Link]);
printf("Enter roll:");
scanf("%d",&[Link]);
printf("Enter marks:");
scanf("%f",&[Link]);
printf("Enter address:");
scanf("%s",[Link]);
display(&s);
return 0;
}

void display(struct student *p)


{
printf("The entered details of the student is:\n");
printf("Name Roll Marks Address\n");
printf("%s %d %f %s\n",p->name,p->roll,p->marks,p->address);
}

Computer Programming [CT 401] Page Number: 78 Prepared by: Bikal Adhikari
Write the output of the following program. -2068 Baisakh
#include<stdio.h>
#include<conio.h>

void main()
{
int k;
int a[]={1,2,3},*b[3],**c[3];
int ***d[3],****e[3],*****f[3];
clrscr();
for(k=0;k<3;k++)
{ b[k]=a+k; c[k]=b+k; d[k]=c+k;
e[k]=d+k; f[k]=e+k;
}
for(k=0;k<3;k++)
{
printf("%3d ",*b[k]); printf("%3d ",**c[k]);
printf("%3d ",***d[k]); printf("%3d ",****e[k]);
printf("%3d\n",*****f[k]);
}
}

OUTPUT:
11111
22222
33333

Computer Programming [CT 401] Page Number: 79 Prepared by: Bikal Adhikari

You might also like