Program: WAP initialization each element of array individually.
Solution: #include<conio.h>
#include<stdio.h>
void main( )
{
int r[5];
clrscr( );
r[0] = 10;
r[1] = 20;
r[2] = 30;
r[3] = 60;
r[4] = 70;
printf(“Rvalueis =%d”, r[3]);
getch();
}
OUTPUT: R valueis = 60
Program : #include<conio.h>
#include<stdio.h>
void main()
{
int r[5], t;
clrscr();
r[0]=60;
r[1]=50;
r[2]=40;
r[3]=60;
r[4]=10;
t = r[0] + r[1]+r[2]+r[3]+r[4];
printf(“Totalis =%d”,t);
getch();
} OUTPUT: Total is = 220
Program: #include<conio.h>
#include<stdio.h>
void main()
{
int r[5] , t , i;
clrscr();
t = 0;
r[0]=10;
r[1] = 20;
r[2] = 30;
r[3] = 30;
r[4] = 60;
for(i = 0; i<5; i++)
{
t = t + r[i];
printf(“Totalis =%d”,t);
}
getch();
}
OUTPUT: Total is = 130
Program: WAP finding out thesumof odd and even numbers in array.
Solution: #include<conio.h>
#include<stdio.h>
void main()
{
int arr[]={2,7,8,9,11};
int sumev = 0;
int sumodd = 0;
int i;
for(i=0;i<5;i++)
{
if((arr[i]%2)==0)
sumev = sumev + arr[i];
else
sumodd = sumodd + arr[i];
}
printf(“Sumof even numbers in array =%d”, sumev);
printf(“Sumof odd numbers in array =%d”, sumodd);
getch();
}
OUTPUT : Sum of even numbers in array = 10
Sumof odd numbers in array = 27
Program: Displaying thelength of an array.
Solutions: #include<conio.h>
#include<stdio.h>
void main()
{
doublemarks[]={4.5,7.8,9.9,8.9};
int n;
clrscr();
n = marks. length;
printf(“Lengthis = %d”,n);
getch();
}
OUTPUT: Length is = 4
Program: WAP Display theelements of an array.
Solution: #include<conio.h>
#inlcude<stdio.h>
void main()
{
char alpha[] = {‘A’,’B’,’C’,’D’,’E’};
int n = alpha . length;
printf(“Element of Array”);
for(int i = 0; i<n; i++)
printf(alpha[i]);
getch();
}
OUTPUT : Element of Array
A B C D E
Program : WAP display arrangingthenumber in descendingorder.
Solution: #include<conio.h>
#include<stdio.h>
void main()
{
int a[] = {20, 5, 70, 100, 14};
clrscr();
int n = a . length;
int temp, i, j;
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(“Numbers in descendingorder”);
for(i = 0; i<n; i++)
{
printf(“%d”,a[i]);
}
getch();
}
OUTPUT : Numbers in descending order
100
70
20
14
5
Program : WAP sorting a characterarray usingsort() function.
Solution: #include<conio.h>
#include<stdio.h>
void main()
{
char name[]={‘S’,’A’,’R’,’N’};
Arrays.sort(name);
printf(“Elements in ascendingorder”);
for(int i = 0; i<name.length;i++)
printf(“%c”,name[i]);
getch();
}
OUTPUT : Elements in ascending order
A R N S
Program : WAP sorting an integer array usingsort() function.
Solution: #include<conio.h>
#include<stdio.h>
void main()
{
int num[]={70,56,29,4,750,200,50};
int n;
int i;
Arrays.sort(num);
printf(“Elements in ascendingOrder”);
for(i = 0; i<n; i++)
printf(“%d”,num[i]);
getch();
}
OUTPUT: Elements in ascendingOrder
4 29 50 56 70 200 750
Two – DimensionalArray:
You can createarray in form of m x n matrix
or in table formalso.
Syntax : Data Type arrayname[] [] = new type[size] [size];
Example : int matrix[] [] = new int[3][5];
3 Rows
5 Columns
Program: #include<stdio.h>
#include<conio.h>
void main()
{
int a[] [] = {{55,29,17},{70,56,25},{69,75,23},{7,8,9}};
int i, j;
clrscr();
printf(“Martix= “);
for(i = 0;i<3; i++)
{
for( j = 0; j<3 ; j++)
{
printf(“%d”,a[i][j],””);
}
printf(“n”);
}
getch();
}
OUTPUT : Matrix = 55 29 17
70 56 25
69 75 23
7 8 9
Program : WAP showing that you can use literalvalues as well as expressions
inside { } for initialization.
[0] [0] [0] [1] [0] [2] [0] [3] [0] [4]
[1] [0] [1] [1] [1] [2] [1] [3] [1] [4]
[2] [0] [2] [1] [2] [2] [2][3] [2] [4]
Solution: #include<conio.h>
#include<stdio.h>
void main()
{
int a[] [] ={{5*2, 2*1,3*0},{6*3,7*0,9*4},{5*3,5*5,4*9}};
int i, j;
clrscr();
for(i = 0; i<3; i++)
{
for( j = 0; j<3; j++)
{
printf(“%d”,a[i][j],””);
printf(“n”);
}
}
getch();
}
OUTPUT : 10 2 3
18 0 36
15 25 36
Three- Dimensional Array :
3-Dimensionalarray means array with
multiple dimensional3, 4 or even more.
Example : int three[2] [4] [6];
Program : #include<conio.h>
#include<stdio.h>
void main()
{
int three[2][4][6];
int i, j, k;
for(i = 0; i<3; i++)
{
for( j = 0; j<4; j++)
{
for( k = 0; k<5 ; k++)
{
three[i][j][k] = i * j * k;
}
}
}
for(i = 0; i<3; i++)
{
for( j = 0; j<4; j++)
{
for( k = 0; k<5; k++)
{
printf(three[i][j][k], “”);
printf(“n”);
}
printf(“n”);
}
getch();
}
Question
1: WAP to input values into an array and display them.
Session – 6
Function
A function is a group of statements that together perform a task. Every C
program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
You can divide up your code into separate functions. How you divide up your
code among different functions is up to you, but logically the division is such
that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type,
and parameters. A function definition provides the actual body of the function.
Defining a function:
The general form of a function definition in C
programming language is as follows –
return_type function_name( parameter list )
{
body of the function
}
Return Type:
A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
Function Type: This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
Parameters:
A parameter is like a placeholder. When a function is invoked,
you pass a value to the parameter. This value is referred to as actual parameter
or argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may
contain no parameters.
Function Body:
The function body contains a collection of statements that define
what the function does.
Example:
/* function returningthemax between two numbers */
int max(int num1, int num2)
{
/* local variabledeclaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Function Declaration:
A function declaration tells the compiler about a
function nameand how to callthe function. Theactualbody of the function can
be defined separately.
return_typefunction_name( parameterlist );
For theabove defined functionmax(), thefunction declaration is as follows –
int max(int num1, int num2);
Parameter names are not important in functiondeclaration only their typeis
required, so thefollowing is also a valid declaration –
int max(int, int);
Callinga Function: When a programcalls a function, the program control is
transferredtothe called function. Acalled function performs a defined task and
when its return statementis executed or when its function-ending closing brace
is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with
the function name, and if the function returns a value, then you can store the
returned value.
Program:#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %dn", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
OUTPUT :Max value is : 200
Function Arguments:
If a function is to use arguments,it must declarevariables that accept the values
of the arguments. These variables are called the formal parameters of the
function.
Formal parameters behavelike other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, therearetwoways in which arguments can be passed
to a function –
Sr.No
.
Call Type & Description
1
Call By Value
This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
2
Call By Reference
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
Call By Value : The call by value method of passing arguments to a function
copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have
no effect on the argument.
By default, C programming uses call by value to pass arguments. In general, it
means the code within a function cannot alter the arguments used to call the
function. Consider the function swap() definition as follows.
/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Now, let us call thefunction swap() by passing actualvalues as in thefollowing
example –
#include<stdio.h>
/* function declaration*/
void swap(int x, int y);
int main ()
{
/* local variabledefinition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %dn", a );
printf("Beforeswap, value of b : %dn", b );
/* calling a function toswap thevalues */
swap(a, b);
printf("After swap, valueof a : %dn", a );
printf("After swap, valueof b : %dn", b );
return 0;
}
OUTPUT : Before swap, value of a :100
Before swap, valueof b :200
After swap, value of a :100
After swap, value of b :200
Call by Reference: Thecall by reference method of passing arguments to a
function copies theaddress of an argument intotheformalparameter. Inside the
function, the address is used to access the actual argument used in the call. It
means the changes made to the parameter affect the passed argument.
To pass a valueby reference, argumentpointers are passed to the functions just
like any other value. So accordingly you need to declarethe function parameters
as pointer types as in thefollowing function swap(), which exchanges the values
of the two integer variables pointed to, by their arguments.
Program :
/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us now callthe function swap() by passing values by referenceas in the
following example −
#include<stdio.h>
/* functiondeclaration*/
void swap(int *x, int *y);
int main ()
{
/* localvariable definition */
int a = 100;
int b = 200;
printf("Beforeswap, value of a : %dn", a );
printf("Beforeswap, value of b : %dn", b );
/* calling a function toswap thevalues.
* &a indicates pointer to a ie. address of variablea and
* &b indicates pointer to b ie. address of variableb.
*/
swap(&a, &b);
printf("After swap, valueof a : %dn", a );
printf("After swap, valueof b : %dn", b );
return 0;
}
OUTPUT : Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
Scope Rules: A scope in any programmingis a region of theprogram where
a defined variable can have its existence and beyond that variable it cannot be
accessed. There are three places where variables can be declared in C
programming language −
Inside a function or a block which is called local variables.
Outside of all functions which is called global variables.
In the definition of function parameters which are called formal
parameters.
Let us understand what are local and global variables, and formal parameters.
Local Variables: Variables that aredeclared inside a function or block are
called local variables. They can be used only by statements that are inside that
function or block of code. Local variables are not known to functions outside
their own.
Program :
#include<stdio.h>
int main ()
{
/* local variabledeclaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("valueof a = %d, b = %d and c = %dn", a, b, c);
return 0;
}
OUTPUT: value of a = 10, b = 20, c = 30
Global Variable: Global variables are defined outside a function, usually
on top of theprogram. Globalvariables hold their values throughout the lifetime
of your programand they can be accessed insideany of the functions defined for
the program.
A global variable can be accessed by any function.
Program:
#include <stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %dn", a, b, c);
return 0;
}
Program :
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{
/* local variable declaration */
int g = 10;
printf ("value of g = %dn", g);
return 0;
}
Formal Parameters: Formal parameters, are treated as local variables
with-in a function and they take precedence over global variables.
Program:
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %dn", a);
c = sum( a, b);
printf ("value of c in main() = %dn", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b)
{
printf ("value of a in sum() = %dn", a);
printf ("value of b in sum() = %dn", b);
return a + b;
}
OUTPUT: value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Initializing Local and Global Variables:
When a local variable is defined, it is not initialized by the system, you must
initializeit yourself. Global variables are initialized automatically by the system
when you define them as follows –
Data Type Initial Default Value
int 0
char '0'
float 0
double 0
pointer NULL
Passing Arrays as function arguments in “C”:
If you want to pass a single-dimension array as an argument in a function, you
would have to declarea formal parameter in one of following threeways and all
three declaration methods produce similar results because each tells the
compiler that an integer pointer is going to be received. Similarly, you can pass
multi-dimensional arrays as formal parameters.
Way-1
Formal parameters as a pointer –
void myFunction(int *param)
{
}
Way-2
Formal parameters as a sized array –
void myFunction(int param[10])
{
}
Way-3
Formal parameters as an unsized array −
void myFunction(intparam[])
{
}
Program:
double getAverage(intarr[], int size)
{
int i;
doubleavg;
doublesum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
Now, let us call theabove function as follows –
#include<stdio.h>
/* function declaration*/
double getAverage(intarr[], int size);
int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to thearray as an argument */
avg = getAverage( balance, 5 ) ;
/* output thereturned value*/
printf( "Averagevalue is: %f ", avg );
return 0;
}
OUTPUT: Average value is: 214.400000
Session-7
Structure
Arrays allow to define type of variables that can hold several data items of the
same kind. Similarly structure is another user defined data type available in C
that allows to combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of
your books in a library. You might want to track the following attributes about
each book –
Title
Author
Subject
Book ID
Defining a Structure:
To define a structure, you must usethe struct statement.Thestruct statement
defines a new data type, with more than onemember. Theformat of the struct
statement is as follows –
struct Books
printf("Book 1title: %sn",Book1.title);
printf("Book 1author:%sn",Book1.author);
printf("Book 1subject:%sn",Book1.subject);
printf("Book 1book_id:%dn",Book1.book_id);
/*printBook2info*/
printf("Book 2title: %sn",Book2.title);
printf("Book 2author:%sn",Book2.author);
printf("Book 2subject:%sn",Book2.subject);
printf("Book 2book_id:%dn",Book2.book_id);
return0;
}
OUTPUT :
Book 1title:C Programming
Book 1author:NuhaAli
Book 1subject:CProgrammingTutorial
Book 1book_id: 6495407
Book 2title:Telecom Billing
Book 2author:ZaraAli
Book 2subject:TelecomBilling Tutorial
Book 2book_id: 6495700
Structures as Function Arguments:
You can pass a structure as a function argument in thesameway as you pass any other
variableor pointer.
#include<stdio.h>
#include<string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
OUTPUT:
Book title:CProgramming
Book author:NuhaAli
Book subject:CProgrammingTutorial
Book book_id:6495407
Book title:TelecomBilling
Book author:ZaraAli
Book subject:TelecomBilling Tutorial
Book book_id:6495700
Pointers to Structures :
Youcandefinepointerstostructuresinthesamewayasyou definepointertoanyother
variable–
struct Books *struct_pointer;
Now, youcanstoretheaddressof a structurevariableintheabovedefinedpointervariable.
Tofindtheaddressof a structurevariable,placethe'&';operatorbeforethestructure'sname
as follows –
struct_pointer=&Book1;
Toaccessthemembersof a structureusingapointertothatstructure,youmustusethe→
operatoras follows –
struct_pointer->title;
Program:
#include<stdio.h>
#include<string.h>
structBooks
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
Book book_id:101
Book title:Telecom Billing
Book author:AshuSrivastava
Book subject:TelecomBilling
Book book_id:102
Unions
Aunionisa specialdatatypeavailablein Cthatallowstostoredifferent datatypesin the
samememory location.Youcandefineaunionwithmanymembers,butonlyonemember
cancontainavalueatanygiventime. Unionsprovideanefficientwayof usingthesame
memory locationformultiple-purpose.
Defining a Union :
Todefineaunion,youmustusetheunionstatementinthesameway asyou didwhile
definingastructure.Theunionstatementdefinesanewdatatypewithmorethanone
member foryourprogram.Theformatof theunionstatementisasfollows –
union[uniontag]
{
member definition;
member definition;
...
member definition;
} [oneor moreunionvariables];
Program:
#include<stdio.h>
#include<string.h>
unionData
{
inti;
float f;
charstr[20];
};
int main( )
{
unionDatadata;
printf("Memory sizeoccupiedbydata: %dn",sizeof(data));
return0;
}
OUTPUT:Memory sizeoccupiedbydata: 20
AccessingUnionMembers:
Toaccessanymemberof a union,weusethememberaccessoperator(.). Themember
accessoperatoris codedas aperiod between theunionvariablenameandtheunion
member thatwewishtoaccess.Youwould usethekeyworduniontodefinevariables of
uniontype.
Program:
#include<stdio.h>
#include<string.h>
unionData
{
inti;
float f;
charstr[20];
};
intmain()
{
unionDatadata;
data.i= 10;
data.f=220.5;
strcpy(data.str,"CProgramming");
printf("data.i:%dn",data.i);
printf("data.f:%fn",data.f);
printf("data.str:%sn",data.str);
return0;
TheC programminglanguageprovidesakeywordcalled typedef,whichyoucanuseto
giveatypeanewname.
typedef unsignedcharBYTE;
Program:
#include<stdio.h>
#include<string.h>
typedefstructBooks
{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
} Book;
intmain()
{
Book book;
strcpy(book.title,"CProgramming");
strcpy(book.author,"AshutoshSrivastava");
strcpy(book.subject,"CProgrammingLanguage");
book.book_id=101;
printf("Book title: %sn",book.title);
printf("Book author:%sn",book.author);
printf("Book subject:%sn",book.subject);
printf("Book book_id:%dn",book.book_id);
return0;
}
OUTPUT:
Book title: CProgramming
Book author:AshutoshSrivastava
Book subject:CProgrammingLanguage
Book book_id:101
typedef vs #define:
#defineis a C-directive which is also used to define the aliases for various data types
similar totypedef but with thefollowing differences −
typedef is limited to giving symbolic names to types only where as #definecan be
used todefinealias for values as well, q., you can define1 as ONE etc.
typedef interpretationisperformedby thecompiler whereas #definestatements are
processed by thepre-processor.
Program:
#include<stdio.h>
#defineTRUE 1 OUTPUT: Valueof TRUE : 1
#defineFALSE 0 Value of FALSE : 0
int main( )
{
printf( "Valueof TRUE : %dn", TRUE);
printf( "Valueof FALSE : %dn", FALSE);
return 0;
}
QUESTION
1: StoreInformation (name, rolland marks) of a Student Using Structure.
Sr.No. Function & Purpose
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.
Strcpy():TheC libraryfunctionchar*strcpy(char*dest,constchar*src)copiesthestring
pointedto, bysrctodest.
Declaration:
char*strcpy(char*dest,constchar*src)
Parameters:
dest − Thisis thepointertothedestinationarraywherethecontentistobecopied.
src − This is thestring tobecopied.
Return Value : Thisreturnsapointertothedestinationstringdest.
Program:
#include<stdio.h>
{
printf("str2 is less than str1");
}
else
{
printf("str1 is equaltostr2");
}
return(0);
}
OUTPUT :str2isless thanstr1
strchr(): TheClibraryfunctionchar*strchr(constchar*str,intc)searchesforthefirst
occurrenceofthecharacterc(anunsignedchar)inthestringpointedtobythe
argumentstr.
Declaration:
char*strchr(constchar*str,intc)
Parameters
str −This is theC string tobescanned.
c −This is thecharacter tobesearched in str.
Return Value :
Thisreturnsapointertothefirstoccurrenceofthecharactercinthestringstr,orNULLif
thecharacterisnotfound.
Program:
#include<stdio.h>
#include<string.h>
What arePointers?
Apointeris a variablewhosevalueis theaddressof anothervariable,i.e., directaddressof
thememory location.Likeanyvariableorconstant,youmustdeclareapointerbeforeusing
ittostoreanyvariableaddress.Thegeneralformof a pointervariabledeclarationis –
type*var-name;
Example:
int *ip; /*pointertoaninteger*/
double*dp; /*pointertoa double*/
float *fp; /*pointertoa float*/
char *ch /* pointertoa character*/
How to UsePointers?
#include<stdio.h>
intmain()
{
int var=20; /*actualvariabledeclaration*/
int *ip; /* pointervariabledeclaration*/
ip =&var; /*storeaddressof varinpointervariable*/
printf("Addressof varvariable:%xn",&var );
/* addressstoredinpointervariable*/
printf("Addressstoredinip variable:%xn",ip );
/*accessthevalueusingthepointer*/
printf("Valueof*ip variable: %dn",*ip);
return0;
}
OUTPUT :
Address ofvar variable:bffd8b3c
Address storedinip variable:bffd8b3c
Valueof *ip variable: 20
NULL Pointers:
Itis always agood practicetoassignaNULLvaluetoapointervariableincaseyoudonot
haveanexactaddresstobeassigned.Thisis doneatthetimeof variabledeclaration.A
pointerthatisassignedNULLis calleda nullpointer.
Program:
#include<stdio.h>
intmain()
{
int *ptr=NULL;
printf("Thevalueof ptris: %xn",ptr );
return0;
}
OUTPUT :
Thevalueof ptris 0
Pointers inDetail :
Sr.No. Concept & Description
1 Pointerarithmetic
There are four arithmetic operators that can be used in pointers: ++, --, +, -
2 Array of pointers
You can define arrays to hold a number of pointers.
3 Pointerto pointer
C allows you to have pointer on a pointer and so on.
4 Passing pointersto functionsin C
Passing an argument by reference or by address enable the passed argument to be changed in the
calling function by the called function.
5 Return pointerfrom functionsin C
“C” allows a function to return a pointer to the local variable, static variable and dynamically
allocated memory as well.
Pointer arithmetic
A pointer in c is an address, which is a numeric value. Therefore, you can
performarithmetic operations on a pointer just as you can on a numeric value.
Thereare four arithmetic operators that can beused on pointers: ++, --, +, and -
ptr++
Incrementing a Pointer
Program:
#include<stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Valueof var[%d] = %dn", i, *ptr );
/* move to the next location */
ptr++;
}
return 0;
}
OUTPUT :
Address of var[0] = bf882b30
Valueof var[0] = 10
Address of var[1] = bf882b34
Valueof var[1] = 100
Address of var[2] = bf882b38
Valueof var[2] = 200
Decrementing a Pointer
Program:
#include<stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us havearray address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--)
{
printf("Address of var[%d] = %xn", i-1, ptr );
printf("Valueof var[%d] = %dn", i-1, *ptr );
/* move to theprevious location */
ptr--;
}
return 0;
}
OUTPUT:
Address of var[2] = bfedbcd8
Valueof var[2] = 200
Address of var[1] = bfedbcd4
Valueof var[1] = 100
Address of var[0] = bfedbcd0
Valueof var[0] = 10
Pointer Comparisons
Program:
#include<stdio.h>
constintMAX=3;
intmain()
{
int var[]={10,100,200};
int i,*ptr;
/*let ushaveaddressof thefirstelementin pointer*/
ptr=var;
i=0;
while( ptr<=&var[MAX-1])
{
printf("Addressof var[%d]=%xn",i,ptr);
printf("Valueofvar[%d]=%dn",i,*ptr );
/*point totheprevious location*/
ptr++;
i++;
}
return0;
}
OUTPUT:
Address ofvar[0]= bfdbcb20
Valueof var[0]=10
Address ofvar[1]= bfdbcb24
Valueof var[1]=100
Address ofvar[2]= bfdbcb28
Valueof var[2]=200
Arrayofpointers
Program :#include<stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++)
{
printf("Valueof var[%d] = %dn", i, var[i] );
}
return 0;
}
OUTPUT:
Valueof var[0] = 10
Valueof var[1] = 100
Valueof var[2] = 200
Program:
#include<stdio.h>
const int MAX = 4;
int main ()
{
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Valueof names[%d] = %sn", i, names[i] );
}
return 0;
}
OUTPUT :
Valueof names[0] = Zara Ali
Valueof names[1] = Hina Ali
Valueof names[2] = Nuha Ali
Valueof names[3] = Sara Ali
Pointer to Pointer
A pointer to a pointer is a form of multipleindirections, or a chain of pointers.
Normally, a pointer contains theaddress of a variable. When we define a pointer
to a pointer, the first pointer contains theaddress of thesecond pointer, which
points to the location that containstheactualvalueas shown below.
int **var;
Program :
#include<stdio.h>
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
/* takethe address of var */
ptr = &var;
/* taketheaddress of ptr using address of operator & */
pptr = &ptr;
/* takethe value using pptr */
printf("Valueof var = %dn", var );
printf("Valueavailable at *ptr = %dn", *ptr );
printf("Valueavailableat **pptr = %dn", **pptr);
return 0;
}
OUTPUT :
Valueof var = 3000
Valueavailable at *ptr = 3000
Valueavailable at **pptr = 3000
Passingpointers to functions
C programming allows passing a pointer to a function. To do so, simply declare
the function parameter as a pointer type.Following is a simple example where
we pass an unsigned long pointer toa function and change the value inside the
function which reflects back in the calling function −
Program:
#include<stdio.h>
#include<time.h>
void getSeconds(unsigned long *par);
int main ()
{
unsigned long sec;
getSeconds(&sec );
/* print theactualvalue*/
printf("Number of seconds: %ldn", sec );
return 0;
}
void getSeconds(unsigned long *par)
{
/* get the currentnumberof seconds */
*par = time( NULL );
return;
}
OUTPUT: Number of seconds :1294450468
Program :
#include<stdio.h>
/* functiondeclaration*/
double getAverage(int*arr, int size);
int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
doubleavg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output thereturned value */
printf("Averagevalueis: %fn", avg );
return 0;
}
double getAverage(int*arr, int size)
{
int i, sum = 0;
doubleavg;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = (double)sum/ size;
return avg;
}
OUTPUT: Average value is: 214.40000
Return pointer from functions
C also allows to return a pointer from a function. Todo so, you would have to
declarea functionreturning a pointer as in thefollowing example –
int * myFunction()
{
}
Second point to remember is that, it is not a good idea to return theaddress of a
local variableoutsidethe function,so you would have to define thelocal variable
as static variable.
Program :
#include<stdio.h>
#include<time.h>
/* functiontogenerateand return randomnumbers.*/
int * getRandom( )
{
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i)
{
r[i] = rand();
printf("%dn", r[i] );
}
return r;
}
/* main function tocallabove defined function */
int main ()
{
/* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ )
{
printf("*(p + [%d]) : %dn", i, *(p + i) );
}
return 0;
}
2: Program to read array elements and print with addresses.
3: Program to print size of different types of pointer variables.
Session–10
Filesand I/O
A file represents a sequenceof bytes, regardless of it being a text file or a binary
file. C programminglanguageprovides access on high level functions as well as
low level (OS level) calls to handlefile on your storagedevices. This chapter will
takeyou throughtheimportant calls for file management.
Types ofFiles:
When dealing with files, thereare two types of files you should knowabout:
1. Text files
2. Binary files
1.Text files:
Text files are the normal.txt files that you can easily createusing Notepad or any
simple text editors.
When you open those files, you'll see all the contents withinthefile as plain text.
You can easily edit or delete the contents.
They takeminimumeffort to maintain, areeasily readable, and provide least
security and takes bigger storagespace.
Opening Files:
You can use the fopen( ) functiontocreatea new file or to open an existing file.
This call will initializean object of the type FILE, which contains allthe
information necessary tocontrolthestream. Theprototypeof this function callis
as follows –
FILE *fopen( const char * filename, const char * mode );
Sr.No. Mode & Description
1 R
Opens an existing text file for reading purpose.
2 W
Opens a text file for writing. If it does not exist, then a new file is
created. Here your programwill start writing content fromthe
beginningof thefile.
3 A
Opens a text file for writing in appending mode. If it does not
exist, then a new file is created. Hereyour programwill start
appending contentin theexisting file content.
4 r+
Opens a text file for both reading and writing.
5 w+
Opens a text file for both reading and writing. It first truncates the
file to zerolength if it exists, otherwisecreates a file if it does not
exist.
6 a+
Opens a text file for both reading and writing. It creates thefile if
it does not exist. Thereading will start from thebeginning but
writing can only be appended.
If you are going to handlebinary files, then you will use following access modes
instead of the above mentioned ones –
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
ClosingaFile:
To close a file, use the fclose( ) function. Theprototypeof this functionis −
int fclose( FILE *fp );
The fclose(-) function returnszeroon success, or EOF if thereis an error in
closing thefile. This function actually flushes any data stillpending in the buffer
to the file, closes the file, and releases any memory used for the file. The EOF is a
constant defined in theheader file stdio.h.
Writinga File:
Following is the simplest function towrite individualcharacters toa stream −
int fputc( int c, FILE *fp );
The function fputc() writes thecharactervalueof the argumentc to the output
streamreferenced by fp. It returns thewritten characterwritten on success
otherwiseEOF if thereis an error. You can usethe following functions towritea
null-terminated string toa stream –
int fputs( const char *s, FILE *fp );
The function fputs() writes thestring s to the output streamreferenced by fp. It
returns a non-negativevalueon success, otherwise EOF is returned in caseof any
error. You can use int fprintf(FILE *fp,constchar *format, ...)function as well to
write a string intoa file.
Program:
#include<stdio.h>
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt","w+");
fprintf(fp, "This is testing for fprintf...n");
fputs("This is testing for fputs...n",fp);
fclose(fp);
}
Readinga File:
Given below is the simplest function toread a singlecharacterfroma file –
int fgetc( FILE * fp );
The fgetc() functionreads a characterfromtheinput file referenced by fp. The
return valueis thecharacterread, or in case of any error, it returns EOF. The
following functionallows to read a string froma stream –
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n-1 characters from the input stream
referenced by fp. It copies the read string into the buffer buf, appending
a null character to terminate the string.
If this function encounters a newline character 'n' or the end of the file EOF
before they have read the maximumnumber of characters, then it returns only
thecharacters read up to that point including the new line character. You can
also use int fscanf(FILE *fp, const char *format, ...) functiontoread strings from a
file, but it stops reading after encountering the first space character.
Program:
#include<stdio.h>
void main()
{
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt","r");
fscanf(fp, "%s", buff);
printf("1 : %sn", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %sn", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %sn", buff );
fclose(fp);
}
2. Binary files:
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in thebinary form (0's and 1's).
They can hold higher amount of data, arenot readableeasily and provides a
better security thantext files.
File Operations:
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information toa file
Workingwith files:
When working with files, you need to declarea pointer of type file. This
declaration is needed for communication between thefile and program.
FILE *fptr;
Opening a file - for creation and edit:
Opening a file is performed using the library functionin the"stdio.h"header file:
fopen().
ptr = fopen("fileopen","mode")
Example:
fopen("E:cprogramnewprogram.txt","w");
fopen("E:cprogramoldprogram.bin","rb");
Opening Modes in Standard I/O
File
Mode
Meaning of Mode During Inexistence of file
r Open for reading. If the file does not exist,
fopen() returns NULL.
rb Open for reading in binary
mode.
If the file does not exist,
fopen() returns NULL.
w Open for writing. If the file exists, its contents
are overwritten. If thefile does
not exist, it will be created.
wb Open for writing in binary mode. If the file exists, its contents
are overwritten. If thefile does
not exist, it will be created.
a Open for append. i.e, Data is
added to end of file.
If the file does not exists, it
will be created.
ab Open for append in binary mode.
i.e, Data is added to end of file.
If the file does not exists, it
will be created.
r+ Open for both reading and
writing.
If the file does not exist,
fopen() returns NULL.
rb+ Open for both reading and
writing in binary mode.
If the file does not exist,
fopen() returns NULL.
w+ Open for both reading and
writing.
If the file exists, its contents
are overwritten. If thefile does
not exist, it will be created.
wb+ Open for both reading and
writing in binary mode.
If the file exists, its contents
are overwritten. If thefile does
not exist, it will be created.
a+ Open for both reading and
appending.
If the file does not exists, it
will be created.
ab+ Open for both reading and
appending in binary mode.
If the file does not exists, it
will be created.
Reading and writing to a binary file:
Functions fread() and fwrite() areused for reading fromand writing to a file on
thedisk respectively in caseof binary files.
Writing to a binary file:
To write into a binary file, you need to usethe function fwrite(). Thefunctions
takes four arguments: Address of data to be written in disk, Size of data to be
written in disk, number of such type of data and pointer to thefile where you
want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Program :
#include<stdio.h>
#include<stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
structthreeNumnum;
FILE *fptr;
if ((fptr = fopen("C:program.bin","wb")) == NULL)
{
printf("Error! opening file");
// Programexits if thefile pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(structthreeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
Reading from a binary file:
Function fread() alsotake4 arguments similar to fwrite() functionas above.
Program:
#include<stdio.h>
#include<stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
structthreeNumnum;
FILE *fptr;
if ((fptr = fopen("C:program.bin","rb")) == NULL){
printf("Error! opening file");
// Programexits if thefile pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(structthreeNum), 1, fptr);
printf("n1: %dtn2: %dtn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
Getting data using fseek():
If you have many records insidea file and need to access a record at a specific
position, you need to loop throughallthe records beforeit to get therecord.
This will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek().
fseek(FILE * stream, long int offset, int whence)
Different Whence in fseek
Whence Meaning
SEEK_SET Starts theoffset from thebeginning of the file.
SEEK_END Starts theoffset from theend of thefile.
SEEK_CUR
Starts theoffset from thecurrent location of thecursor in
thefile.
Program:
#include<stdio.h>
#include<stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
structthreeNumnum;
FILE *fptr;
if ((fptr = fopen("C:program.bin","rb")) == NULL){
printf("Error! opening file");
// Programexits if the file pointer returnsNULL.
exit(1);
}
// Moves thecursor tothe end of the file
fseek(fptr, -sizeof(struct threeNum),SEEK_END);
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(structthreeNum), 1, fptr);
printf("n1: %dtn2: %dtn3: %dn", num.n1, num.n2, num.n3);
fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);
}
fclose(fptr);
return 0;
}
QUESTION
1: WAP stores a sentenceentered by user in a file.