SlideShare a Scribd company logo
1 of 86
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.
2: WAP to add elements of an array.
3: WAP to count even and odd numbers in an array.
4: WAP to pass array elements to a function.
5: WAP to input and display a matrix.
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
Question
1: Display all prime numbers between two Intervals.
2: Check Prime and Armstrong Number by making function.
3: Check whether a number can beexpressed as thesum of two prime number.
4: Writea programin C to find thesquareof any number using the function.
5: Writea programin C to swap two numbers usingfunction.
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
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
AccessingStructure Members:
#include<stdio.h>
#include<string.h>
structBooks
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
intmain()
{
structBooksBook1; /*DeclareBook1 of typeBook */
structBooksBook2; /*DeclareBook2 of typeBook */
/*book1 specification*/
strcpy(Book1.title,"CProgramming");
strcpy(Book1.author,"NuhaAli");
strcpy(Book1.subject,"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2 specification*/
strcpy(Book2.title,"TelecomBilling");
strcpy(Book2.author,"ZaraAli");
strcpy(Book2.subject,"TelecomBillingTutorial");
Book2.book_id=6495700;
/* printBook1info*/
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];
int book_id;
};
/*function declaration */
void printBook( struct Books book );
int main( )
{
struct Books Book1; /*DeclareBook1 of typeBook */
struct Books Book2; /*DeclareBook2 of typeBook */
/*book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/*book 2 specification */
strcpy( Book2.title, "TelecomBilling");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "TelecomBilling Tutorial");
Book2.book_id = 6495700;
/*print Book1 info*/
printBook( Book1 );
/*Print Book2 info*/
printBook( Book2 );
return 0;
}
void printBook( struct Books book )
{
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);
}
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;
};
/*functiondeclaration*/
void printBook(structBooks*book);
intmain()
{
structBooksBook1; /* Declare Book1of typeBook */
structBooksBook2; /*DeclareBook2 of typeBook */
/* book1specification*/
strcpy(Book1.title,"CProgramming");
strcpy(Book1.author,"AshutoshSrivastava");
strcpy(Book1.subject,"CProgrammingLanguage");
Book1.book_id=101;
/*book2 specification*/
strcpy(Book2.title,"TelecomBilling");
strcpy(Book2.author,"AshuSrivastava");
strcpy(Book2.subject,"TelecomBilling");
Book2.book_id=102;
/*printBook1infobypassingaddressofBook1 */
printBook(&Book1);
/*printBook2infobypassingaddressof Book2*/
printBook(&Book2);
return0;
}
void printBook(structBooks*book)
{
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);
}
OUTPUT:
Book title:CProgramming
Book author:AshutoshSrivastava
Book subject:CProgrammingLanguage
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;
}
OUTPUT:
data.i: 1917853763
data.f:4122360580327794860452759994368.000000
data.str:CProgramming
Bit Fields
SupposeyourCprogramcontainsanumberofTRUE/FALSE variablesgroupedina
structurecalledstatus,asfollows–
struct
{
unsignedintwidthValidated;
unsignedintheightValidated;
} status;
Program:
#include<stdio.h>
#include<string.h>
/*definesimple structure*/
struct
{
unsignedintwidthValidated;
unsignedintheightValidated;
} status1;
/*definea structurewithbitfields*/
struct
{
unsignedintwidthValidated:1;
unsignedintheightValidated:1;
} status2;
intmain()
{
printf("Memorysizeoccupiedbystatus1:%dn",sizeof(status1));
printf("Memorysizeoccupiedbystatus2:%dn",sizeof(status2));
return0;
}
OUTPUT:Memory sizeoccupiedbystatus1:8
Memory sizeoccupiedbystatus2:4
Bit Field Declaration:
struct
{
type[member_name]:width;
};
Sr.No
.
Element & Description
1 Type
An integer type that determines how a bit-field's value is interpreted. The type
may beint, signed int, or unsigned int.
2 member_name
Thenameof thebit-field.
3 Width
Thenumberofbits inthebit-field.Thewidthmustbeless than or equaltothebit
width of thespecified type.
struct
{
unsignedintage:3;
} Age;
Program:
#include<stdio.h>
#include<string.h>
struct
{
unsignedintage:3;
} Age;
intmain()
{
Age.age=4;
printf("Sizeof(Age) : %dn",sizeof(Age));
printf("Age.age: %dn",Age.age);
Age.age=7;
printf("Age.age: %dn",Age.age);
Age.age=8;
printf("Age.age: %dn",Age.age);
return0;
}
OUTPUT:
Sizeof( Age) : 4
Age.age: 4
Age.age: 7
Age.age: 0
typedef
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.
2: Add TwoDistances (in inch-feet) SystemUsing Structures.
3: Add TwoComplex Numbers by Passing Structuretoa Function.
4: CalculateDifferenceBetween TwoTimePeriod.
5: StoreInformation of 10 Students Using Structure.
Session-8
Strings
Stringsareactuallyone-dimensionalarrayofcharactersterminatedbyanullcharacter'0'.
Thusanull-terminatedstringcontainsthecharactersthatcomprisethestringfollowedby
a null.
chargreeting[6]={'H','e','l', 'l', 'o', '0'};
chargreeting[]="Hello";
Program:
#include<stdio.h>
intmain()
{
chargreeting[6]={'H','e','l', 'l', 'o', '0'};
printf("Greetingmessage:%sn",greeting);
return0;
}
OUTPUT: Greeting:Hello
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>
#include<string.h>
intmain()
{
charsrc[40];
chardest[100];
memset(dest, '0',sizeof(dest));
strcpy(src,"ThisisC.com");
strcpy(dest,src);
printf("Finalcopied string:%sn",dest);
return(0);
}
OUTPUT:Finalcopied string:ThisisC.com
Strcat():TheC libraryfunctionchar*strcat(char*dest,constchar*src)appendsthe
stringpointedtobysrctotheend of thestringpointedtobydest.
Declaration:
char*strcat(char*dest,constchar*src)
Parameters:
 dest − This is pointer tothedestination array, which should contain a C string, and
should belargeenough tocontain theconcatenated resulting string.
 src −This is thestring tobeappended. This should not overlap thedestination.
Return Value:
Thisfunctionreturnsapointertotheresultingstringdest.
Program:
#include<stdio.h>
#include<string.h>
intmain()
{
charsrc[50],dest[50];
strcpy(src, "Thisissource");
strcpy(dest,"Thisisdestination");
strcat(dest,src);
printf("Finaldestinationstring:|%s|",dest);
return(0);
}
OUTPUT:Finaldestinationstring:|ThisisdestinationThisissource|
strlen():TheC libraryfunctionsize_tstrlen(constchar*str)computesthelengthofthe
stringstrupto,butnotincludingtheterminatingnullcharacter.
Declaration:
size_tstrlen(constchar*str)
Parameters :
1:str−Thisis thestringwhoselengthistobefound.
Return Value :
Thisfunctionreturnsthelengthofstring.
Program :
#include<stdio.h>
#include<string.h>
intmain()
{
charstr[50];
intlen;
strcpy(str,"Thisisc.com");
len= strlen(str);
printf("Lengthof|%s|is|%d|n",str,len);
return(0);}
OUTPUT :Lengthof|Thisisc.com|is |26|
Strcmp():The Clibraryfunctionintstrcmp(constchar*str1,constchar*str2)compares
thestringpointedto,bystr1tothestringpointedtobystr2.
Declaration:
intstrcmp(constchar*str1,constchar*str2)
Parameters:
 str1 −This is thefirst string tobecompared.
 str2 −This is thesecond string tobecompared.
Return Value:
This function return values that are as follows −
 if Return value< 0 then it indicates str1 is less than str2.
 if Return value> 0 then it indicates str2 is less than str1.
 if Return value= 0 then it indicates str1 is equaltostr2.
Program:
#include<stdio.h>
#include<string.h>
int main ()
{
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
ret = strcmp(str1, str2);
if(ret < 0)
{
printf("str1 is less than str2");
}
elseif(ret > 0)
{
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>
intmain()
{
constcharstr[]="http://www.ashutoshsrivasatava.com";
constcharch='.';
char*ret;
ret= strchr(str,ch);
printf("Stringafter|%c|is-|%s|n",ch,ret);
return(0);
}
OUTPUT :Stringafter|.|is-|.ashutoshsrivasatava.com|
strstr():TheClibraryfunctionchar*strstr(constchar*haystack,constchar
*needle) functionfindsthefirstoccurrenceofthesubstringneedleinthestringhaystack.
Theterminating'0'charactersarenotcompared.
Declaration:
char *strstr(const char *haystack, const char *needle)
Parameters:
 haystack −This is themain C string tobescanned.
 needle−This is thesmallstring tobesearched with-in haystack string.
Return Value:
Thisfunctionreturnsapointertothefirstoccurrenceinhaystackofanyoftheentire
sequence of characters specified in needle, or a null pointer if the sequence is not
present in haystack.
Program:
#include<stdio.h>
#include<string.h>
intmain()
{
constcharhaystack[20]="Ashutosh";
constcharneedle[10]="Point";
char*ret;
ret= strstr(haystack,needle);
printf("Thesubstringis:%sn",ret);
return(0);
}
OUTPUT: Thesubstringis:Point
QUESTION
1: WAP toCheckifagivenStringisPalindrome.
2:WAP toCheckifaStringisaPalindromewithoutusingtheBuilt-inFunction.
3:WAP toFindtheLargest&Smallest Wordin aString.
Session-9
Pointers
Pointers in“c”languageisa variablethatstores/pointstheaddressofanothervariable.A
pointerin“C” is usedtoallocatedynamicallyi.e. atruntime,thepointervariablemightbe
belongingtoanyof thedatatypesuchasint,float,char,double,short etc.
Program:
#include<conio.h>
#include<stdio.h>
void main()
{
int var1;
charvar2[20];
printf(“Address:%xn”,&var1);
printf(“Address:%xn”,&var2);
getch();
}
OUTPUT : Address : bff5a400
Address :bff5a3f6
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;
}
QUESTION
1: Program to print a string using pointer.
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.
2: WAP to read text from a file.
Array Cont

More Related Content

What's hot (20)

structure and union
structure and unionstructure and union
structure and union
 
Pointers
PointersPointers
Pointers
 
358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Structure In C
Structure In CStructure In C
Structure In C
 
Fnctions part2
Fnctions part2Fnctions part2
Fnctions part2
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
 
Structure and union
Structure and unionStructure and union
Structure and union
 
Class and object
Class and objectClass and object
Class and object
 
Structures
StructuresStructures
Structures
 
Lecture18 structurein c.ppt
Lecture18 structurein c.pptLecture18 structurein c.ppt
Lecture18 structurein c.ppt
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
 
Structure & union
Structure & unionStructure & union
Structure & union
 

Similar to Array Cont

Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4Saranya saran
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptxNagasaiT
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4MKalpanaDevi
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7Rumman Ansari
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)hhliu
 
Presentation on function
Presentation on functionPresentation on function
Presentation on functionAbu Zaman
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5alish sha
 

Similar to Array Cont (20)

Function in c program
Function in c programFunction in c program
Function in c program
 
Function in c
Function in cFunction in c
Function in c
 
Function in c
Function in cFunction in c
Function in c
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
 
C function
C functionC function
C function
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Function in C program
Function in C programFunction in C program
Function in C program
 
functions
functionsfunctions
functions
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
CHAPTER 6
CHAPTER 6CHAPTER 6
CHAPTER 6
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 

More from Ashutosh Srivasatava (15)

First edition and updated edition(BASIC)
First edition and updated edition(BASIC)First edition and updated edition(BASIC)
First edition and updated edition(BASIC)
 
Ccc
CccCcc
Ccc
 
Microsoft word-2007-keyboard-shortcuts
Microsoft word-2007-keyboard-shortcutsMicrosoft word-2007-keyboard-shortcuts
Microsoft word-2007-keyboard-shortcuts
 
Word
WordWord
Word
 
Ad
AdAd
Ad
 
Front tally
Front tallyFront tally
Front tally
 
Ccc
CccCcc
Ccc
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Tally ledger
Tally ledgerTally ledger
Tally ledger
 
PayRoll TALLY ERP9
PayRoll TALLY ERP9PayRoll TALLY ERP9
PayRoll TALLY ERP9
 
Tally erp 9
Tally erp 9Tally erp 9
Tally erp 9
 
O Level
O LevelO Level
O Level
 
Html basics
Html basicsHtml basics
Html basics
 
TALLY ERP ((SHORT CUT)
TALLY ERP ((SHORT CUT)TALLY ERP ((SHORT CUT)
TALLY ERP ((SHORT CUT)
 
It tools and business system
It tools and business systemIt tools and business system
It tools and business system
 

Recently uploaded

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

Array Cont

  • 1. 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
  • 2. 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++) {
  • 3. 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
  • 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])
  • 5. { 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]);
  • 6. 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];
  • 7. 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]
  • 8. 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];
  • 9. 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.
  • 10. 2: WAP to add elements of an array.
  • 11. 3: WAP to count even and odd numbers in an array.
  • 12. 4: WAP to pass array elements to a function.
  • 13. 5: WAP to input and display a matrix.
  • 14. 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.
  • 15. 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 */
  • 16. 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 */
  • 17. 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 –
  • 18. 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; }
  • 19. 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
  • 20. 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.
  • 21. * &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>
  • 22. 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;
  • 23. 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;
  • 24. } /* 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
  • 25. 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;
  • 26. 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
  • 27. Question 1: Display all prime numbers between two Intervals.
  • 28. 2: Check Prime and Armstrong Number by making function.
  • 29. 3: Check whether a number can beexpressed as thesum of two prime number.
  • 30. 4: Writea programin C to find thesquareof any number using the function.
  • 31. 5: Writea programin C to swap two numbers usingfunction.
  • 32. 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
  • 33. { char title[50]; char author[50]; char subject[100]; int book_id; }; AccessingStructure Members: #include<stdio.h> #include<string.h> structBooks { char title[50]; char author[50]; char subject[100]; int book_id; }; intmain() { structBooksBook1; /*DeclareBook1 of typeBook */ structBooksBook2; /*DeclareBook2 of typeBook */ /*book1 specification*/ strcpy(Book1.title,"CProgramming"); strcpy(Book1.author,"NuhaAli"); strcpy(Book1.subject,"CProgrammingTutorial"); Book1.book_id=6495407; /*book2 specification*/ strcpy(Book2.title,"TelecomBilling"); strcpy(Book2.author,"ZaraAli"); strcpy(Book2.subject,"TelecomBillingTutorial"); Book2.book_id=6495700; /* printBook1info*/
  • 34. 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];
  • 35. int book_id; }; /*function declaration */ void printBook( struct Books book ); int main( ) { struct Books Book1; /*DeclareBook1 of typeBook */ struct Books Book2; /*DeclareBook2 of typeBook */ /*book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; /*book 2 specification */ strcpy( Book2.title, "TelecomBilling"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "TelecomBilling Tutorial"); Book2.book_id = 6495700; /*print Book1 info*/ printBook( Book1 ); /*Print Book2 info*/ printBook( Book2 ); return 0; } void printBook( struct Books book ) { 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); }
  • 36. 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; };
  • 37. /*functiondeclaration*/ void printBook(structBooks*book); intmain() { structBooksBook1; /* Declare Book1of typeBook */ structBooksBook2; /*DeclareBook2 of typeBook */ /* book1specification*/ strcpy(Book1.title,"CProgramming"); strcpy(Book1.author,"AshutoshSrivastava"); strcpy(Book1.subject,"CProgrammingLanguage"); Book1.book_id=101; /*book2 specification*/ strcpy(Book2.title,"TelecomBilling"); strcpy(Book2.author,"AshuSrivastava"); strcpy(Book2.subject,"TelecomBilling"); Book2.book_id=102; /*printBook1infobypassingaddressofBook1 */ printBook(&Book1); /*printBook2infobypassingaddressof Book2*/ printBook(&Book2); return0; } void printBook(structBooks*book) { 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); } OUTPUT: Book title:CProgramming Book author:AshutoshSrivastava Book subject:CProgrammingLanguage
  • 38. 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];
  • 39. }; 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;
  • 40. } OUTPUT: data.i: 1917853763 data.f:4122360580327794860452759994368.000000 data.str:CProgramming Bit Fields SupposeyourCprogramcontainsanumberofTRUE/FALSE variablesgroupedina structurecalledstatus,asfollows– struct { unsignedintwidthValidated; unsignedintheightValidated; } status; Program: #include<stdio.h> #include<string.h> /*definesimple structure*/ struct { unsignedintwidthValidated; unsignedintheightValidated; } status1; /*definea structurewithbitfields*/ struct { unsignedintwidthValidated:1;
  • 41. unsignedintheightValidated:1; } status2; intmain() { printf("Memorysizeoccupiedbystatus1:%dn",sizeof(status1)); printf("Memorysizeoccupiedbystatus2:%dn",sizeof(status2)); return0; } OUTPUT:Memory sizeoccupiedbystatus1:8 Memory sizeoccupiedbystatus2:4 Bit Field Declaration: struct { type[member_name]:width; }; Sr.No . Element & Description 1 Type An integer type that determines how a bit-field's value is interpreted. The type may beint, signed int, or unsigned int. 2 member_name Thenameof thebit-field. 3 Width Thenumberofbits inthebit-field.Thewidthmustbeless than or equaltothebit width of thespecified type.
  • 42. struct { unsignedintage:3; } Age; Program: #include<stdio.h> #include<string.h> struct { unsignedintage:3; } Age; intmain() { Age.age=4; printf("Sizeof(Age) : %dn",sizeof(Age)); printf("Age.age: %dn",Age.age); Age.age=7; printf("Age.age: %dn",Age.age); Age.age=8; printf("Age.age: %dn",Age.age); return0; } OUTPUT: Sizeof( Age) : 4 Age.age: 4 Age.age: 7 Age.age: 0 typedef
  • 43. 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
  • 44. 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.
  • 45. 2: Add TwoDistances (in inch-feet) SystemUsing Structures.
  • 46. 3: Add TwoComplex Numbers by Passing Structuretoa Function.
  • 48. 5: StoreInformation of 10 Students Using Structure.
  • 49. Session-8 Strings Stringsareactuallyone-dimensionalarrayofcharactersterminatedbyanullcharacter'0'. Thusanull-terminatedstringcontainsthecharactersthatcomprisethestringfollowedby a null. chargreeting[6]={'H','e','l', 'l', 'o', '0'}; chargreeting[]="Hello"; Program: #include<stdio.h> intmain() { chargreeting[6]={'H','e','l', 'l', 'o', '0'}; printf("Greetingmessage:%sn",greeting); return0; } OUTPUT: Greeting:Hello
  • 50. 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>
  • 51. #include<string.h> intmain() { charsrc[40]; chardest[100]; memset(dest, '0',sizeof(dest)); strcpy(src,"ThisisC.com"); strcpy(dest,src); printf("Finalcopied string:%sn",dest); return(0); } OUTPUT:Finalcopied string:ThisisC.com Strcat():TheC libraryfunctionchar*strcat(char*dest,constchar*src)appendsthe stringpointedtobysrctotheend of thestringpointedtobydest. Declaration: char*strcat(char*dest,constchar*src) Parameters:  dest − This is pointer tothedestination array, which should contain a C string, and should belargeenough tocontain theconcatenated resulting string.  src −This is thestring tobeappended. This should not overlap thedestination. Return Value: Thisfunctionreturnsapointertotheresultingstringdest. Program: #include<stdio.h> #include<string.h> intmain() { charsrc[50],dest[50]; strcpy(src, "Thisissource");
  • 52. strcpy(dest,"Thisisdestination"); strcat(dest,src); printf("Finaldestinationstring:|%s|",dest); return(0); } OUTPUT:Finaldestinationstring:|ThisisdestinationThisissource| strlen():TheC libraryfunctionsize_tstrlen(constchar*str)computesthelengthofthe stringstrupto,butnotincludingtheterminatingnullcharacter. Declaration: size_tstrlen(constchar*str) Parameters : 1:str−Thisis thestringwhoselengthistobefound. Return Value : Thisfunctionreturnsthelengthofstring. Program : #include<stdio.h> #include<string.h> intmain() { charstr[50]; intlen; strcpy(str,"Thisisc.com"); len= strlen(str); printf("Lengthof|%s|is|%d|n",str,len); return(0);} OUTPUT :Lengthof|Thisisc.com|is |26|
  • 53. Strcmp():The Clibraryfunctionintstrcmp(constchar*str1,constchar*str2)compares thestringpointedto,bystr1tothestringpointedtobystr2. Declaration: intstrcmp(constchar*str1,constchar*str2) Parameters:  str1 −This is thefirst string tobecompared.  str2 −This is thesecond string tobecompared. Return Value: This function return values that are as follows −  if Return value< 0 then it indicates str1 is less than str2.  if Return value> 0 then it indicates str2 is less than str1.  if Return value= 0 then it indicates str1 is equaltostr2. Program: #include<stdio.h> #include<string.h> int main () { char str1[15]; char str2[15]; int ret; strcpy(str1, "abcdef"); strcpy(str2, "ABCDEF"); ret = strcmp(str1, str2); if(ret < 0) { printf("str1 is less than str2"); } elseif(ret > 0)
  • 54. { 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>
  • 55. intmain() { constcharstr[]="http://www.ashutoshsrivasatava.com"; constcharch='.'; char*ret; ret= strchr(str,ch); printf("Stringafter|%c|is-|%s|n",ch,ret); return(0); } OUTPUT :Stringafter|.|is-|.ashutoshsrivasatava.com| strstr():TheClibraryfunctionchar*strstr(constchar*haystack,constchar *needle) functionfindsthefirstoccurrenceofthesubstringneedleinthestringhaystack. Theterminating'0'charactersarenotcompared. Declaration: char *strstr(const char *haystack, const char *needle) Parameters:  haystack −This is themain C string tobescanned.  needle−This is thesmallstring tobesearched with-in haystack string. Return Value: Thisfunctionreturnsapointertothefirstoccurrenceinhaystackofanyoftheentire sequence of characters specified in needle, or a null pointer if the sequence is not present in haystack.
  • 59. Session-9 Pointers Pointers in“c”languageisa variablethatstores/pointstheaddressofanothervariable.A pointerin“C” is usedtoallocatedynamicallyi.e. atruntime,thepointervariablemightbe belongingtoanyof thedatatypesuchasint,float,char,double,short etc. Program: #include<conio.h> #include<stdio.h> void main() { int var1; charvar2[20]; printf(“Address:%xn”,&var1); printf(“Address:%xn”,&var2); getch(); } OUTPUT : Address : bff5a400 Address :bff5a3f6
  • 60. 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.
  • 61. 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.
  • 62. 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
  • 63. 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:
  • 64. #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 () {
  • 65. 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] ); }
  • 66. 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;
  • 67. /* 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)
  • 68. { /* 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;
  • 69. 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 */
  • 70. 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; }
  • 71. QUESTION 1: Program to print a string using pointer.
  • 72. 2: Program to read array elements and print with addresses.
  • 73. 3: Program to print size of different types of pointer variables.
  • 74. 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.
  • 75. 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+
  • 76. 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>
  • 77. 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()
  • 78. { 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:
  • 79. 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.
  • 80. 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; };
  • 81. 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
  • 82. { 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)
  • 83. 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
  • 84. 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.
  • 85. 2: WAP to read text from a file.