Sie sind auf Seite 1von 36

Programming and Data Structures I

Unit -I

Control Statements
Control statements are of 2 types
1. Decision making and Branching
2. Decision making and Looping
Decision making here refers to the condition we are going to check in the program.
The condition may return a value either true or false

Branching
If the condition returns the value as true one part of the program statements will be executed
otherwise another part of the program will get executed.

Looping
Till a condition is satisfied it is going to execute the same set of statements

Decision making and Branching (Conditional statement)


Simple if statement
if..else statement
Nested if..else
else..if ladder
switch..case
go to
ternary operator

Decision making and Looping(Control Statement)


for
while and do..while

Decision making and Branching


Simple if statements
checks a condition and if it is true it will execute a part of the program.If the condition is false ,
no process will be done

Syntax
if(condition)
{
statements;
}
The statements now available within the if block will get executed when the condition is true.
If the block contains only one statement there is no need of the { } braces

Example
main()
{
int i;
printf("Enter a number");
scanf("%d",&i);
if(i>9)
printf("2 digit number");
}

Programming and Data Structures I

Unit -I

Output
Enter a number
10
2 digit number
Enter a number
5
when the program is executed it will ask for a number If the user gives a value which is greater
than 9 it will show the output as 2 Digit number otherwise there won't be any output

if .. else statements
checks a condition and if it is true it will execute a part of the program.If the condition is false ,
the other part of the program block will get executed.

Syntax
if(condition)
{
statements;
}
else
{
statements;
}
The statements now available within the if block will get executed when the condition is true and
when it is false statements within the else block will get executed. If the block contains only one
statement there is no need of the { } braces

Example
main()
{
int i;
printf("Enter a number");
scanf("%d",&i);
if(i>9)
printf("2 digit number");
else
printf("Single digit number");
}
Output
Enter a number
10
2 digit number
Enter a number
5
Single digit number
when the program is executed it will ask for a number. If the user gives a value which is greater
than 9 it will show the output as 2 Digit number. If the value entered is less than 10 , it will show
the result as Single digit number.

Programming and Data Structures I

Unit -I

Nested if .. else statements


checks a condition and if it is true it will check another condition, if it's also true it will check the
other condition

Syntax
if(condition)
{
if(condition)
{
if(condition)
{
statements;
}
else
{
statements;
}
else
{
statements;
}
else
{
statements;
}
when the first condition is satisfied it will go and check the next condition till it reaches the last
if. when the condition is false it will execute the statements available within the else block. If the
block contains only one statement there is no need of the { } braces

Example
main()
{
int i;
printf("Enter a number");
scanf("%d",&i);
if(i>9)
if(i>99)
if(i>999)
printf("3 digit number");
else
printf("4 digit number");
else
printf("2 digit number");
else
printf("Single digit number");
}

Programming and Data Structures I

Unit -I

Output
Enter a number
10
2 digit number
Enter a number
5
Single digit number
Enter a number
102
3 digit number

Enter a number
5213
4 digit number
when the program is executed it will ask for a number. If the user gives a value which is greater
than 9 it will check for the next condition i > 99 , then to next condition i > 999 . If that's
also true then it will show the output as 3 Digit number.
If the value entered is less than 100 , it will show the result as 2 digit number.
If the value entered is less than 10 , it will show the result
as Single digit number.

else .. if ladder
checks a condition and if it is true it will execute that part , otherwise it will check the other
condition

Syntax
if(condition)
{
statements;
}
else if(condition)
{
statements;
}
else if(condition)
{
statements;
}
else
{
statements;
}
when the first condition is satisfied it will execute the statements under that block otherwise it
will check the next condition and so on. when all the condition fails it will execute the statements
available within the else block

Programming and Data Structures I

Unit -I

If the block contains only one statement there is no need of the { } braces

Example
main()
{
int i;
printf("Enter a number");
scanf("%d",&i);
if(i<10)
printf("Single digit number");
else if(i>9 && i<100)
printf("2 Digit number");
else if(i>99 && i<1000)
printf("3 Digit number");
else
printf("4 Digit number");
}

Output
Enter a number
10
2 digit number
Enter a number
5
Single digit number
Enter a number
102
3 digit number
Enter a number
5213
4 digit number
when the program is executed it will ask for a number. If the user gives a value which is less than
10 , it will print the result as Single digit number otherwise it will check the
next condition .If the value entered is less than 100 , it will show the result as 2 digit number. If
the value entered is less than 10 , it will show the result as Single digit number.

switch .. case
The control statements which allow us to make a decision from the number of choices is called a
switch or more correctly a switch-case-default , since these three keywords go together to make
up the control statement.

Syntax
switch(integer or character variable)
{
case 1:
statements;
break;

Programming and Data Structures I


case 2:
statements;
break;
case 3:
statements;
break;
default:
statements;
}

break after each case is used to terminate the process there itself.

Example
main()
{
int a,b,res;
char op;
clrscr();
printf("Enter the value of a\n");
scanf("%d",&a);
printf("Enter the value of b");
scanf("%d",&b);
printf("Enter the operation you want to perform(+,-,*,/,%)");
op=getch();
printf("%c",op);
switch(op)
{
case '+':
res=a+b;
break;
case '-':
res=a-b;
break;
case '*':
res=a*b;
break;
case '/':
res=a/b;
break;
case '%':
res=a%b;
break;
default:
printf("Not a legal operator");
}
printf("\nresult of %d %c %d is %d",a,op,b,res);
getch();
}

Unit -I

Programming and Data Structures I

Unit -I

In the above program the user has been provided with a set of options

+ , - , * , / , %.
Based on the selection of operator by the user it is going to execute only that part of the
statements in the switch block. After completing the execution the break command at the end
transfer the control to the statement after switch block

goto
A goto statement can be used to transfer the control almost anywhere in the program.
It's use is one of the reasons that programs become unreliable , unreadable and hard to debug.
With good programming skills , goto can always be avoided

Example
main()
{
int a;
back:
printf("Enter a number");
scanf("%d",&a);
if(a<0)
goto back;
printf("%d",a); }
Output
Enter a number
-8
Enter a number
5
5
If a negative number is given it is going to again execute and ask for the number.
If it is greater than 0 (ie) positive then it will the number that has been entered
As the goto statement returns the control to the previous statements , we can also
call this as backward jump. If the goto statement returns the control to the statements which are
following , we can call this as forward jump.

Ternary Operator
This operator can be used as an alternative for the if..else statements.This is also
called as conditional operators.

Syntax
condition?statements:statements;

Example
main()
{
int a,b;
printf("Enter 2 numbers");
scanf("%d %d",&a,&b);
a>b?printf("\nbig = %d",a):printf("\nbig = %d",b);
}

Output

Programming and Data Structures I

Unit -I

Enter 2 numbers
10
20
big = 20

Decision making and Looping


for loop
Syntax
for(initialisation;condition;increment or decrement operation)
{
statements;
}

Example
main()
{
int i;
for(i=1;i<=10;i++)
printf("%d ",i);
}

Output
1 2 3 4 5 6 7 8 9 10
As there are 2 blank spaces after printing the value of i each time , it is leaving 2 blank spaces
after that
Another example program which prints the multiplication table upto a given number
We have to get the number upto which the table has to be printed as well as the maximum
number in each table. Here we are going to use 2 variables one as i and the other as j.
i is for the number upto which we want j is for the times each table has to be printed

Program
main()
{
int i,j,max,times;
printf("Enter the number upto which the table is required\n");
scanf("%d",&max);
printf("Enter the max number upto which each table has to be printed");
scanf("%d",&times);
for(i=1;i<=max;i++)
{
for(j=1;j<=times;j++)
{
printf("%d * %d = %d\t",i*j);
}
printf("\n");
}
}

Programming and Data Structures I

Unit -I

Output
Enter the number upto which table is required
3
Enter the max number upto which each table has to be printed
3
1*1=1
1*2=2
1*3=3
2*1=2
2*2=4
2*3=6
3*1=3
3*2=6
3*3=9

While loop
This is one kind of loop which will do repeatedly the statements available under a block if a
condition is satisfied.
In some situations after the processing of the statements is over there may be decrease or
increase in the value of the varaible which is not of a standard one . It may be changing
unevenly at each stage. In this situations we were not be able to use the for loop which can be
used only for a fixed increment or decrement values.
For example if we want to reverse a number given as an input by the user the for loop won't
help as each and every stage of the reverse process will give different values

Syntax
while(condition)
{
statements;
}
As the condition is checked before executing the statements we can call this as an
entry controlled loop

Example
Program to reverse a number
main()
{
int m,n,rem,sum=0;
printf("Enter a number");
scanf("%d",&n);
m=n;
while(n>0)
{
rem=n%10;
sum=sum*10+rem;
n=n/10;
}
printf("\nReverse of the given number %d is %d",m,sum);
}
when we run the program first it will ask the user to enter a number. The number will be stored
in the variable n and the same will be stored in m also. If the user has given the number as 0 or

Programming and Data Structures I

Unit -I

at one stage if the value available in n is 0 , then that is the stage to stop the process. Suppose if
the user has given the number as 145 then the processing steps will be

1. sum=0
rem=154%10 = 4
sum=0*10+4 = 4
n=154/10 = 15
2. sum=4
rem=15%10 = 5
sum=4*10+5 = 45
n=15/10 = 1
3. sum=45
rem=1%10 = 1
sum=45*10+1 = 451
n=1/10 = 0
Output

Enter a number
154
Reverse of the given number 154 is 451

do..while
while and do..while loop behave in a similar manner.
The major difference between while and do..while is While loop checks the condition before
executing the statements. do..while loop will execute the statements then check the
condition.Even if the condition fails do..while is going to execute the statements whereas in
while it won't.

Syntax
do
{
statements;
}while(condition);
As the condition is checked after executing the statement it is also called as exit contolled loop

Example
main()
{
while(1>2)
printf("wonder");
}
It won't print anything in this case as the condition 1>2 fails.
main()
{
do
{
printf("wonder");
}
while(1>2);

Programming and Data Structures I

Unit -I

}
If we write the same thing in do..while then it will print the word wonder then only checks the
condition. It will useful in situations where we want to do the process more than once according
to the user's choice.

Arrays
A variable can hold only one value at a time. In some situations we want to store more than
one value in the same name. we've to create as many number of variables as we want to store the
values. If we use for each and every value a seperate variable then there will be confusion to
find out a particular value and each variable will have its own memory location which results
in longer retrieval time.
To avoid that we can go for arrays wherein we can store more than one value of the same
data type in a single name. Array is also called as subscripted variables. Each value will be
identified by its index number. Array index always starts from 0. Array which contains only a
single row and different number of columns are called Single dimensional array. Array which
contains both rows and columns are called 2 Dimensional array.

Declaration of an array variable


datatype nameofarray[size];
Here datatype can be any valid data type available in C.
It may be an int , float , char , long or double
nameofarray can be any valid variable name
size refers to the number of elements an array can hold.

(eg)
int a[10];
Here datatype is int , array name is a and the size of the array is 10.
This indicates that the array can have maximum of 10 values all of the same data type int and
it will be stored from index numbers 0 to 9 . It can store totally 10 elements from index 0 to
9. Totally 20 bytes of memory will be allocated for this as each value will occupy 2 bytes in
memory. The array can have even only one value or it might have been declared and no value
has been placed. In this situation the values at the other index numbers which are not having
any values will be filled by its own values which is also called as Garbage values. Whenever
we refer the array name it will have the starting address of that array. The array by itself has a
built in Pointer with which it is going to find out the values available in the index numbers
specified. If an array has been declared with the name a and size as 10 , a will be allocated 20
bytes of memory and the starting address of the array will be given whenever we print the
value of a.
If the value available at index number 5 is required , then it is going to find the address of that
specified index using the starting address and the number of bytes required for each index.
For example if the array has the starting address as 64232 then it is going to calculate the
address of index number 5 using
64232+5*2=64332
Each index is going to occupy 2 bytes. So to reach the 5th position we have to move 10 bytes
away from the starting address.This has been done internally by the system.

Programming and Data Structures I

Unit -I

Example of using Array


Program to arrange numbers in ascending order
Here we are going to use a method called Bubble sort or exchange sort.
A number at the position 1 will be compared with all the remaining numbers in the array.
If any number is found to be lesser than the number at position 1 both numbers positions has to
be changed by exchanging the values available in that.
main()
{
int a[10],i,j,n,temp;
/* getting no of elements in array */
printf("Enter no of elements in the array");
scanf("%d",&n);
/* Getting values for elements in array */
printf("\nEnter %d values",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
/* Sorting Process */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
/* Interchange if 1st value is > 2nd */
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
/* Printing the numbers in array */
printf("\nSorted array\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
Output
Enter no of elements in the array
6
Enter 6 values
12 56 43 23 11 1
Sorted array
1
11
12
23
43
56

Programming and Data Structures I

Unit -I

String Functions
When we want to enter more than one name which contains a group of character it is not possible
with the help of single dimensional array. We require a 2 dimensional array for storing more than
one name so that each name will be stored as a seperate row.

\0

\0

\0

\0

\0

The end of each name will be identified by the special character '\0' which indicates the end of a
name .To do any operation on the strings that has been placed in this form we require string
functions which are available under the header file named as string.h
Some of the string functions available are
1.strlen(string)
To find no of characters in a string
2..strcpy(str1,str2)
To copy contents of one string into another (str2 to str1)
str1 --> destination
str2 --> source
3.strcat(str1,str2)
To add the new content of str2 into the existing content of str1
4.strcmp(str1,str2)

Programming and Data Structures I

Unit -I

To compare 2 strings character by character and will return an integer value. The value
may be 0 , +ve no or a -ve no
value will be 0 if contents of both string are equal
value will be a +ve number if the first string is alphabetically greater than second value
will be a -ve number if the first string is alphabetically lesser than second
5.strrev(string)
To reverse a given string
6.strupr(string)
To convert the characters in the string to uppercase
7.strlwr(string)
To convert the characters in the string to lowercase
With the help of the string functions only it is possible to write a program which will sort the
names in sorted order (ie) ascending order.
To do this we require 2 functions
1. strcmp()
2. strcpy()
3. strcmp() to find out whether any interchange of positions is required
to arrange it in order. If any interchange is required we can do that with the use of strcpy()
which copies the contents of one string to another

Program to sort names in alphabetical order


main()
{
char name[20][20],temp[20];
int i,j,n;
clrscr();
printf("Enter total no of persons\n");
scanf("%d",&n);
printf("\nEnter %d names\n",n);
for(i=0;i<n;i++)
scanf("%s",name[i]);
printf("Sorted values\n");
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(name[i],name[j])>0)
{

Programming and Data Structures I

Unit -I

strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("\nNames after sorting\n");
for(i=0;i<n;i++)
printf("%s\n",name[i]);
}
Output
Enter total no of persons
4
Enter 4 names
vinod
mahesh
rajiv
arun
Names after sorting
arun
mahesh
rajiv
vinod

Program to check whether a given string is palindrome


or not
main()
{
char name[20],revname[20];
int len,i,j=0;
printf("Enter a name");
scanf("%s",name);
printf("\nName entered is %s",name);
len=strlen(name);
for(i=len-1;i>=0;i--)
{
revname[j]=name[i];
j++;
}
printf("\nReversed name is %s",revname);
if(strcmp(name,revname)==0)
printf("\nString %s is a palindrome",name);
else
printf("\nString %s is not a palindrome",name);

Programming and Data Structures I

Unit -I

}
Output
1.
Enter a name
liril
Name entered is liril
Reversed name is liril
String liril is a palindrome
2.
Enter a name
suresh
Name entered is suresh
Reversed name is hserus
String suresh is not a palindrome

Program to concatenate 2 strings


/* Program to concatenate 2 strings without using strcat() function */
main()
{
char name[20],name1[20];
int len,i,j;
printf("Enter 2 names");
scanf("%s %s",name,name1);
printf("\nNames entered are %s %s",name,name1);
len=strlen(name);
j=len;
for(i=0;i<strlen(name1);i++)
{
name[j]=name1[i];
j++;
}
name[j]='\0';
printf("\nNames after concatenation %s %s",name,name1);
}
Output
Enter 2 names
suresh
kumar
Names entered are suresh kumar
Names after concatenation sureshkumar kumar
Functions
Function is a sub program which will be useful when we want to do some operations
repeatedly in a program

Programming and Data Structures I

Unit -I

Syntax
======
returntype functionname(arguments)
{
statements;
}
The values which we are going to pass to the function are called as actual arguments and the
name we are going to use in the function definition to store the values we call it as formal
arguments
The operation what we are going to do with the function has been written separately outside the
main() , which we call it as function definition
Types
=====
1. Function without arguments , without any return type.
No Arguments passed from main to the sub function and no value returned from sub to main
2. Function with arguments , without any return type
Arguments value passed from main to sub function but no value is returned from sub function
to main
3. Function with arguments , with return type
arguments value passed from main to sub function as well as some value is returned from sub
to main.
It can return a maximum of one value
(eg)
1)
main() /* Main Function */
{
add(); /* Function call */
}
add() /* Sub Function with name as add
without arguments */
{
int a,b;
printf("Enter 2 numbers");
scanf("%d %d",&a,&b);
printf("Sum = %d",a+b);
}
2)
main()
{
int a,b;
printf("Enter 2 numbers");
scanf("%d %d",&a,&b);
add(a,b); /* Function called by passing 2
arguments a & b*/
}

Programming and Data Structures I


add(int x,int y)

Unit -I

/* Function add with 2


arguments x ,y*/

{
printf("Sum = %d",x+y);
}
3)
main()
{
int a,b,c;
printf("Enter 2 numbers");
scanf("%d %d",&a,&b);
c=add(a,b); /*Function called by passing
2 args a,b result is stored in c*/
printf("Sum = %d",c);
}
add(int x,int y)
{
return(x+y); /* returning a value from function
add to main()*/
}
Function returning a float value
This program uses a function named add with 2 arguments of datatype float. It is going to return
the result which is again float datatype. The default return type allowed in 'C' is int. If it returns a
data other than int , then we
should specify the return type in the function definition as well as we have to declare the
function in the main by mentioning the
returntype functionname(datatype of arguments)
This we call it as function declaration orfunction prototype.
main()
{
float a,b,c;
float add(float,float); /* Function prototype
or function declaration */
printf("Enter 2 numbers");
scanf("%f %f",&a,&b);
c=add(a,b);
printf("\nSum = %f",c);
}
float add(float x,float y)
/* float is the data type
of the returning value */
111{
return(x+y);

Programming and Data Structures I


}
Output
Enter 2 numbers
12.45
23.23
Sum = 35.68

Passing single dimension array to function


main()
{
int i,n,a[10],big;
printf("Enter no of elements in the array");
scanf("%d",&n);
printf("\nEnter %d values",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
big=max(a,n);
printf("\nLargest value in the array is %d",big);
}
max(int b[],int m)
{
int large=b[0],i;
for(i=1;i<m;i++)
{
if(b[i]>large)
large=b[i];
}
return(large);
}
Output
Enter no of elements in the array
5
Enter 5 values
45
3
278
1
24
Largest value in the array is 278

Passing 2 Dimensional array to functions


main()
{
int a[5][5],b[5][5],r1,c1,r2,c2,i,j;
printf("\nEnter no of rows and columns of first
matrix");

Unit -I

Programming and Data Structures I


scanf("%d %d",&r1,&c1);
printf("\nEnter rows and columns of second
matrix");
scanf("%d %d",&r2,&c2);
if(r1==r2 && c1==c2)
{
printf("Enter %d values for first matrix",r1*c1);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
printf("Enter %d values for second matrix",r1*c1);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&b[i][j]);
printf("\nResultant Matrix\n");
matadd(a,b,r1,c1);
}
else
printf("\nMatrix addition not possible");
}
matadd(int x[][5],int y[][5],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d\t",x[i][j]+y[i][j]);
printf("\n");
}
}
Output
Enter no of rows and columns of first matrix
2
2
Enter no of rows and columns of second matrix
3
2
Matrix addition not possible
2)
Enter no of rows and columns of first matrix
2
2
Enter no of rows and columns of second matrix

Unit -I

Programming and Data Structures I


2
2
Enter 4 values for first matrix
2
3
4
5
Enter 4 values for second matrix
5
6
7
8
Resultant Matrix
7
9
11
13

Function with pointers


main()
{
int a,b;
clrscr();
printf("Enter values for a and b\n");
scanf("%d %d",&a,&b);
printf("Value of a and b before swapping\n");
printf("\n%d %d",a,b);
swap(&a,&b);
printf("\nValue of a and b after swapping ");
printf("\n%d %d",a,b);
}
swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Output
Enter values for a and b
10
15
Value of a and b before swapping
10
15
Value of a and b after swapping
15

Unit -I

Programming and Data Structures I

Unit -I

10

C Preprocessor
Preprocessor by the name itself indicates the process before actual compilation of the source
code. The preprocessor is indicated by the symbol # which will be written normally before the
main() function. When a program is compiled with the compiler first it will search for a macro
which may have small definitions or functions. If any preprocessor statement is available it goes
through the entire program in search of the places where it has been used. In all these places the
macros will be substituted then only the compilation process begins.
It can be used to define variables as shown here
# define LIMIT 20
main()
{
int i;
for(i=1;i<=LIMIT;i++)
printf("=");
}
It will print the '=' symbol 25 times. It can be used to define operators as shown here.
#define AND &&
main()
{
int a,b;
printf("Enter 2 numbers");
scanf("%d %d",&a,&b);
if(a>9 AND a<100)
printf("2 digit number");
}
Instead of using && we've used AND which does the same operation. It can be used to replace
conditions as shown here
#define RANGE (a>25 && a<50)
main()
{
int a=30;
if(RANGE)
printf("Within range");
else
printf("Outside range");
}
It can be used to replace an entire C statement also
#define YES printf("Agreed");

Programming and Data Structures I

Unit -I

main()
{
char ch;
ch=getch();
if(ch=='y')
YES;
else
printf("No");
}
Macros with arguments
Macros can also have arguments just as the functions have.
#define AREA(x) (3.14*x*x)
main()
{
float r1=2.5,r2=4.5,a;
a=AREA(r1);
printf("\nArea of circle = %f",a);
a=AREA(r2);
printf("\nArea of circle = %f",a);
}
Output
19.625
63.585
Don't leave any blank space between AREA and (x).If a blank is there , it will be taken as macro
expansion and not as an argument. The entire macro expansion should be within paranthesis.
Otherwise it will replace the expansion and not the result
For example if we have a macro defined as
#define SQUARE(n) n*n
like this when the macro is expanded
i= 128/SQUARE(4)
it will be replaced as 128/4*4 which results in 128 whereas if you use it within paranthesis when
it is expanded it will be taken as 128/16 which results in 8.
File Inclusion
To include the content of one file into another we require this. It can be used in 2 cases
1. If we have a very large program , the code may be too long and it is better to divide it into
smaller parts.
2. we may require some functions or macro definitions in more than one program.At that time
also we require this so that the once written code can be used everywhere.
we can include a file by using #include directive.
we can use this in 2 forms
#include
#include "filename"
when we use #include it look for the files in specified directories only (include directory)

Programming and Data Structures I

Unit -I

when we use #include "filename" it will search in current directory as well as in the specified
directories also.
Conditional compilation
we can make the compiler skip over a part of the source code by inserting the preprocessing
commands #ifdef and #endif
Syntax
#ifdef macroname
statement 1;
statement 2;
statement 3;
#endif
if macroname has been #defined the block of code will be processed as usual.
This will be useful when some part of the code has to be rewritten with some other code so that
when required we can have the old code also.
Example
main()
{
#ifdef YES
statement 1;
statement 2;
statement 3;
statement 4;
#endif
statement 5;
statement 6;
}
If the macro YES is defined then it is going to process statements 1,2,3,4 otherwise it is going to
process statements 5 & 6. At later stages if you want the old code to be used delete the #ifdef and
#endif statements
#if and #elif directives
The #if directive can be used to test whether an expression evaluates to a nonzero value. If the
result is zero else part will get executed
Example
#if ADAPATER==MA
code for monochrome adapter
#else
#if ADAPATER==CGA
code for color graphics adapter
#else
#if ADAPATER==EGA
code for Enhanced adapter
#else
code for super VGA
#endif
#endif

Programming and Data Structures I

Unit -I

#endif

Pointers
Pointer is a variable which contains the address of another variable The value of each variable
will be stored in RAM.
To create a pointer variable use the datatype to specify and with a * symbol before
Using the * symbol it is going to identify that variable as a pointer variable. If we declare an
integer variable as
int a,*p1;
p1=&a;
To access the value of the variable of whose address we should use * usually known as
indirection operator
Pointer variable p1 will have the address of the variable a. we can use the pointer variable p1 to
store the memory location of another variable a. The variable a has a separate memory location
where the value stored is 100.The pointer variable p1 will have a separate memory location and
the value in that will be the address of the variable a.

Address of a

64510

100
Address of p1 : 64540

64510

Pointer showing the address and value


main()
{
int a[10],i,n;
printf("Enter no of elements");
scanf("%d",&n);
printf("\nEnter %d values",n);
for(i=0;i<n;i++)

Programming and Data Structures I


scanf("%d",&a[i]);
printf("\nAddress of first element\n");
printf("%u %u %u",a,&a,&a[0]);
printf("\nAddress of 2nd element\n");
printf("\n%u",&a[2]);
printf("\nValue of 2nd element\n");
printf("\n%d",*(a+2));
}
Output
Enter no of elements
5
Enter 5 values
15
43
67
89
90
Address of first element
64532 64532 64532
Address of 2nd element
64536
Value of 2nd element
67
Pointers in mathematical expressions
main()
{
int a,b,*p1,*p2,x,z;
clrscr();
a=12;
b=4;
p1=&a;
p2=&b;
x=*p1 * *p2-6;
printf("Address of a = %u\n",p1);
printf("Address of b = %u\n",p2);
printf("\n");
printf("a = %d , b = %d\n",a,b);
printf("x = %d\n",x);
*p2=*p2+3; /* b=b+3 */
*p1=*p2-5; /* a=b-5 */
z=*p1**p2-6;
printf("\na = %d,b = %d",a,b);
printf("\nz = %d",z);
}
Output

Unit -I

Programming and Data Structures I


Address of a = 64232
Address of b = 64234
a = 12 , b=4
x = 42
a= 2,b=7
z=8

Unit -I

Programming and Data Structures I


Pointers in single dimensional array
main()
{
int a[10],i,j,n;
printf("\nEnter max no of elements");
scanf("%d",&n);
printf("\nEnter %d values",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,n);
printf("\nSorted array");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
/* Function */
sort(int b[],int m)
{
int temp,i,j;
for(i=0;i<m-1;i++)
{
for(j=i+1;j<m;j++)
{
if(*(b+i)> *(b+j))
{
temp=*(b+i);
*(b+i)=*(b+j);
*(b+j)=temp;
}
}
}
}
Output
Enter max. no of elements
6
Enter 6 values
24
45
3
12
56
2
Sorted Array
2
3
12
24

45

56

Unit -I

Programming and Data Structures I


Pointers in 2 dimensional arrays
main()
{
int a[10][10],b[10][10],i,j,k,r,c;
printf("\nEnter rows and columns of matrix");
scanf("%d %d",&r,&c);
printf("\nenter values of the first matrix");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter values of second matrix");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\nResultant matrix\n");
matadd(a,r,c,b);
}
/* function to add 2 matrices using pointers */
matadd(int a[][10],int r,int c,int b[][10])
{
int dc[10][10],i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
/*dc[i][j]=*(*(a+i)+j)+*(*(b+i)+j);*/
dc[i][j]=*(a[i]+j)+*(b[i]+j);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d %u\t",dc[i][j],&dc[i][j]);
}
printf("\n");
}
}

Unit -I

Programming and Data Structures I

Unit -I

Output
Enter rows and columns of matrix
2
2
Enter values of first matrix
1
2
3
4
Enter values of second matrix
5
6
7
8
Resultant matrix
6
8
10
12
/*
Note
====
In 2 Dimensional array each row is treated as one single dimensional array
a[0][0],a[0][1] will be treated as one single dimension array. If we refer as a[0] it
refers to starting address of that single dimensional array. If we refer as a[0]+1 it
refers to the second elements address in that array */
Alphabetical sorting using Pointers
main()
{
char name[5][15],temp[15];
int i,j,n;
printf("Enter total names");
scanf("%d",&n);
printf("\nEnter %d names",n);
for(i=0;i<n;i++)
scanf("%s",name[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(*(name+i),*(name+j))>0)
{
strcpy(temp,*(name+i));
strcpy(*(name+i),*(name+j));
strcpy(*(name+j),temp);
}

Programming and Data Structures I


}
}
printf("\nSorted array");
for(i=0;i<n;i++)
printf("%s\n",name[i]);
}
Output
Enter total names
5
Enter 5 names
mohan
kathir
sundar
arun
hari
Sorted array
Arun
hari
kathir
mohan
sundar
Reverse a string using Pointers
/* Program to reverse a string using pointers */
main()
{
char na[20],*s;
int i,j=0,ctr=0;
printf("Enter a string\n");
gets(na);
/*scanf("%s",na);*/
while(na[j]!='\0')
{
ctr++;
j++;
}
s=na+ctr-1;
printf("\nReversed string is ");
while(ctr>0)
{
printf("%c",*s);
s--;
ctr--;

Unit -I

Programming and Data Structures I


}
}
Output
Enter a string
raj
Reversed string is jar

Pointers in structure
/* Using Pointer with structure */
struct invent
{
char name[20];
int num;
int price;
}product[3],*ptr;
main()
{
/*struct invent product[3],*ptr;*/
printf("Enter values for name,num and price\n");
for(ptr=product;ptrname,&ptr->num,&ptr->price);
printf("\n values entered are \n");
ptr=product;
while(ptrname,ptr->num,ptr->price);
ptr++;
}
}
Output
Enter value for name , num and price
pen
1
15
pencil
2
2
stapler
3
25
Values entered are
pen
1
15
pencil
2
2
stapler
3
25
Pointers in functions

Unit -I

Programming and Data Structures I

Unit -I

Call by Value
Calling the function by passing the exact value of arguments from the main() function. The
arguments available in the function definition will have a copy of the value of the arguments
passed from main() but in a different location.
Any changes made inside the function will affect the values of the variables used inside the
function and it wont affect the location of the variable passed from main()
main()
{
int a,b;
clrscr();
printf("Enter values for a and b\n");
scanf("%d %d",&a,&b);
printf("Value of a and b before swapping\n");
printf("\n%d %d",a,b);
swap(a,b);
printf("\nValue of a and b after swapping ");
printf("\n%d %d",a,b);
}
swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
}

Output
Enter values for a and b
10
15
Value of a and b before swapping
10
15
Value of a and b after swapping
10
15
Call by reference
Instead of passing the value for the arguments for a function we are passing the address of the
arguments. The exact value available in the locations can be got from the pointer notation. By
using the address instead of value the exact location of the variables can be accessed and any
changes made in that will be made in the exact locations of the variables.
main()
{
int a,b;
clrscr();
printf("Enter values for a and b\n");
scanf("%d %d",&a,&b);

Programming and Data Structures I

Unit -I

printf("Value of a and b before swapping\n");


printf("\n%d %d",a,b);
swap(&a,&b);
printf("\nValue of a and b after swapping ");
printf("\n%d %d",a,b);
}
swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}

Output
Enter values for a and b
10
15
Value of a and b before swapping
10
15
Value of a and b after swapping
15
10

Functions with variable number of arguments


Sometimes, you may come across a situation, when you want to have a function, which can take
variable number of arguments, i.e., parameters, instead of predefined number of parameters. The
C programming language provides a solution for this situation and you are allowed to define a
function which can accept variable number of parameters based on your requirement. The
following example shows the definition of such a function.
int func(int, ... )
{
.
.
}
int main()
{
func(1, 2, 3);
func(1, 2, 3, 4);
}
It should be noted that function func() has last argument as ellipses i.e. three dotes (...) and the
one just before the ellipses is always an int which will represent total number variable arguments
passed. To use such functionality you need to make use of stdarg.h header file which provides

Programming and Data Structures I

Unit -I

functions and macros to implement the functionality of variable arguments and follow the
following steps:
Define a function with last parameter as ellipses and the one just before the ellipses is
always an int which will represent number of arguments.
Create a va_list type variable in the function definition. This type is defined in stdarg.h
header file.
Use int parameter and va_start macro to initialize the va_list variable to an argument
list. The macro va_start is defined in stdarg.h header file.
Use va_arg macro and va_list variable to access each item in argument list.
Use a macro va_end to clean up the memory assigned to va_list variable.
Now let us follow the above steps and write down a simple function which can take variable
number of parameters and returns their average:
#include <stdio.h>
#include <stdarg.h>
double average(int num,...)
{
va_list valist;
double sum = 0.0;
int i;
/* initialize valist for num number of arguments */
va_start(valist, num);
/* access all the arguments assigned to valist */
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int);
}
/* clean memory reserved for valist */
va_end(valist);
return sum/num;
}
int main()
{
printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}
When the above code is compiled and executed, it produces the following result. It should be
noted that the function average() has been called twice and each time first argument represents
the total number of variable arguments being passed. Only ellipses will be used to pass variable
number of arguments.
Average of 2, 3, 4, 5 = 3.500000

Programming and Data Structures I


Average of 5, 10, 15 = 10.000000

Unit -I

Das könnte Ihnen auch gefallen