0% found this document useful (0 votes)
5 views64 pages

Module 2 (Proc)

The document provides an overview of control structures in programming, specifically focusing on the do-while and for loops, including their syntax and examples. It also covers arrays, detailing one-dimensional and two-dimensional arrays, their initialization, and various operations such as reading, printing, summing, and manipulating array elements. Additionally, it includes examples of programs that demonstrate these concepts in practice.

Uploaded by

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

Module 2 (Proc)

The document provides an overview of control structures in programming, specifically focusing on the do-while and for loops, including their syntax and examples. It also covers arrays, detailing one-dimensional and two-dimensional arrays, their initialization, and various operations such as reading, printing, summing, and manipulating array elements. Additionally, it includes examples of programs that demonstrate these concepts in practice.

Uploaded by

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

Module - II

It

Do-While loop
Syntax :

do
{
statement 1; }
statement 2; } Body of the loop
..... }
.....
......
statement n;
}
while ( test-condition );
statement X;

The do-while statement is also called an exit-controlled statement.


Whereas, While statement is an entry-controlled statement.
Once, control will enter the loop and it executes all statements within the
loop, then it checks the test-condition. If the test condition is true again
control will go back to the loop.
Repeatedly it executes the statements until the test-condition becomes false.
If, the condition fails, the control will come out of the loop.
Example 1 : Program to print name of the branch ‘N’ times:
#include<stdio.h>
main( )
{
int i=1,n;
printf ( "Enter the value of n \n" );
scanf ( "%d", &n );
do
{
printf ( "Computer Science and Engineering \n" );
i++;
} while( i <= n );
}

Example 2: Program to find the sum of all numbers from 1 to N using


do-while statement.

#include<stdio.h>
main()
{
int i=1,n,sum=0;
printf(“Enter the value of n \n”);
scanf(“%d”, &n);
do
{
sum=sum+i;
i++;
} while ( i <= n );
printf(“Sum of 1 to N numbers=%d”,sum);
}
Example 3: Find whether the given number is palindrome or not.

#include<stdio.h>
main( )
{
int i, num, rev=0, digit, temp;
printf(“Enter the number \n”);
scanf(“%d”, &num);
temp=num;
do
{
digit = num % 10;
rev = rev * 10 + digit ;
num = num / 10;
} while ( num !=0 );

if ( rev == temp )
printf(“The given number is palindrome \n”);
else
printf(“The given number is not palindrome \n”);
}

Example 4: Generate Fibonacci Series upto the given number.

#include <stdio.h>
main()
{
int i=1,n,f1=0,f2=1,f3;
printf(“Enter the value of n \n”);
scanf(“%d”, &n);
printf(“%d%d”,f1,f2);
do
{
f3 = f1 + f2;
printf ( “ %d”, f3);
f1 = f2;
f2 = f3;
i++;
} while (i<=n);
}
Difference between while and do-while loops:

While loop Do-while loop


while(test-condition) do
{ {
1. ….. ….
.….. ….
} } while(test-condition);

2. Entry controlled loop Exit controlled loop


3. Top testing Bottom testing
First, it enters the body
4. If,the test condition is false it will not of the loop and executes
execute the body of the loop even the statements which are
once. present in a loop.

The loop will not be executed even The loop will be


once, if the condition becomes false. executed at least once,
even the test condition is
false.

The FOR Statement


The For loop is another entry-controlled loop that provides a more concise
loop control structure and which will be used most commonly.

Syntax:
for (initialization; test-condition; increment or decrement)
{

… // Body of the loop
}
Example code 1 :
for( i=1; i<=10; i++)
{
printf(“%d”, i);
}

The execution of the for statement is as follows:

1. Initialization of the control variables is done first, using assignment


statements such as i=1 and count=0. The variable i and count are
known as loop-control variables.

2. The value of the control variable is tested using the test-condition. The
test-condition is a relational expression , such as i<10 that determines
when the loop will exit. If the condition is true, the body of the loop is
executed, otherwise the loop is terminated and the execution continues
with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back
to the for statement after evaluating the last statement in the [Link]
the control variable is incremented using an assignment statement such
as i++ and the new value of the control variable is again tested ,
whether it satisfies the loop condition. If the condition is satisfied, the
body of the loop is again executed. This process continues till the value
of the control variable fails to satisfy the condition .

Example code 2 :

for ( x=0; x<9;x++)


{
printf( “%d ”, x);
}

This loop is executed 10 times and prints the digits from 0 to 9 in one line.

Another unique aspect of for loop is that one or more sections can be
omitted, if necessary.
Consider the following example:

m = 5;
for ( ; m!= 100 ; )
{
printf(“%d \n”, m);
m = m+5;
}

Example 1:
Calculate the sum of all numbers from 1 to N using a for loop.

#include<stdio.h>
main( )
{
Int i,n,sum=0;
printf(“Enter the value of n \n”);
scanf(“%d”, &n);
for(i=1; i<=n; i++)
{
sum = sum + i;
}
printf (“Sum = %d”,sum);
}

Example 2:
Program to generate a multiplication table using for loop.
#include<sdtio.h>
main( )
{
int i,n,p;
printf(“Enter the table number \n”);
scanf(“%d”, &n);
for(i=1; i<=10; i++)
{
p = n * i;
printf(“%d * %d = %d”, n, i, p);
}
}

Example 3: Program to sum all the numbers between 10 to 20.


#include<sdtio.h>
main( )
{
int i,sum=0;
for(i=10; i<=20; i++)
{
sum = sum + i;
}
printf (“SUM = %d”, sum);
}

Module-III
ARRAYS
An array is a group of related data items that share a common name. I.e it is
a collection of homogeneous data items.

Syntax : datatype array_name[size];

Example: int students [50];


Here, “students” is an array name having 50 elements.

1. One dimensional array. (Single dimensional)


2. Two dimensional array. (Double dimensional)
3. Multi dimensional array.

One-dimensional array:

A list of items can be given one variable name using only one subscript.
The subscript can begin with number 0.

int x[5];
means x[0], x[1], x[2], x[3], x[4];
If, we want to represent a set of five numbers say [10,20,30,40,50), by an
array variable num, then we may declare the variable num as follows:

int num[5];
The computer reserves five storage locations as follows :

The values to the array elements can be assigned as follows:


num[0] = 10;
num[1] = 20;
num[2] = 30;
num[3] = 40;
num[4] = 50;

10

20

30

40

50
Initialization of Arrays:
1) Compile time initializationb sh
2) Run time initialization

Compile time initialization:


We can initialize the elements of arrays in the same way as an ordinary
variable when they are declared.

The general form of initialization of array is:


static type array_name[size] = { list of values};
(static is optional)

static int a[3] = { 1, 2, 3 };


static float b[4] = {1.5, 2.5, 3.5, 4.5};
static char c[4] = { ‘g’, ’o’, ’o’, ’d’ };
The size can be omitted. In such cases, the compiler allocates enough space
for all initialized elements.
static int count [ ] = { 11,12,13,14};

Run time initialization:


(After the execution of the program values will be given)

Example 1 :
Program to read and print a set of integer numbers using arrays.

#include<stdio.h>
main( )
{
Int i,n,a[10];
printf(“Enter the size of an array \n”);
scanf(“%d”, &n); // if, n=5
printf(“enter the elements of array \n”):
for(i=1; i<=n; i++)
{
scanf (“%d”, &a[i]); // 5 elements have be entered
}
printf(“ Array elements are \n”);
for (i=1; i<=n; i++)
{
printf (“%d \n”, a[i]); // It will print all the array elements
}
}

Output:

Enter the value of n


5

Enter the elements of an array


11 12 13 14 15
Array elements are
11
12
13
14
15

Example 2: Calculate sum of all the elements from an array.

#include<stdio.h>
main( )
{
int i, n, sum=0, a[10];
printf(“Enter the size of an array \n”);
scanf(“%d”, &n); // if, n=4
printf(“enter the elements of array \n”):
for(i=1; i<=n; i++)
{
scanf (“%d”, &a[i]); // 4 elements have be entered
}
printf(“ Sum of array elements is \n”);
for (i=1; i<=n; i++)
{
sum= sum+a[i]; // It will add all array elements
}
printf (“%d”, sum);
}

Output:

Enter the value of n


4

Enter the elements of an array


1 2 3 4

Sum of array elements is


10
Example 4: Lab program

Create an array of integers. Search a given element from the array and change the
existing number by the given number.

#include<stdio.h>
main( )
{
int i, n, a[10], key, new;
printf ("Enter the size of an array \n" );
scanf("%d", &n);
printf("Enter the elements\n");
for(i=1;i<=n;i++)
{
scanf("%d", &a[i]);
}
printf ("The given array is \n");
for(i=1;i<=n;i++)
{
printf("%d ", a[i]);
}
printf("Enter the number to be searched \n");
scanf("%d", &key);
for(i=1;i<=n;i++)
{
if(key == a[i])
{
printf("Enter a new element\n");
scanf("%d",&new);
a[i]=new;
}
}
printf ("The key element is replaced by new element\n");
for(i=1;i<=n;i++)
{
printf("%d ", a[i]);
}
}
Example 5: Lab program
Program to print a pascal triangle.

#include<stdio.h>
main()
{
int rows, value=1, i, j, k;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i=0; i<rows; i++)
{
for (j=1; j<rows-i; j++)
printf(" ");
for (k=0; k<=i; k++)
{
if (k==0 || i==0)
value = 1;
else
value=value*(i-k+1)/k;
printf("%4d", value);
}
printf("\n");
}
}
Example 6: Lab program

Calculate the average, variance, standard deviation of a given array of


elements

#include <math.h>
#define MAX 10
main()
{
int i, n, a[MAX];
float avg, var, sd, deviation, sum=0, sumsqr =0;
printf("Enter the value of n \n");
scanf("%d", &n);
printf("Enter %d real numbers\n",n);
for(i=1; i<=n; i++)
{
scanf("%d", &a[i]);
}

for(i=1; i<=n; i++)


{
sum = sum + a[i];
}
avg = sum / n;

for(i=1; i<=n; i++)


{
deviation = a[i] - avg;
sumsqr = sumsqr + deviation * deviation;
}
var = sumsqr/ n;
sd = sqrt(var);
printf("Average of all elements = %.2f\n", avg);
printf("Variance of all elements = %.2f\n", var);
printf("Standard deviation = %.2f\n", sd);
}

Example 7:
Program to sort a list of elements using arrays.

#include<stdio.h>
main( )
{
Int i,j,n,a[50];
printf( “Enter the size of an array \n”);
scanf(“%d”,&n);
printf(“Enter the elements\n”);
for(i=1; i<=n; i++)
scanf(“%d”,&a[i]);

for(i=1;i<=n-1;i++)
{
for(j=1; j<=n-1; j++)
{
If ( a[j] <= a[ j+1] ) // comparing each element in an array
{
t= a[j];
a[j] = a[j+1];
a[j+1]= t;
}
}
}

for(i=1; i<=n; i++)


printf(“%d \n”, a[i]); // sorted array in ascending order
}
}

Two dimensional array


Till now we have discussed the array variables that can store a list of values.
There would be a situation where a table of values will have to be stored.

For example matrix: number of rows and columns.

C allows us to define such tables of items by using two dimensional arrays.


Two dimensional array can be declared as follows:

Syntax:
datatype array_name [row_size] [column_size];

Ex: int a[3] [3];

In this above example a is an array name with three rows and three columns.

Initialization of two dimensional array: (at Compile time)


Static int a[2][3] = {0,0,0,1,1,1};
Initialized the elements of the first row to zero and the second row to one.
Initialization is done row by row.
The above statement is equivalent to static int a[2][3] = {0,0,0}, {1,1,1} };

We can also write a two dimensional array in the form of a matrix as shown
below.

Static int a[2][3] = {


{0,0,0},
{1,1,1}
};

Example 1: Program to read and print a matrix having 3 x 3 dimension.


#include<stdio.h>
main( )
{
Int i, j, m, n, a[5][5];
printf( “Enter the size of the matrix \n”);
scanf(“%d %d”,&m,&n);
printf(“Enter the elements\n”);
for ( i=1; i<=m; i++ )
{
for( j=1; j<=n; j++ )
{
scanf (“%d”, &a[i] [j] );
}
}
for( i=1; i<=m; i++ )
{
for( j=1; j<=n; j++ )
{
printf (“%d ”, a[i] [j] );
}
}
}

Example 2:
Program to calculate sum of all the elements in a given matrix.
#include<stdio.h>
main( )
{
Int i, j, m, n, a[5][5],sum=0;
printf( “Enter the size of the matrix \n”);
scanf(“%d %d”,&m,&n);
printf(“Enter the elements\n”);
for ( i=1; i<=m; i++ )
{
for( j=1; j<=n; j++ )
{
scanf (“%d”, &a[i] [j] );
}
}
for( i=1; i<=m; i++ )
{
for( j=1; j<=n; j++ )
{
sum = sum +a[i][j];
}
}
printf(“SUM = %d”, sum);
}
Example 3:
Program to find the sum of diagonal elements in a given matrix.
#include<stdio.h>
main( )
{
Int i, j, n, a[5][5],sum=0;
printf( “Enter the size of the matrix \n”);
scanf(“%d”, &n);
printf(“Enter the elements\n”);
for ( i=1; i<=n; i++ )
{
for( j=1; j<=n; j++ )
{
scanf (“%d”, &a[i] [j] );
}
}
for( i=1; i<=n; i++ )
{
for( j=1; j<=n; j++ )
{
If ( i == j) // Row number equal to Column
number
sum = sum +a[i][j];
}
}
printf(“Sum of diagonal elements = %d”, sum);
}

Example 4: Program to print Upper triangle and Lower triangle from a given matrix.
#include<stdio.h>
main( )
{
int i, j, n, a[5][5] ;
printf( “Enter the size of the matrix \n”);
scanf(“%d”, &n);
printf(“Enter the elements \n”);
for ( i=1; i<=n; i++ )
{
for( j=1; j<=n; j++ )
{
scanf (“%d”, &a[i] [j] );
}
}
for( i=1; i<=n; i++ )
{
for( j=1; j<=n; j++ )
{
if ( i != j) // Row number is not equal to Column number
printf(“%d ”, a[i][j]);
}
printf(“\n”);
}
}

Example 5: Program to calculate sum of two given matrices.


#include<stdio.h>
main( )
{
int i, j, m, n, a[5][5], b[5][5], c[5][5] ;
printf( “Enter row size and column size \n”);
scanf(“%d %d”, &m,&n);
printf(“Enter the elements of first matrix \n”);
for ( i=1; i<=m; i++ )
{
for( j=1; j<=n; j++ )
{
scanf (“%d”, &a[i] [j] ); // Reading first matrix
}
}

printf(“Enter the elements of second matrix \n”);


for( i=1; i<=m; i++ )
{
for( j=1; j<=n; j++ )
{
scanf (“%d”, &b[i] [j]); // Reading second matrix
}
}

for( i=1; i<=m; i++ )


{
for( j=1; j<=n; j++ )
{
c[i][j]=a[i][j] + b[i][j]; // adding two matrices
}
}

printf(“The Resultant Matrix \n”);


for( i=1; i<=m; i++ )
{
for( j=1; j<=n; j++ )
{
printf(“%d “, c[i][j]); // Displaying the Resultant
matrix
}
printf(“\n”);
}
}

Example 6 : Write a C program to compute the product of A[mxn] and B [pxq]


matrices

#include<stdio.h>
int main ( )
{
int m, n, p, q, i, j, k, A[10][10], B[10][10],C[10][10] ;
printf ("Enter number of rows and columns of first matrix (less than 10) \n");
scanf ("%d %d", &m, &n);
printf ("Enter number of rows and columns of second matrix (less than 10) \n");
scanf ("%d %d", &p, &q);
if (p==n)
{
printf ("Enter the elements of First matrix \n");
for (i=1; i<=m;i++)
for (j=1; j<=n;j++)
scanf ("%d",&A[i][j]);
printf ("First Matrix is: \n");
for (i=1; i<=m;i++)
{
for (j=1; j<=n;j++)
{
printf ("%d\t",A[i][j]);
}
printf ("\n");
}
printf ("Enter the elements of Second matrix \n");
for (i=1; i<=p;i++)
for (j=1; j<=q;j++)
scanf ("%d", &B[i][j]);
printf ("Second Matrix is: \n");
for (i=1; i<=p; i++)
{
for (j=1; j<=q; j++)
{
printf ("%d\t",B[i][j]);
}
printf ("\n");
}
for (i=1; i<=m; i++)
{
for (j=1; j<=q; j++)
{
C[i][j] = 0;
for (k=1; k<=m; k++)
{
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
printf ("The product of matrix A & B: \n");
for (i=1; i<=m; i++)
{
for (j=1; j<=q; j++)
{
printf ("%d\t",C[i][j]);
}
printf ("\n");
}
}
else
{
printf ("Matrix multiplication cannot be done");
} }
STRING handling functions
A String is an array of characters. Any group of characters defined between
double quotation marks is a constant string.
Example : “Computer Science”.

The common operations performed on character string are:

➢ Reading and Writing strings


➢ Combining strings together
➢ Copying one string to another
➢ Comparing strings for equality
➢ Extracting a portion of a string

Declaring and initializing string variable

The general form : char string_name[size];

The size determines the number of characters in the string_name.

Example: char city[15];


char name[20];

When the compiler assigns a character string to a character array, it


automatically supplies a null character(‘\0’) at the end of the string. Hence,
the size should be equal to the maximum number of characters in the string
plus one.

Character array can be initialized while declaring:

static char city[9] = “NEW YORK” ;


static char city[9] = { ‘N’, ’E’, ’W‘, ‘ ‘,‘Y’, ’O’, ’R’, ’K’ };

static char string [ ] = { ‘G’, ’O’, ’O’, ’D’, ’\0’};


Example 1: Reading strings from Terminal

#include<stdio.h>
#include<string.h>
main()
{
char w1[10],w2[10] ;
printf(“Enter the text \n”);
scanf(“%s %s”, w1,w2);
printf(“\n”);
printf(“Word1 = %s”, w1);
printf(“Word2 = %s”, w2);
}

Example 2: Program to read a line of text from Terminal

#include<stdio.h>
#include<string.h>
main( )
{
char line[80], character ;
int c = 0;
printf(“Enter the text \n”);
do
{
character = getchar();
line[c] = character;
c++;
}
while (character != ‘\n’);
c = c-1;
line[c] =’\0’;
printf(“ \n %s\n”, line);
}
Example 3: Write a program to print our country name in different formats.

#include<stdio.h>
#include<string.h>
main( )
{
static char country[5] = "INDIA";
printf("%s\n",country);
printf("%-5.3s\n",country);
printf("%5.2s\n",country);
printf("%-5.0s\n",country);
printf("%.4s\n",country);
}

Output:
INDIA
IND
IN

INDI

Example 4: Develop a C program to convert from upper case to lower case letters
using string functions.

#include<stdio.h>
#include<string.h>
int main()
{
char a[25];
int i, j=0;
printf("Enter the string \n");
gets(a);
for(i=0; a[i] != '\0'; i++)
{
j=j+1;
}
for(i=0; i<=j; i++)
{
if(a[i] >= 65 && a[i] <= 90)
{
a[i] = a[i] + 32;
}
else
if (a[i] >= 97 && a[i] <= 122)
{
a[i] = a[i] - 32;

}
}
puts(a);
}

Output:

Enter the string


WELCOME
welcome

Enter the string


pdacek
PDACEK

Arithmetic operations on characters:

The C language allows us to manipulate characters the same way we do with numbers.
Whenever a character constant or character variable is used in an expression, it is
automatically converted into an integer value by the system. The integer value depends on
the local character set of the system.

To write a character in its integer representation, we need to write it as an integer.

For example : x = ‘a’;


printf”%d”, x);

It will display the number 97on the screen. (97 is the ASCII value of a ).

ASCII = American Standard Code for Information Interchange

x = ‘z’-1;
printf(“%d”,x);

It prints 121. (122-1=121)


Refer to the ASCII table from the textbook.
Alphabet ASCII value Alphabet ASCII value

A 65 a 97

B 66 b 98

.. .. .. ..

Z 97 z 122

Blank space 32

The C library supports a function that converts a string of digits into their integer
values. The function takes the form as follows:

x = atoi(string)

X is an integer variable and string is a character array containing a string of digits.

number =”2020”;
year = atoi(number);

String handling functions:

Function Action
strcat( ) Concatenates two strings

strcmp( ) Compares two strings

strcpy( ) Copies one string over another

strlen( ) Finds the length of a string

➢ strcat( ) function : The strcat function joins two strings together.

General form is strcat (string1,string2);


String1 and string2 are character arrays. When the function strcat is executed, string2 is
appended to string1. It does so by removing the null character at the end of the string1
and placing string2 from there. The string2 remains unchanged.

Example :
S1 =
V E R Y \0

S2 =
G O O D \0

: strcat (S1,S2) ;

S1 =
V E R Y G O O D \0

S2 =
G O O D \0

strcat (strcat(string1,string2),string3);

This statement concatenates all the three strings together.

➢ strcmp( ) function :

The strcmp function compares two strings identified by the arguments and has a
value 0 if they are equal. If they are not, it has the numeric difference between the
first non- matching characters in the strings.

Syntax : strcmp (string1,string2);

string1 and string2 may be string variable or string constants.

strcmp (name1,name2);
strcmp(name1,”John”);
strcmp(“Ram”, “Rahim”);

Example :

x = strcmp(“PDA”,”PDA”);
It returns value zero, because both strings are equal.

x= strcmp(“their”,”there”);
It returns a value -9 which is the numerical difference between ASCII “i” and
ASCII “r”. That is, “i” minus “r” in ASCII code is -9.

➢ strcpy( ) function :

The strcpy function works almost like a string-assignment operator. It assigns the
contents of string2 to string1, string2 may be a character array variable or a string
constant.

Syntax: strcpy(string1, string2);

Example : strcpy(city,”DELHI”);

It assigns the string “DELHI” to the string city.

➢ strlen() function:
The function counts and returns the number of characters in a string.

n = strlen(string);
Where n is an integer variable which receives the value of the length of the
string.
Example: n= strlen(“Professor”);
It returns the value 9.

Module-IV

USER-DEFINED FUNCTIONS
C functions can be classified into as two categories:

1. Library functions
2. User-Defined functions.

printf(), scanf(), sqrt(), strcat() etc are the examples of library functions.
main() is the user defined function.

Need for User-defined functions:


When our program is too large and complex and as a result the task of debugging, testing
and maintaining becomes very difficult.

If a program is divided into functional parts, then each part may be independently coded
and later combined into a single unit. These subprograms are called “functions”.

Advantages of using functions:

1. It facilitates top-down modular programming.


2. The length of a source program can be reduced by using functions.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs.

The general form of a c function:

function_name( argument list)


argument declaration;
{
local variable declarations;
executable statement1;
executable statement2;
...

return(expression);
}

Calling a function :

A function can be called by simply using the function name in a statement.

Example:

main()
{
int p;
p = mult(10,5);
printf(“%d”, p);
}
Here, mult is the function name and 10,5 are the arguments.

CATEGORY OF FUNCTIONS:

A function, depending on whether arguments are present or not and whether


a value is returned or not, may belong to one of the following categories.

1. Function with no arguments and no return values.


2. Function with arguments and no return values.
3. Function with arguments and return values.
4. Function with multiple return values.

● Function with no arguments and no return values:

No arguments

Calling Called
Function Function
(main/UDF) (UDF)

No return value

When a function has no arguments, it does not receive any data from the
calling function. Similarly, when it does not return a value, the calling function
does not receive any data from the called [Link] is no data transfer
between the calling and called function.

Example:
Program to calculate simple interest using first category function.

#include<stdio.h>
main()
{
simple_interest();
}
simple_interest()
{
int p,t,r;
float si;
printf(“enter the p,t,r values \n”);
scanf(“%d %d %d”, &p,&t,&r);
si = (p * t * r)/100;
printf(“Simple Interest = %f”, si);
}

● Function with arguments but no return value:

Values of arguments
Calling
Function Called
(main/ Function
UDF) (UDF)
No return value

In this category of function, we can make the calling function(main function)


to read data from the terminal and pass it on to the called function. The
nature of data communication between calling and called function with
arguments but no return value.
Example:
Program to calculate simple interest using second category function.

#include<stdio.h>
main()
{
int p,t,r;
printf("Enter the values of p,t,r \n");
scanf("%d%d%d", &p,&t,&r);
simple_interest(p,t,r);
}
simple_interest(p,t,r)
int p,t,r;
{
float si;
si = (p * t * r)/100;
printf("Simple Interest = %f", si);
}

● Function with arguments and with return values:

With argument values

Calling Called
function function
(main/UDF) (UDF)
With return values

In this 3rd category function, data will pass through the calling function to the
called function. The called function simply receives the data, calculates the
result and sends the value to the main function. i.e., reading the data and
printing the result will be performed by the main function.
Example :
Program to calculate simple interest using with arguments and with
return value( 3rd category function).

#include<stdio.h>
main()
{
int p,t,r;
float si;
printf("Enter the values of p,t,r \n");
scanf("%d%d%d", &p,&t,&r);
si= simple_interest(p,t,r);
printf("Simple Interest = %f", si);
}
simple_interest(p,t,r)
int p,t,r;
{
float si;
si = (p * t * r)/100;
return(si);
}
● Function with Multiple return values:

This category of function is also the same as the 3rd category function, but
with multiple return values. In this type data is supplied by the main function
and the result will be printed in the main function itself. The sub function only
perform the calculation and returns the values to the main.

Example : Program to find the largest of two numbers.

#include <stdio.h>

int main()
{
int a,b,big;
scanf("%d%d",&a,&b);
big=large(a,b);
printf("Largest = %d",big);
}
large(a,b)
int a,b;
{
if(a>b)
return(a);
else
return(b);
}

Recursion:
When a called function in turn calls another function a process of
“chaining” occurs. Recursion is a special case process of calling the
function, where the function calls itself.

Example:

main( )
{
printf(“ Welcome to Recursion \n”);
main( );
}

When the above code is executed, this will produce an output


infinitely.

Welcome to Recursion
Welcome to Recursion
Welcome to Recursion
Welcome to Recursion
Welcome to Recursion
Welcome to Recursion
Welcome to Re…..
….
….

Execution is terminated abruptly; otherwise the execution will


continue indefinitely. So, we need to use some test condition to
control the execution.

Example: Finding the factorial of a given number using recursion.

#include<stdio.h>
main( )
{
int num,fact;
int factorial(int n);
printf(“Enter the number\n”);
scanf(“%d”,&num);
fact=factorial(num); // function name with one parameter
printf(“Factorial = %d”, fact);
}
int factorial(int n) // called function
{
int f;
if(n == 0)
return(1);
else
f = n * factorial(n-1); // The function calls itself
return(f);
}
Structures:
The ‘C’ language supports a constructed data type known as
structure,which is a method for packing data of different types. A
structure is a convenient tool for handling a group of logically related
data items. It is a collection of heterogeneous data items which
share a common name.

Syntax :

struct tag_name
{
datatype member1;
datatype member2;
...
...
...
};
Example :

struct book_bank
{
char title[25];
char author[20];
int pages;
float price;
};

The keyword struct declares a structure to hold the details of four fields,
namely title,author,pages,price. These fields are called structure
elements or members. Each member may belong to a different type of
data. book_bank is the name of the structure or tag name.

We can declare structure variables using the tag name anywhere in the
program.

struct book_bank book1, book2, book3;

Each one of these variables has four members.

struct book_bank
{
char title[25];
char author[20];
int pages;
float price;
};
struct book_bank book1, book2, book3;

It is also allowed to combine both the template declaration and


variables declaration in one statement as shown in below.

struct book_bank
{
char title[25];
char author[20];
int pages;
float price;
} book1, book2, book3;

The use of tag name is optional for example:

struct
{
…….
…….
……
} book1, book2, book3;

GIVING VALUES TO MEMBERS:

We can assign values to the members of a structure in a number of


ways. The members themselves are not variables. They should be
linked to the structure variables in order to make them meaningful
members.

Accessing the members form a structure:

The word title has no meaning whereas the phrase ”title of book3” has a
meaning. The link between a member and a variable is established using the
member operator ‘.’ which is also known as ‘dot operator’ or ‘period operator’.

Example: [Link]

It is the variable representing the price of book1 and can be treated like any
other ordinary variable.

Here is how we would assign values to the members of book1:

strcpy([Link], “BASIC”);
strcopy([Link], “ Balaguruswamy”);
[Link] = 250;
[Link] = 500.25;
We can also use scanf statement to give the values through the keyboard.
The following are the valid input statements.

scanf(“%s”, [Link]);
scanf(“%s”, [Link]);
scanf(“%d”, &[Link]);
scanf(“%f”, &[Link]);

Structure initialization:
Like any other data type structure variable can be initialized.

Example:

main( )
{
static struct
{
int weight;
float height;
}
student = {62, 180.25};
…..
…..
}

This assigns the value 62 to [Link] and 180.25 to


[Link]. There is a one-to-one correspondence between the
member and their initializing values.

A lot of variation is possible in initializing a structure. The following


statement initializes two structure variables. In this case, it is essential
to use the tag name.
Example:

main( )
{
struct st_record
{
int weight;
float height;
};
struct st_record student1 = {62, 180.25};
struct st_record student2 = {70, 185.75};
}
Comparison of structure variables:

Two variables of the same structure type can be compared the same
way as ordinary variables.
If person1 and person2 belong to the same structure , then the
following operations are valid.

Operation Meaning

person1 = person2 Assigns person2 to person1

person1 == person2 Compares all members of


person1 and person2 and
return 1 if they are equal,
0 otherwise.

person1 != person2 Return 1 if all the members are


not equal , 0 otherwise.
Module - V
Pointers:
Pointer is an important feature and powerful tool in ‘C’ language.
Pointer is a variable which holds the address of another variable.

There are a number of reasons for using pointers.

1. A pointer enables us to access a variable that is defined outside the


function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
5. The use of a pointer array to character strings results in saving of data
storage space in memory.

Understanding Pointers:
Memory organization :

Consider the following statement.


Int quantity = 250;
This statement instructs the system to find a location for the integer variable
quantity and puts the value 250 in that location. Let us assume that the
system has chosen the address location 5000 for quantity.

It can be represented as follows:

quantity Variable

250 Value

5000 Address

Fig 2: Representation of a variable

During the execution of the program the system always associates the name
quantity with the address 5000. We have access to the value 250 by using
either the name quantity or the address 5000. Since memory addresses are
simply numbers, they can be assigned to some variables which can be stored
in memory, like any other variable. Such variables that hold memory
addresses are called pointers.
Variable Value Address

Quantity
250 5000

p 5000 5048

Fig 3: Pointer as a variable

Suppose, we assign the address of quantity to a variable p. The link


between the variable p and quantity can be visualized as shown in figure 3.
The address of p is 5048.

Since the value of the variable p is the address of the variable quantity. We
may access the value of quantity by using the value of p and therefore, we
say that the variable p ‘pointes’ to the variable quantity. Thus , p gets the
name pointer.

Accessing the address of a variable:


An address can be determined with the help of the operator & available in C.
we have already used this address operator in the scanf function. The
operator & immediately preceding a variable returns the address of the
variable.

Example: p = &quantity;

Would assign the address 5000 to the variable p. The & operator can be used
only with a simple variable or an array element.

The following are illegal use of address operator:


1. &125
2. Int x[10];
&x;
3. &(x+y)

If x is an array, then expressions such as &x[0] and &x[i+3] are valid.

Example 1: Write a program to print the address of a variable along with


its value.

#include <stdio.h>
main( )
{
char a;
int x;
float p;
a= ‘A’;
x=125;
p=10.25;
printf(“%c is stored at address %u=”, a, &a);
printf(“%d is stored at address %u=”, x, &x);
printf(“%f is stored at address %u=”, p, &p);
}

Declaring and initializing pointers:

Syntax : data type *pt_name;

Where,
1. The asterisk (*) tells that the variable pt_name is a pointer variable.
2. Pt_name needs a memory location.
3. Pt_name points to a variable of type data type.

Examples:

int *p;
Declares the variable p as a pointer variable that points to an integer
datatype.

float *x;
Declares x as a pointer to a floating point variable.

Accessing a variable through its pointer:

Consider the following statements:

int quantity, *p, n;

quantity = 250;
p = &quantity;
n = *p;

➢ The first line declares quantity and n as integer variables and p as a


pointer variable pointing to an integer.
➢ The second line assigns the value 250 to quantity.
➢ The third line assigns the address of quantity to the pointer variable p.
➢ The fourth line contains the indirection operator *, when the operator *
is placed before a pointer variable in an expression the pointer returns
the value of the variable of which the pointer value is the address.

Pointer expressions:
Pointer variables can be used in expressions.
For example, if p1 and p2 are properly declared and initialized pointers,
then the following statements are valid.
y = *p1 * *p2; same as (*p1) * (*p2)
sum = sum + *p1;
z = *p2 / *p1;
*p2 = *p2 + 10;

Note that there is a blank space between / and * in the third item above.

We can also use short-hand operator with the pointers.


p1++;
--p2;
sum += *p2;
Pointer increments and scale factor:

If p1 is an integer pointer with an initial value, say 2800, then after the
operation p1=p1+1, the value of p1 will be 2802, and not 2801. That is, when
we increment a pointer, its value is incremented by the length of the data type
that it points to. This length is called the scale factor.
The lengths of various data type as follows:
character 1 byte
integer 2 byte
floats 4 bytes
long integers 4 bytes
double 8 bytes

Pointers and arrays:


When an array is declared, the array in the compiler allocates a base address
and sufficient amount of storage to contain all the elements of the array in
contiguous memory locations. The base address is the location of the first
element (index 0) of the array. The compiler also defines the array name as a
constant pointer to the first element.

Example: static int x[5] = {10,20,30,40,50};


Suppose the base address of x is 1000 and assuming that each integer
requires two bytes, the five elements will be stored as follows:
Elements x[0] x[1] x[2] x[3] x[4]
values
10 20 30 40 50
Address
1000 1002 1004 1006 1008

Base Address

The name x is defined as a constant pointer to the first element, x[0] and
therefore the value of x is 1000 , the location where x[0] is stored.
i.e., x = &x[0] = 1000
If we declare p as an pointer, then we can make the pointer p to point to the
array x by the following assignment:
p = x;
This is equal to p = &x[0];

Now, we can access every value of x using p++ to move from one element to
another.
p = &x[0] = 1000
p+1 = &x[1] = 1002
p+2 = &x[2] = 1004
p+3 = &x[3] = 1006
p+4 = &x[4] = 1008

Example 2:
Develop a program to compute the sum of all the elements stored in an array using
pointers.
#include<stdio.h>
main( )
{
Int i, sum=0, *p;;
static int x[5] = {11,22,33,44,55};
p = x;
printf(“Element Value Address \n”);
for(i =0; i<5; i++)
{
printf (“ x[%d] %d %u \n”, i, *p, p);
sum = sum +*p;
p++;
}
printf(“\n Sum = %d\n” ,sum);
printf(“\n &x[0] = %u\n”,&x[0]);
printf(“\n p = %u\n”,p);
}
Pointers and character strings:
As we know string is an array of characters, terminated with a null character.
We can use a pointer to access the individual characters in a string.

Example 3 :
Program to determine the length of a character string using pointers.

#include <stdio.h>
#include<string.h>
main()
{
char *name;
Int length;
char *cptr = name;
name = “DELHI”;
while (*cptr != 0)
{
printf(“%c is stored at address %u \n”, *cptr, cptr);
cptr++;
}
length= cptr - name;
printf(“\n Length of the string = %d”, length);
}

Pointers and Functions:


Pointers as Function arguments:

When an array is passed to a function as an argument, only the address of


the first element of the array is passed, but not the actual values of the array
elements. If x is an array, when we call sort(x), the address of x[0] is passed
to the function sort. The function uses this address for manipulating the array
elements. Similarly, we can pass the address of a variable as an argument to
a function in the normal fashion.
When we pass addresses to a function, the parameter receiving the
addresses should be pointers. The process of calling a function using
pointers to pass the addresses of variable is known as call by reference.
The function which is called by “reference” can change the value of the
variable used in the call.
Consider the following code:
Example 4:
#include<stdio.h>
main()
{
int x;
x = 20;
change(&x);
printf(“%d\n”,x);
}
change(p)
int *p;
{
*p = *p + 10;
}
When the function change() is called, the address of the variable x, not its
value, is passed into the function change(). Inside change(), the variable p is
declared as a pointer and therefore p is the address of the variable x.
The statement *p = *p + 10;
means “add 10 to the value stored at the address p”. Since p represents the
address of x, the value of x is changed from 20 to 30. Thus, call by reference
provides a mechanism by which the function can change the stored values in
the calling function.
Example 5:
Program to exchange the values stored in two locations in the memory
using pointers.
main()
{
int x, y;
x = 100;
y = 200;
printf(“Before exchange x =%d y=%d \n”, x, y);
exchange(&x,&y);
printf(“After exchange x =%d y=%d \n”, x, y);
}
exchange(a,b)
int *a,*b;
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Pointers to Functions:
A function, like a variable, has an address location in the memory. It is
therefore possible to declare a pointer to function, which can be then be used
as an argument in another function.
A pointer to a function is declared as follows:
type(*fptr)( );
This tells the compiler that fptr is a pointer to a function which returns type
value. The parentheses around *fptr are necessary.
Pointer and Structures:
The whole structure can be used for array variables with pointer.
Example:
struct inventory
{
char name[20];
int number;
float price;
} product[2], *ptr;

This statement declares the product as an array of two elements, each of the
type struct inventory and ptr as a pointer to data objects of the type struct
inventory.
ptr = product;
would assign the address of the zeroth element of the product to ptr. i.e. the
pointer ptr will now point to product[0]. Its members can be accessed using
the following notation.
ptr -> name;
ptr -> number
ptr -> price
The symbol -> is called the arrow operator and is made up of a minus sign
and a greater than sign.
When the pointer ptr is incremented by one, it is made to point to the next
record, i.e product[1]. The following for statement will print the values of
members of all the elements of the product array.

for(ptr = product; ptr <product+2; ptr++)

printf(“%s %d %f \n”, ptr name, ptr -> number, ptr -> price);
We would also use the notation (*ptr).number to access the member
number. The parentheses around *ptr are necessary because the member
operator “.” has a higher precedence than the operator *.
FILE MANAGEMENT IN C

The I/O functions which always use the terminal as the target place. This
works fine as long as the data is small. However , many real-life problems
involve large volumes of data and in such situations, the I/O operations pose
two problems.
1. It becomes cumbersome and time consuming to handle large volumes
of data through terminals.
2. The entire data is lost when either the program is terminated or the
computer is turned off.
It is therefore necessary to have a more flexible approach where data
can be stored on the disks and read whenever necessary, without
destroying the data. This method employs the concept of files to store
data. A file is a place on the disk where a group of related data is
stored. ‘C’ language supports a number of functions that have the ability
to perform basic file operations, which include:
➢ Naming a file
➢ Opening a file
➢ Reading data from a file
➢ Writing data to a file
➢ Closing a file

There are two distinct ways to perform file operations in C.


1. Low-level I/O and uses UNIX system calls
2. High-level operation and use functions in C’s standard I/O library.

High-level I/O functions


fopen( ) Creates a new file for use.
Opens an existing file for use.
fclose( ) Closes a file which has been opened for use.
getc( ) Reads a character from a file
putc( ) Writes a character to a file
fprintf( ) Writes a set of data values to a file
fscanf( ) Reads a set of data values from a file
getw( ) Reads an integer from a file
putw( ) Writes an integer to a file
fseek( ) Sets the position to a desired point in the file
ftell( ) Gives the current point in the file
rewind( ) Sets the position to the beginning of the file

DEFINING AND OPENING A FILE:


Data structure of a file is defined as FILE in the library of standard I/O
function definitions. Therefore, all files should be declared as type FILE
before they are used.
Following is the general format for declaring and opening a file:
FILE *fp;
fp = fopen(“filename”, “mode”);
The first statement declares the variable fp as a “pointer to the data type
FILE”. FILE is a structure that is defined in the I/O library.
The second statement opens the file named filename and assigns an
identifier to the FILE type pointer fp. This pointer contains all the information
about the file.

Mode can be one of the following:

r = opens the file for reading only.


w = opens the file for writing only.
a = open the file for appending for adding data to it.

Consider the following statements:

FILE *p1, *p2;


p1 = fopen(“data”, “r”);
p2 = fopen(“results”,”w”);

The file data is opened for reading and results is opened for writing.
Many recent compilers include additional modes of operations such as :

r+ the existing file is opened to the beginning for both reading and writing.
w+ same as w except both for reading and writing
a+ same as a except both for reading and writing .

CLOSING A FILE:

A file must be closed as soon as all operations on it have been completed.

Syntax:
fclose(file_pointer);
This would close the file associated with the FILE pointer file_pointer.

Example : FILE *p1,*p2;


p1 = fopen(“INPUT”,”w”);
p2 = fopen(“OUTPUT”,”r”);


fclose(p1);
fclose(p2);

This program opens two files and closes them after all operations on them
are completed. Once the file is closed, its file pointer can be reused for
another file.

INPUT/OUTPUT OPERATIONS ON FILES:

The getc and putc functions:


Assume a file is opened with mode w and file pointer fp1. Then, the
statement
putc(c,fp1);
writes the character contained in the character variable c to the file
associated with FILE pointer fp1.

Similarly, getc is used to read a character from a file that has been opened in
read mode.
c = getc(fp2);
would read a character from the file whose file pointer is fp2.

The file pointer moves by one character position for every operation of getc or
putc. The getc will return an end-of-file marker EOF, when the end of the file
has been reached. Therefore, the reading should be terminated when EOF is
encountered.

Example1: Program to read data from the keyboard, write it to a file


called INPUT, again read the same data from the INPUT file, and display
it on the screen.

#include< stdio.h>
main( )
{
FILE *f1;
char c;
printf( “Data input \n”);
f1 = fopen(“INPUT”, ”w”);
while ((c= getchar()) != EOF)
putc(c,f1);
fclose(f1);
printf(“Data output\n”);
f1= fopen(“INPUT”,”r”);
while((c=getc(f1)) !=EOF)
printf(“%c”,c);
fclose(f1);
}
The getw and putw functions:

The getw and putw are integer-oriented functions. They are similar to the getc
and putc functions and are used to read and write only integer values.

The general forms of getw and putw are:

putw(integer,fp);

getw(fp);

Example2: Illustrate the use of putw and getw functions.

#include< stdio.h>
main( )
{
FILE *f1, *f2, *f3 ;
int number;
printf( “Contents of DATA file \n”);
f1 = fopen(“DATA”, ”w”);
for(i=1; i<=50; i++)
{
scanf(“%d”, &number);
If ( number == -1) break;
putw(number, f1);
}
fclose(f1);

f1 = fopen(“DATA”, “r”);
f2=fopen(“ODD”, “w”);
f3=fopen(“EVEN”, “w”);
while(number = getw(f1)) != EOF)
{
If (number % 2 == 0)
putw(number,f3);
else
putw(number,f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);

printf(“Contents of ODD file \n”);


while(number = getw(f2)) != EOF)
printf(“%d”, number);

printf(“Contents of EVEN file \n”);


while (number = getw(f3) != EOF)
printf(“%d”, number):

fclose(f2);
fclose(f3);
}
The fprintf and fscanf functions:

So far, we have seen functions which can handle only one character or
integer at a time.

The functions fprintf and fscanf perform I/O operations that are identical to
the printf and scanf functions, except of course that work on files.

The general form of fprintf is :


fprintf( fp, “control string”, list);

Where fp is the file pointer associated with a file that has been opened for
writing. The control string contains output specifications for the items in the
list. The list may include variables, constants and strings.

Example: fprintf (f1, ”%s %d %f”,name,age,height);

The general form of fscanf is :

fscanf( fp, “control string”, list);

Example: fscanf (f2, ”%s %d %f”, item, &quantity, &price);

Example 1 : Program to open a file named INVENTORY and store in it


the data such as Item name, Number, Price,Quantity.

#include<stdio.h>
main()
{
FILE *fp;
int number,quantity;
float price, value;
char item[10], filename[10];
printf(“Input file name\n”);
scanf(“%s”, filename);
fp=fopen(filename,”w”);
printf(“Input Inventory Data\n”);
printf(“Item Name Number Price Quantity \n”);
for(i=1; i<=3; i++)
{
fscanf(stdin,”%s%d%f %d”, item, &number, &price, &quantity);
fprintf(fp, “%s %d %f %d”, item, number, price, quantity);
}
fclose(fp);
fprintf(stdout, “\n”);
fp=fopen(filename, “r”);
printf(“Item Name Number Price Quantity Value \
n”);
for(i=1; i<=3; i++)
{
fscanf(fp, ”%s %d %f %d”, item, &number, &price, &quantity);
value=price * quantity;
fprintf(stdout,“%s %d %f %d %f”, item,number,price,quantity,
value);
}
fclose(fp);
}
ERROR HANDLING DURING I/O OPERATIONS:

It is possible that an error may occur during I/O operations on a file.


Typical error situations include:

1. Trying to read beyond the end-of-file mark.


Device overflow.
2. Trying to use a file that has not been opened.
3. Trying to perform an operation on a file, when the file is
opened for another type at operation.
4. Opening a file with an invalid filename.
5. Attempting to write to a write-protected file.

If we fail to check such read and write errors, a program may behave
abnormally when an error occurs.

We have two status-inquiry library functions, feof and ferror that can help us
detect I/O errors in the files.
The feof function can be used to test for end-of-file condition. It takes a FILE
pointer as its only argument and returns a nonzero integer value if all of the
data from the specified file has been read, and returns zero otherwise.
If fp is a pointer to file that has just been opened for reading then the
statement:

if(feof(fp))
printf(“End of data \n”);
would display the message , “End of data” on reaching the end of the file
condition.

The ferror function reports the status of the file indicated. It also takes a FILE
pointer as its argument and returns a nonzero integer if an error has been
detected upto that point during processing. It returns zero otherwise.

The statement:

if(ferror(fp) !=0)
printf(“An error has occurred. \n”);
Would print the error message, if the reading is not successful.

We know that whenever a file is opened using the fopen function, a file
pointer is returned. If the file cannot be opened for some reason, then the
function returns a null pointer. This facility can be used to test whether a file
has been opened or not.

if(fp == NULL)
printf(“File could not be opened \n”);

Example 2: program to illustrate error handling in file operations.

#include<stdio.h>
main()
{
char *fiilename;
FILE *fp1, *fp2;
int i,number;
fp1 = fopen(“TEST”,”w”);
for(i=10; i<=100; i+=10)
putw(i, fp1);
fclose(fp1);

printf(“Input filename \n”);


open_file:
scanf(“%s”, filename);
if ((fp2 = fopen(filename, “r”)) == NULL)
{
printf(“Cannot open \n”);
printf(“Type filename again \n”);
goto open_file;
}
else
for(i=1; i<=20; i++)
{
number = getw(fp2);
if(feof(fp2))
{
printf(“ Ran out of the data \n”);
break;
}
else
printf(“%d”,number);
}
fclose(fp2);
}

RANDOM ACCESS TO FILES:

So far we have seen file functions that are useful for reading and writing data
sequentially. There are occasions, however, when we are interested in
accessing only a particular part of a file and not in reading the other parts.
This can be achieved with the help of the functions fseek, ftell and rewind
available in the I/O library.

➢ ftell takes a file pointer and returns a number of type long, that
corresponds to the current position. This function is useful in saving the
current position of a file.
n = ftell(fp);
n would give the relative offset (in bytes) of the current position.

➢ rewind takes a file pointer and resets the position to the starting of the
file.
rewind(fp);
n=ftell(fp);
would assign 0 to n because the file position has been set to the start of
the file by rewind.

➢ fseek function is used to move the file position to a desired location


within the file it takes the following form:
fseek(file ptr, offset, position);
file ptr is a pointer to the file concerned, offset is a number or variable of
type long, and position is an integer number. The position can take one
of the following three values:

Value Meaning
0 Beginning of file
1 Current position
2 End of file

-------------------------End of the Syllabus ---------------------------

You might also like