C
C
C
TABLE OF CONTENTS:
2. C language Preliminaries
a. Characters set.
b. C tokens
c. Keywords and Identifiers
d. Structure of a C Program.
e. Executing a C Program.
5. Operators in C
a. Arithmetic Operators
1
b. Arithmetic expressions
c. Modes of expression
d. Arithmetic operators precedence(including parenthesis)
e. Increment and decrement Operators.
f. Relational operators.
g. Logical operators.
h. Relational and logical expressions.
i. Precedence of relational operators and logical operators.
j. The conditional operators
k. Bitwise operators.
l. The comma operator.
m. The precedence of operators among themselves and across all the set of operators.
n. The associativity of operators.
o. Evaluation of expressions involving all the above type of operators.
p. Mathematical functions.
q. Header files
r. Preprocessor directives.
------------------------------------------------------------------
Algorithms :
The fundamental knowledge necessary to solve problems using a computer is
the notion of an algorithm. An algorithm is a precise specification of a sequence of instructions to
be carried out in order to solve a given problem. Each instruction tells us what task is to be
performed.
Ingredients:
½ kg fresh peas, 400 gms paneer, 2 onoins grated, 2 tomatoes, peeled and chopped
1tsp
chilli powder, ½ cup coriander leaves,1/2 turmeric powder,1tsp garlic/ginger paste,4 tsp oil,salt to
taste.
Method:
• Step 1: Pressure cook peas in Pressure Pan with 1 ½ cups of water. Drain out excess water,
keep peas aside.
• Step 2: Heat oil in the pressure pan and add the onions. Saute’ till they turn brown then
add tomato pulp.
• Step 3: Add spices, garlic and ginger paste, saute’ till the gravy is well blended.
• Step 4: Add cooked peas,paneer and salt.
2
• Step 5: Simmer for 5 minutes.
• Step 6: Garnish with coriander leaves.
Result:
Mutter paneer ready to serve for 4 people.
The recipe given above is similar to an algorithm but it does not technically qualify as one as the
instructions given above are not precise it depends on the individual whether the person has to
wait for the gravy to be blended.
Input
Needles No.12=2
Wool 4 ply = 9 balls
Method
Step1 : Cast on 133 stitches
Step2: Repeat Steps 3 and 4, 11 times
Step3: Knit 2, *Purl 1, Knit 1, Repeat from * to last stitch, Knit 1.
Step 4: Knit, *Purl 1, Knit 1, Repeat from * to End
…………………………
…………………………
( Similar steps)
Result :
A Sweater
Computers are built to carry out a small variety of elementary instructions. A computer may
thus be thought of as a servant who would carry out instructions at very high speed
obediently and uncritically. There is a need to give the computer extensive, detailed and
correct instructions for solving problems. In order to do this there is need for algorithms
which have to be precise, concise and unambiguous.
Flowcharts:
A flowchart depicts pictorially the sequence in which instructions are carried out in
an algorithm. Flow charts are used not only as aids in developing algorithms but also to
document algorithms.
3
For visual recognition a standard convention is used in drawing flowcharts. In this standard
convention
(i) Parallelograms are used to represent input and output operations.
(ii) Rectangles are used to indicate any processing operation such as storage and
arithmetic
(iii) Diamond shaped boxes are used to indicate questions asked or conditions tested
based on whose answers appropriate exits are taken by a procedure.
(iv) Rectangles with rounded ends are used to indicate the beginning or end points of a
procedure.
(v) A circle is used to join different parts of a flowchart. This is called a connector.
(vi) Arrows indicate the direction to be followed in a flowchart.
The above algorithm may be expressed much more clearly and concisely using a
flowchart.
Algorithm to
solve the given quadratic
equation:
Step1: Read
three numbers a, b, c
Step2: Multiply
number b twice
Step3: Multiply
number 4 with a and c
Step4: Subtract
the result of step2 from
the result of step3
Step5: Find the
square root of the result
obtained in Step4
4
Step6: Add the result of step5 with the negative of number b
Step7: Multiply the number 2 with a
Step 8: Divide the result of step 6 by the result of step 7
Step9: Similarly subtract the result of step5 with the negative of number b
Step10: The result is obtained for the quadratic equations for values x1 and x2.
Step11: Stop.
5
Algorithm to count the number of non-zero data
Summary
• Algorithms :
• The fundamental
knowledge
necessary to
solve problems using a
computer is the
notion of an algorithm . An
algorithm is
precise specification of a
sequence of instructions to
be carried out to
solve a given problem.
• Flowcharts:
• Pictorial representation of
the task to be carried out.
A flowchart depicts
pictorially the sequence in which instructions are carried out in an algorithm. Flow
charts are used not only as aids in developing algorithms but also to document
algorithms.
6
.
Executing a C program
The figure below illustrates the process of creating, compiling and executing the
program.
7
Summary:
In c language every word is classified into either keyword or identifier. All keywords
have fixed meanings and these meanings cannot be changed.
Scanf functions:-
The function scanf() is used to read data into variables from the standard
input, namely a keyboard. The general format is:
Scanf(format-string, var1,var2,………varn)
Where format-string gives information to the computer on the type of data to be stored in
the list of variables var1,var2……varn and in how many columns they will be found
Observe that the symbol &(called ampersand) should precede each variable name.
Ampersand is used to indicate that the address of the variable name should be found to
store a value in it. The manner in which data is read by a scanf statement may be
explained by assuming an arrow to be positioned above the first data value. The arrow
moves to the next data value after storing the first data value in the storage location
corresponding to the first variable name in the list. A blank character should separate the
data values.
The scanf statement causes data to be read from one or more lines till numbers are stored
in all the specified variable names.
No that no blanks should be left between characters in the format-string. The symbol &
is very essential in front of the variable name.
8
If some of the variables in the list of variables in the list of variables in scanf are of type
integer and some are float, appropriate descriptions should be used in the format-string.
For example:
Scanf(“%d %f %e”, &a , &b, &c);
Specifies that an integer is to be stored in a, float is to be stored in b and a float written
using the exponent format in c. The appropriate sample data line is:
485 498.762 6.845e-12
Printf function:
main()
{
int a= 45, b= 67
float x=45.78 , y=34.90
9
printf(“Output:\n”);
printf(“1,2,3,4,5,6,7,,8,0\n”);
printf(“\n”);
printf(“%d, %d,,%f ,%f \n” , a,b,x,y);
printf(“\n”);
}
Output:
1234567890
45,67,45.78,34.90
#include<stdio.h>
main()
{
int a,b,c,d;
float x,y,z,p;
scanf(“%d %o %x %u”, &a, &b ,&c ,&d);
printf(“the first four data displayed\n”);
printf((“%d %o %x %u \n”, a,b,c,d);
scanf(“%f %e %e %f”, &x, &y, &z, &p);
printf(“Display of the rest of the data read\n”);
printf(“%f %e %e %f\n”, x,y,z,p);
printf(“End of display”);
}
Input:
-768 0362 abf6 3856 -26.68 2.8e-3 1.256e22 6.856
Output:
10
Single characters can be entered into the computer using the C library function
getchar. The getchar function is a part of the standard C I/O library. It returns a single
character from a standard input device typically a keyboard. The function does not require
any arguments, though a pair of empty parentheses must follow the word getchar.
Example:
A C program contains the following statements
char c;
…………….
C=getchar();
The first statement declares that c is a character-type variable. The second statement causes a
single character to be entered from the standard input device and then assigned to c.
If an end-of-file condition is encountered when reading a character with getchar function,
the value of the symbolic constant EOF will automatically be returned. (This value will be
assigned within the stdio.h file. Typically, EOF will be assigned the value -1, though this
may vary from one compiler to another).
The getchar function can also be used to read multi character strings, by reading one
character at a time within a multi pass loop.
Char c;
………
putchar(c);
C programs:
11
#include<stdio.h>
main()
{
printf(“hello, world\y”);
printf(“hello, world\7”);
printf(“hello, world\?”);
}
#include<stdio.h>
main()
{
float fahr, Celsius;
#include<stdio.h>
main()
{
int number;
printf(“enter an integer number\n”);
scanf(“%d”, &number);
If (number<100)
{
printf(“Your number is smaller than 100\n\n”);
else
printf(“Your number contains more than two digits\n”);
}
Output
12
Enter an integer number
108
Your number contains more than digits
#include<stdio.h>
main()
{
int year,period;
float amount,inrate,value;
while(year<=period)
{
value amount + inrate*amount;
printf(“%2d Rs. %8.2f\n”, year, value);
amount=value;
year=year+1;
}
}
#define N 10
main()
{
int count;
float sum, average,number;
sum=0;
count=0;
while(count<N)
{
scanf(“%f”, &number);
sum=sum+number;
count=count+1;
}
average= sum/N;
13
printf(“N=%d Sum= %f”, N, sum);
printf(“Average=%f”, average);
}
#include<stdio.h>
main()
{
int months,days;
printf(“enter days \n”);
scanf(“%d”, &days);
months=days/30;
days=days%30;
printf(“Months = %d Days= %d”, months,days);
}
Operatos Ex:
Example :
A university has the following rules for a student to qualify for a degree with
Physics as the main subject and Mathematics as the subsidiary subject:
Pass x x - -
Repeat Physics - - x -
Fail - - - x
14
include<stdio.h>
main()
{
unsigned int roll_no, physics_marks, chem_marks;
while(scanf(“%d %d %d”, &roll_no,&physics_marks,
&chem_marks)!=EOF)
{
If(((chem_marks>=50 &&(physics_marks>=35)) ||
((chem_marks>=40)) &&(physics_marks>=50)))
Else
Else
Printf(“%d %d %d Failed \n”, roll_no, physics _marks, chem_marks);
}
}/*End while*/
}/*End main*/
Example:
In the above example, the expressions within the parentheses are evaluated
first. The arithmetic operations are carried out before the relational operations.
Thus b*5 is calculated and after that a is compared with it. Similarly y+6 is
evaluated first and then x is compared with it .
1. The unary operations, namely, -,++,--,! (logical not) are performed first.
2. Arithmetic operations are performed next as per their precedence.
3. After that the relational operations in each sub expressions are performed,
each sub expression will be a zero or non _ zero. If it is zero it is taken as
false else it is taken as true.
4. These logical values are now operated on by the logical operators.
5. Next the logical operation && is performed next.
15
6. Lastly the evaluated expression is assigned to a variable name as per the
assignment operator.
The operator ?; works as follows: exp1 is evaluated first. If it is nonzero(true), then the
expression exp2 is evaluated and becomes the value of the expression. If exp1 is false, exp3
is evaluated and its value becomes the value of the expression. Note that only one of the
expressions(either exp2 or exp3) is evaluated.
In this example, z will be assigned the value of b. This can be achieved using the if..else
statements as follows:
If (x>y)
z=x;
else
z=b;
Bitwise operators:
Bitwise Operators
Operator Meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ One’s Complement
16
The Comma Operator
C has some special operators. The comma operator is one among them. This
operator can be used to link the related expressions together. A comma-linked
list of expressions are evaluated left to right and the value of right-most
expression is the value of the combined expression.
For example, the statement
Value=(a=2, b=6 ,a+b);
First assigns the value 2 to a, then assigns 6 to b, and finally assigns 8(i.e 2+6)
to value. The comma operator has the lowest precedence of all
operators,hence the parentheses are necessary.
In for loops:
For(a=1, b=10;a<=b; a++, b++)
In while loops:
While(c=getchar(), C!=’10’)
Exchanging values:
T=x, x=y, y=t;
The precedence of operators among themselves and across all the set of
operators:
Operator Description
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation
~ One’s Complement
& Address
size of(type) type cast conversion
---------------------------------------------------------------------
* Multiplication
/ Division
% Modulus
+ Addition
- Subtraction
<< left shift
17
>> Right shift
< less than
<= less than or equal to
> Greater than
>= Greater than or equal to
== Equality
!= Inequality
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
&& Logical AND
|| Logical OR
?: Conditional expression
= Assignment operators
*= /= %=
+= -= &=
^= |=
<<= >>=
Comma operator
Preprocessor directive:
There are different preprocessor directives. The table below shows the preprocessor
directives.
Directive Function
#define statement:
One of the uses of the #define statement is for assigning symbolic names to program
constants.
The general syntax is :
#define TRUE 1
18
defines the name TRUE and makes it equivalent to the value 1. The name TRUE can
subsequently be used anywhere in the program where the constant 1 could be used.
Whenever this name appears, its defined value of 1 will be automatically substituted into the
program by the preprocessor. For example, we might have the following C statement that
uses the defined name TRUE
count=TRUE;
This statement would assign the value of TRUE to count.
The preprocessor statement
#define FALSE 0
would define the name FALSE and would make its subsequent use in the program equivalent
to specifying the value 0. Therefore, the statement
count=FALSE;
would assign the value of FALSE to count and the statement
If (count==FALSE)
……
would compare the value of count against the defined value of FALSE.
#define TRUE 1
#define FALSE 0
/*Function to determine if an integer is even*/
main()
{
int number,ans;
printf(“enter the number:”);
scanf(“%d” , &number);
if (number%2==0)
{
ans=TRUE;
else
ans=FALSE;
}
Some more examples of definition constants:
#define COUNT 100
#define SUBJECTS 6
#define PI 3.1415
#define CAPITAL “BANGALORE”
#include statement:
C preprocessor enables you to collect all your definitions into a separate file and then
include them in your program using the #include statement.
The general statement for this preprocessor directive is:
#include “filename”
19
#include<filename>
without double quotation marks. In this case, the file searched only in the standard
directories.
#include <stdio.h>
#include “SYNTAX.C”
#include “STAT.C”
#include “TEST.C”
Header files:
C language offers simpler way to simplify the use of library functions to the greatest
extent possible. This is done by placing the required library function declarations in special
source files, called header files. Most C compilers include several header files, each of which
contains declarations that are functionally related.
stdio.h is a header file containing declarations for input/ouput routines; math.h contains
declarations for certain mathematical functions and so on. The header files also contain other
information related to the use of the library functions, such as symbolic constant definitions.
The required header files must be merged with the source program during the compilation
process. This is accomplished by placing one or more #include statements at the beginning of
the source program.
The other header files are:
<ctype.h> character testing and conversion functions
<stdlib.h> utility functions such as string conversion routines , memory allocation
routines, random number generator, etc
<string.h> String manipulations functions
<time.h> time manipulation functions
Control Statements
Introduction :
So far we have studied the programs , where the instructions are executed sequentially. It
means statements are executed in the same order in which they appear in the program. But
there are many times, we want the instructions to be executed in one situation. The ‘c’
language was capable of performing different sets of actions depending on the circumstances.
The C has three major decision making instructions, the if statement , the if-else statement
and the switch statement.
if ( condition)
statement;
20
The keyword if tells the compiler if the condition is true, then statement should be executed.
Suppose if the condition is false, then statement has to be skipped. The following table shows
the relation operator used in condition.
== equal
!= Not equal to
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
&& and
|| or
! not
&& operator return true when all conditions are evaluated to true. Otherwise it return false.
For example
|| operator return true when one of the condition returns true, otherwise it returns false. For
example
Problem : Given two integer numbers, find out the larger of them.
#include <stdio.h>
main()
{
float x, y;
printf(“ input two numbers\n”);
scanf(“%f %f “, &x, &y);
if ( x > y)
printf(“ x is big\n”);
if (y > x)
printf(“y is big\n”);
}
21
Problem : Find out a number is even or odd.
#include <stdio.h>
main()
{
int x;
printf(“input an integer\n”);
scanf(“%d”,&x);
if ((x % 2) == 0)
printf(“it is even number\n”);
if ((x%2) == 1)
printf(“it is odd number\n”);
}
Problem : Imagine there are n cricket palyers. Find out how many cricket team can be formed
and how many players left out.
#include <stdio.h>
main()
{
int n,teams,leftout;
printf(“input how many members\n”);
scanf(“%d”,&n);
teams = n/11;
leftout=n %11;
printf(“number of teams can be formed = %d\n”, teams);
printf(“number of members are left out = %d\n”, leftout);
}
It may so happen that in a program we want more than one statement to be executed if the
condition following if is satisfied. If such multiple statements are to be executed then they
must be placed within a pair of braces.
Let us consider an example of finding out the roots of the quadratic equation.
#include <stdio.h>
main()
{
float a,b,c,d,x1,x2, xr1,xi1,xr2,xi2;
22
scanf(“%f %f %f”, &a, &b, &c);
if ( a == 0)
{
printf(“ it is linear equation\n”);
x1 = -b/c;
printf(“root is %f\n”, x1);
exit(0);
}
d = b*b – 4.0 * a * c;
if ( d == 0)
{
printf(“ equal roots\n”);
x1 = -b/ (2.0*a);
x2 = -b/(2.0*a);
printf(“ %f %f\n”, x1,x2);
exit(0);
}
if ( d >0)
{
printf(“ real and unequal roots\n”);
x1 = (-b + sqrt(d)) / (2.0*a);
x2 = (-b – sqrt(d))/(2.0*a);
printf(“ %f %f\n”, x1,x2);
exit(0);
}
if ( d < 0)
{
printf( “ complex roots\n”);
d= -d;
xr1 = -b/(2.0*a);
xi1 = sqrt(d)/(2.0*a);
xr2= -b/(2.0*a);
xi2 = sqrt(d)/(2.0*a)
printf(“ first root is %f + %f\n”, xr1, xi1);
printf(“second root is %f - %f\n”, xr2,xi2);
exit(0);
}
}
In the above program exit(0) is used to quit from the program. This is because once the
condition is fulfilled, there is no necessity to continue the program.
23
The if-else statement
The if statement by itself will execute a single statement or a group of statements, when the
condition following if is true. It does nothing when it is false. The if-else statement provides
the option a statement/s can be executed when the condition is false.
The syntax is
if (condition)
statement1;
else
statement2;
If the condition is true , the statement1 is executed. If the condition is false, then statement2
under else part is get executed.
#include <stdio.h>
main()
{
int x;
printf(“input an integer\n”);
scanf(“%d”,&x);
if ((x % 2) == 0)
printf(“it is even number\n”);
else
printf(“it is odd number\n”);
}
Switch statement
This is another form of the multi way decision. It is well structured, but can only be used in
certain cases where;
• Only one variable is tested, all branches must depend on the value of that variable.
The variable must be an integral type. (int, long, short or char).
• Each possible value of the variable can control a single branch. A final, catch all,
default branch may optionally be used to trap all unspecified cases.
24
The C switch allows multiple choice of a selection of items at one level of a conditional where
it is a far neater way of writing multiple if statements:
switch (expression) {
case item1:
statement1;
break;
case item2:
statement2;
break;
case itemn:
statementn;
break;
default:
statement;
break;
}
In each case the value of itemi must be a constant, variables are not allowed.
The break is needed if you want to terminate the switch after execution of one choice.
Otherwise the next case would get evaluated.
For example:-
switch (letter)
{
case `A':
case `E':
case `I':
case `O':
case `U':
numberofvowels++;
break;
case ` ':
numberofspaces++;
break;
default:
numberofconstants++;
break;
}
In the above example if the value of letter is `A', `E', `I', `O' or `U' then numberofvowels is incremented.
25
If the value of letter is ` ' then numberofspaces is incremented.
If none of these is true then the default condition is executed, that is numberofconstants is incremented.
The ? operator
The ? (ternary condition) operator is a more efficient form for expressing simple if
statements. It has the following form:
It simply states:
z = (a>b) ? a : b;
if (a>b)
z = a;
else
z=b;
#include <stdio.h>
main()
{
int a,b,max;
printf(“input two integer numbers\n”);
scanf(“%d %d”, &a,&b);
max = (a > b) ? a: b;
printf(“maximum number is equal to = %d\n”, max);
}
Loops
Introduction :
When we write a list of instructions for someone to perform we usually expect them to
follow the list from the top to the bottom, one at a time. This is the simple default flow of
26
control through a program. The C programs we have written so far use this one-after-another
default flow of control.
This is fine and simple, but it limits the running time of any program we can write. There is
a limit to the number of instructions we can write and it does not take long for a computer to
read though and obey our list. Whenever we want to execute a group of instruction many
times, the concept called loop it comes into the picture.
Suppose we want to display "computer" six times on the screen. We may write a program
that is given below
#include <stdio.h>
main()
{
printf("computer\n");
printf("computer\n");
printf(“computer\n”);
printf("computer\n");
printf("computer\n");
printf("computer\n");
}
But this becomes complicated when we want to print 100 times “computer” messages.
What you really need is some way of repeating the printf statements without having to write
it out each time. The solution to this problem is to use loop statements.
Loop statement in c :
• The while loop keeps repeating an action until an associated test returns false. This is
useful where the programmer does not know in advance how many times the loop
will be traversed.
• The do while loops is similar, but the test occurs after the loop body is executed. This
ensures that the loop body is run at least once.
• The for loop is frequently used, usually where the loop will be traversed a fixed
number of times. It is very flexible, and novice programmers should take care not to
abuse the power it offers.
While statement
27
while (expression) {
statement
}
First, the while statement evaluates expression, which must return a boolean value. If the
expression returns true, the while statement executes the statement(s) in the while block. The
while statement continues testing the expression and executing its block until the expression
returns false.
#include <stdio.h>
main()
{
int fact, i,n;
printf(“input a number\n”);
scanf(“%d”,&n);
fact=1;
i=1;
while ( i <= n)
{
fact=fact*i;
++i;
}
printf(“ factorial = %d\n”, fact);
}
do –while statement
Syntax:
do {
statement(s)
} while (expression);
Instead of evaluating the expression at the top of the loop, do-while evaluates the expression at
the bottom. Thus, the statements within the block associated with a do-while are executed at
least once.
Each line of a C program up to the semicolon is called a statement. The semicolon is the
statement's terminator. The braces { and } which have appeared at the beginning and end of
our program unit can also be used to group together related declarations and statements into a
compound statement or a block.
In the case of the while loop before the compound statement is carried out the condition is
checked, and if it is true the statement is obeyed one more time. If the condition turns out to be
28
false, the looping isn't obeyed and the program moves on to the next statement. So we can
see that the instruction really means while something or other is true keep on doing the
statement.
In the case of the do while loop it will always execute the code within the loop at least once,
since the condition controlling the loop is tested at the bottom of the loop. The do while loop
repeats the instruction while the condition is true. If the condition turns out to be false, the
looping isn't obeyed and the program moves on to the next statement.
printf(“input an integer\n”);
scanf(“%d”,&n);
fact=1;
i=1;
do
{
fact=fact*i;
++i;
}
while ( i <= n);
for statement:
The for statement provides a compact way to iterate over a range of values. The general
form of the for statement can be expressed as follows.
The initialization expression initializes the loop — it's executed once at the beginning of the
loop. The termination expression determines when to terminate the loop. When the
expression evaluates to false, the loop terminates. Finally, increment is an expression that gets
invoked after each iteration through the loop. All these components are optional. In fact, to
write an infinite loop, you omit all three expressions.
29
}
Let us consider an example to calculate the factorial of a number using the for loop.
#include <stdio.h>
main()
{
int n,fact,i;
printf(“enter an integer\n”);
scanf(“%d”,&n);
fact=1;
for (i=1; i<=n; ++i)
fact=fact*i;
printf(“factorial = %d\n”, fact);
}
Arrays:
The meaning of an array:
A group of related data items that share a common name is called an array.
For example, we can define an array name marks to represent a set of marks obtained by a
group of students. A particular value is indicated by writing a number called index number or
subscript in brackets after the array name.
Example,
Marks[7]
Represents the marks of the 7th student. The complete set of values is referred to as an array,
the individual values are called elements. The arrays can be of any variable type.
One-dimensional array:
When a list of items can be given one variable name using only one subscript and
such a variable is called a single-subscripted variable or one dimensional array.
The subscripted variable xi refers to the ith element of x. The subscript can begin with
number 0. For example, if we want to represent a set of five numbers, say (57,20,56,17,23),
by a array variable num, then we may declare num as follows
Int num[5];
And the computer reserves five storage locations as shown below:
30
Num[0]
Num[1]
Num[2]
Num[3]
Num[4]
The table below shows the values that are stored in the particular numbers.
Num[0]
Num[1]
Num[2]
Num[3]
Num[4]
57
20
56
17
23
Two dimensional arrays are stored in memory as shown in the table below. Each dimension
of the array is indexed from zero to its maximum size minus one; the first index selects the
row and the second index selects the column within that row.
31
[1][0] [1][1] [1][2]
The arrays are declared before they are used in the program. The general form of
array declaration is
Type variable_name[size];
The type specifies the type of element that will be contained in the array, such as int,float,or
char and the size indicates the maximum number of elements that can be stored inside the
array.
Example:
Float weight[40]
Declares the weight to be an array containing 40 real elements. Any subscripts 0 to 39 are
valid.
Similarly,
Int group1[11];
Decalres the group1 as an array to contain a maximum of 10 integer constants.
The C language treats character strings simply as arrays of characters. The size in a character
string represents the maximum number of characters that the string can hold.
For example:
Char text[10];
Suppose we read the following string constant into the string variable text.
“HOW ARE YOU”
Each character of the string is treated as an element of the array text and is stored in the
memory as follows.
‘H’
‘O’
‘W’
‘A’
‘R’
32
‘E’
‘Y’
‘O’
‘U’
‘\o’
When the compiler sees a character string, it terminates it with an additional null character.
Thus, the element text[11] holds the null character ‘\o’ at the end. When declaring character
arrays, we must always allow one extra element space for the null terminator.
Initialization of arrays:
#include<stdio.h>
main()
33
{
int a[10][10];
int i, j row,col;
printf(“\n Input row and column of a matrix:”);
scanf(“%d %d”, &row,&col);
for(i=0; i<row;i++)
for(j=0;j<col;j++)
scanf(“%d”, &a[i][j]);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf(“%5d”, a[i][j]);
printf(“\n”);
}
main()
{
int i;
float a[10],value1,total;
printf(“Enter 10 Real numbers\n”);
for(i=0;i<10;i++)
{
scanf(“%f”, &value);
x[i]=value1;
}
total=0.0;
for(i=0;i<10;i++)
total=total+a[i]*a[i];
printf(“\n”);
for(i=0;i<10;i++)
printf(“x[%2d]= %5.2f\n”, i+1, x[i]);
printf(“\ntotal=%.2f\n”, total);
}
Programming examples:
#define R1 4
#define C1 4
main()
34
{
int row,col,prod[R1][C1];
int i,j;
printf(“ MULTIPLICATION TABLE \n\n”);
printf(“ “);
for(j=1;j<=C1;j++)
printf(“%4d”,j);
printf(“\n”);
printf(“-------------------------------------------\n”);
for(i=0;i<R1;i++)
{
row=i+1;
printf(“%2d|”, R1);
for(j=1;j<=C1;j++)
{
col=j;
prod[i][j]=row*col;
printf(“%4d”, prod[i][j]);
}
printf(“\n”);
}
}
Output
MULTIPLICATION TABLE
1 2 3 4
---------------------------------------
1 | 1 2 3 4
2 | 2 4 6 8
3 | 3 6 9 12
4 | 4 8 12 16
#include<stdio.h>
#include<math.h>
main()
{
int b[10],sum=0,i,dig;
printf(“\n enter the number of digits (MAX 8): \t”);
35
scanf(“%d”, &dig);
printf(“\n Enter the binary digits (Left to Right): \t”);
for(i=1;i<=dig;i++)
scanf(“%d”, &bin[i]);
for(i=dig;i<=1;i--)
sum+=bin[i]*pow(2,dig-1);
printf(“\n the decimal number is= \t %d n”, sum);
}
#include<stdio.h>
main()
{
int st[5], watt;
float cost[5], total;
total=0;
for(watt=0;watt<=4;++watt)
{
scanf(“%d %f”, &st[watt], &cost[watt])
{
scanf(“%d %f”, &st[watt], &cost[watt]);
total+= (float) st[watt]*cost[watt];
}
printf(“%f \n”, total);
}
#include<stdio.h>
main()
{
int x[10], i, j, temp;
for(i=0;i<=9;++i)
scanf(“%d”, &x[i]);
for(j=0;j<=8;j+=2)
{
temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;
}
for(i=0;i<=9;++i)
36
printf(“%d”, x[i]);
printf(“\n”);
}
#define N 10
main()
{
int i,j,k;
float a[N],t;
printf(“Enter the number of items\n”);
scanf(“%d”, &n);
printf(“Input %d values \n”, n);
for(i=1; i<=n ;;i++)
scanf(“%f”, &a[i]);
for(i=1;i<=n-1;i++)
{
for(j=1;j<=n-i; j++)
{
if)a[j]<=a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
else
continue;
}
}
for(i=1;i<=n;i++)
printf(“%f”, a[i]);
}
#include<math.h>
#define MAX 100
main()
{
int i,n;
float val[MAX],deviation,sum,ssqr,mean,var,stddev;
sum=ssqr=n=0;
printf(“Input values: input-1 to end\n”);
for(i=1;i<MAX;i++)
{
37
scanf(“%f”, &val[i]);
if(val[i]==-1)
break;
sum+=val[i];
n+=1;
}
mean=sum/(float)n;
for(i=1;i<=n;i++)
{
deviation=val[i]-mean;
ssqr+=deviation*deviation;
}
var=ssqr/(float)n;
stddev=sqrt(var);
printf(“\n Number of items:%d\n”,n);
printf(“Mean: %f \n”, mean);
printf(“Standard deviation: %f\n”, stddev);
}
#include<stdio.h>
main()
{
int I,s, largcount,smcount;
float num[30],lar,small;
for(i=0;i<size;i++)
scanf(“%f”, &num[i]);
for(i=0;i<size;i++)
printf(“%f”, &num[i]);
lar=small=num[0];
larcount=smcount=1;
for(i=1;i<size;i++)
{
if(num[i]>lar)
{
lar=num[i];
larcount=i+1;
38
}
elseif(num[i]<small)
{
small=num[i];
smcount=i+1;
}
}
printf(“\n Largest value is % f found at %d”, lar,larcount);
printf(“\n Smallest value is %f found at %d “, small, smcount);
}
Functions:
There are times when some type of operation or calculation is repeated at many points
throughout a program. In such situations, we may repeat the program statements
wherever they are needed. There is another way to design a function that can be called
and used whenever required. This saves both time and space.
1. The figure below shows to-down modular programming. In this programming style,
the high level logic of the overall problem is solved first while the details of each
lower-level function are addressed later.
2. The length of a source program can be reduced by using functions at appropriate
places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs.
Main Program
39
Top-down modular programming using functions
Defining and using functions:
All parts are not essential. Some may be absent. For example, the argument list and its
associated argument declaration parts are optional. The declaration of local variables
is required only when any local variables are used in the function. A function can
have any number of executable statements. A function that does nothing, may not
include any executable statements at all.
Do_nothing() {}
The return statement is the mechanism for returning a value to the calling function.
This is also optional statement. Its absence indicates that no value is being returned to
the calling function.
Function name:
A function must follow the same rules of formation as other variable names in
C.
Argument List:
The argument list contains valid variable names separated by commas. The
list must be surrounded by parentheses. The argument variables receive values from
the calling function, thus providing a means for data communication from the calling
function to the called function. Some examples of functions with arguments are:
Quadratic(a,b,c)
Power(x,n)
Mul(a,b)
All the argument variables must be declared for their types after the function header
and before the opening brace of the function body.
Power(x,n)
float x;
int n;
{
---------
---------
--------
}
Category of functions:
40
A function may depend on whether arguments are present or not and whether
a value is returned or not. It may belong to one of the following categories.
When a function has no arguments, it does not receive any data from the calling
function. Similarly, when it does not return a value, the calling function does not
receive any data from the called function. In effect, there is not data transfer between
the calling function and the called function. The dotted lines indicate that there is only
a transfer of control but not data.
{ {
----------------
function2() --------------
---------------- --------------
---------------- --------------
} }
main()
{
printtext();
value();
printtext();
}
printtext()
{
int I;
for (i=1;i<=40;i++)
printf(“%c”, ‘-‘);
printf(“\n”);
}
value()
{
int year, period;
float inrate, sum principal;
41
printf(“Principal amount?”);
scanf(“%f”, &principal);
printf(“Interest rate? “);
scanf(“%f”, &inrate);
printf(“Period? “);
scanf(“%d”, &period);
sum=principal;
year=1;
while(year<=period)
{
sum=sum * (1+inrate);
year=year+1;
}
printf(“ \n 8.2f %5.2f %5d %12.2f\n”, principal,inrate,period,sum);
}
Function1() function2(1)
{ values of arguments ---------------
-------------- ------------ {
function2(a) --------------
-------------- < ----------- ---------------
------------- ---------------
} }
For example.
Printtext(ch)
Value(p,r,n)
The arguments ch,p,r and n are called the formal arguments. The calling
function can now send values to these arguments using function calls containing
appropriate arguments. For example, the function call
Value(100,0.23,10)
Would send the values 100,0.23,and 10 to the function.
Value(p,r,n)
And assign 100 to p, 0.23 ,to r, and 10 n. The values 100,0.23 and 10 are the actual
arguments which become the values of the formal arguments inside the called
function.
The actual and formal functions should match in number, type and order. The
values of actual arguments are assigned to the formal arguments on a one to one basis
starting with the first argument.
main()
{
Function
42
call --------------
----- function1(a1,a2,a3………am)
-------------
}
Called function
------ > function1(f1,f2,f3,………….fn)
--------------
--------------
{
----------
----------
}
The formal arguments must be valid variable names, the actual arguments may be
variable names, expressions or constants. The variables used in actual arguments
must be assigned values before the function call is made.
When a function call is made, only a copy of the values of actual arguments is
passed into the called function.
The function call value(prin, rate, per);
Passes information it contains to the function value.
The function header of value has three formal arguments p,r and n which correspond
to the actual arguments in the function call, namely, prin,rate and per. The formal
arguments are declared immediately after the function header. On execution of the
function call, the values of the actual arguments are assigned to the corresponding
formal arguments.
p=prin;
r=rate;
n=per;
The variable declared inside a function are known as local variables and therefore
their values are local to the function and cannot be accessed by any other function.
The function value calculates the final amount for a given period and prints
the result. Control is transferred back on reaching the closing brace of the function.
Note that the function does not return any value.
Main()
{
float prin.rate,amt;
int per;
printf(“Enter principal amount, interest”);
printf(“rate and period\n”);
scanf(“%f %f %d”, &prin,&rate,&per);
printtext(‘Z’);
value(prin,rate,per);
43
printtext(‘A’);
}
printtext(ch)
char ch;
{
int j;
for(j=1;j<=52;j++)
printf(“%c”, ch);
printf(“\n”);
}
value(p,r,n)
int n;
float p,r;
{
int year;
float sum;
sum=p;
year=1;
while(year<=n)
{
sum=sum*(1+r)
year=year+1;
}
printf(“%f %f %d %f \n”, p, r, n, sum);
}
We may not always wish to have the result of a function displayed. We may use it in the
calling function for further processing. Moreover , to assure a high degree or
portability between programs, function should generally be coded without involving
any I/O operations. Different programs may require different output
Formats for displaying results. This can be overcome by handing over the result of a function
to its calling function where the returned value can be required by the program.
Function1() function2(f)
{ values of
arguments ------------
----------- -------------- {
----------- -------------
Function result ------------
function2(a) <----------------- ------------
------------- return(e)
----------- }
44
}
main()
{
float prin.rate,amt;
int per;
printf(“Enter principal amount, interest”);
printf(“rate and period\n”);
scanf(“%f %f %d”, &prin,&rate,&per);
printtext(‘*’, 52);
amt=value(prin,rate,per);
printf(“\n %f %f %d %f \ n \n”, prin,rate,per,amt);
printtext(‘=’, 52);
}
printtext(ch,l)
int l;
char ch;
{
int j;
for(j=1;j<=52;j++)
printf(“%c”, ch);
printf(“\n”);
}
value(p,r,n)
int n;
float p,r;
{
int year;
float sum;
sum=p;
year=1;
while(year<=n)
{
sum=sum*(1+r)
year=year+1;
}
return(sum);
}
1. The function call transfers the control along with the copies of the values of the actual
arguments to the function value where the formal arguments p,r and n are assigned
the values of prin, rate and per respectively.
45
2. The called function value is executed line by line in a normal fashion until the return
(sum); statement is encountered. The value of sum is passed back to the function call
in the main program.
3. The calling statement is executed normally and the returned value is thus assigned to
amt.
The function value mentioned above in the example does all the calculations
using floats but the return statement
return(sum);
returns only the integer part of sum. This is due to the absence of the type-specifier in
the function header. Some times it might be necessary to receive float or double type of
data.
We should follow the steps below to enable a calling function to receive a
non-integer value from a called function.
2. The called function must be declared at the start of the body in the calling function
like any other variable. This is to tell the calling function the type of data that the
function is actually returning.
main()
{
float x,y, mul();
double div();
x= 34.238;
y= 6.78;
printf(“%f \n”, mul(x,y));
printf(“%f \n”, div(x,y));
}
float mul(x,y)
float x,y;
{
return(x * y);
}
46
double div(p,q)
double p,q;
{
return(p/q);
}
}
The declaration part of main function declares not only the variables but the functions
mul and div as well. This only tells the compiler that mul will return a float-type value
and div a double type value. Parantheses that follow mul and div specify that they are
functions instead of variables.
If we have a mismatch between the type of data that the called function returns and the
type of data that the calling function expects, we will have unpredictable results. We
must be very careful to make sure that both types are compatible.
Array in functions.
47
for(j=1; j<n; j++)
if(max< a[j])
max=a[j];
return(max);
}
When the function call large(value,5) is made the value of all elements of the array value are
passed to the corresponding elements of array a in the called function. The large function
finds the largest value in the array and returns the result to the main.
Global variables:
Variables that are both alive and active throughout the entire program are known as
global or external variables. The global variables can be accessed by any function in the
program. External variables are declared outside a function.
The external declaration of integer number and float length might appear as:
int number;
float length=7.5;
main()
{
----------
---------
}
function1()
{
------------
----------
}
function2()
{
---------
--------
}
The variables number and length are available for use in all the three functions. When the
local variable and a global variable have the same name, the local variable will have
precedence over the global one in the function where it is declared.
Consider the following example:
int cnt;
main()
{
cnt=10;
------------
-----------
48
}
function()
{
int cnt=0;
-----------
----------
cnt=cnt+1;
}
When the function references the variable cnt, it will be referencing only its local variable,
not the global one. The value of cnt in main will not be affected.
A program to show the properties of global variables.
int x;
main()
{
x=15;
printf(“x= %d \n”, x);
printf(“x=%d \n”, fun1());
printf(“x=%d\n”, fun2());
printf(“x=%d\n”, fun3());
}
fun1()
{
x=x+15;
return(x);
}
fun2()
{
int x;
x=1;
return(x);
}
fun3()
{
x=x+15;
return(x);
}
Local variables:
These type of variables are declared inside a function in which they are to be utilized. They
are created when the function is called and destroyed automatically when the function is
exited. Hence these variables are also known as automatic variables.
A variable declared inside a function without storage class specification is by default a local
variable.
main()
49
{
int number;
------------
------------
}
main()
{
int m=1000;
function2();
printf(“%d\n”, m);
}
function1()
{
int m=10;
printf(“%d\n”, m);
}
function2()
{
int m=1000
function();
printf(“%d\n”, m);
}
Register variable:
Some times we can tell the compiler that a variable should be kept in one of the
machine’s registers, instead of keeping in the memory. Since the access of register variables
is faster than the memory access. The general format is as follows:
Register int variable name;
Since only a few variables can be placed in the register, it is important to carefully select the
variables for this purpose. Once the limit is reached C will automatically convert register
variables into non-register variables.
Static variable:
A variable can be declared static using the keyword static like
static int a;
static float y;
A static variable may be either an internal type or external type, depending on the
place of declaration.
50
Internal static variables are those which are declared inside a function. The scope of
internal static variables extend up to the end of the function in which they are defined. These
internal static variables are similar to local variables except that they remain in existence
throughout the remainder of the program. Therefore , internal static variables can be used to
retain values between function calls.
main()
{
int j;
for(j=1;j<=3;j++)
stat();
}
stat()
{
static int y=0;
y=y+1;
printf(“y=%d \n”,y);
}
Programming examples:
1. Program to calculate standard deviation using function.
#include<math.h>
main()
{
float value[5], stddev();
int i;
printf(“Enter the values\n”);
for(i=0;i<5;i++)
scanf(“%f”, &value[i]);
printf(“Std.deviation is %f\n”, stddev(value,5);
}
float stddev(x,n)
float x[ ];
int n;
{
int i;
float mean(),y,sum=0.0;
y=mean(x,n);
for(i=0;i<n;i++)
{
sum=sum+(y-x[i])*(y-x[i]);
51
return(sqrt(sum/(float)n));
}
float mean(x,n)
float x[ ];
int n;
{
int i;
float sum=0.0;
for(i=0;i<n;i++)
sum=sum+x[i];
return(sum/(float)n);
}
Main()
{
int i;
static int num[6]={34,56,23,12,95,67};
printf(“The numbers before soring\n:”);
for(i=0;i<6;i++)
printf(i=0;i<6;i++)
printf(“\n”);
}
sort(n,y)
int m, x[ ];
{
int i,j,temp;
for(i=1 ; i<=n;i++)
for(j=1;j<=n-i;j++)
if(x[j-1]>=x[j])
{
temp=x[j-1];
x[j-1]=x[j];
x[j]=temp;
}
}
Strings
String variable:
A string is an array of characters. Any group of characters defined between
double quotation marks is called a constant string.
Example:
“Good Morning Everybody”
Character strings are often used to build meaningful and readable programs.
52
A string variable is any valid C variable name and is always declared as an array.
Character arrays may be initialized when they are declared. C permits a character array to be
initialized in either of the following two forms:
The reason that state had to be 10 elements long is that the string KARNATAKA contains
10 characters and one element space is provided for the null terminator.
main()
{
char text1[50],text2[50],text3[50],text4[50];
printf(“Enter text:\n”);
scanf(“%s %s”, text1,text2);
53
scanf(“%s”, text3);
scanf(“%s”, text4);
printf(“\n”);
printf(“text1= %s\n text2=%s\n”, text1,text2);
printf(“text3= %s\n text4= %s\n”, text3,text4);
}
Writing strings:
The printf function with %s can be used to display an array of characters that is
terminated by the null character.
Example:
printf(“%s”, text);
We can also specify the precision with which the array is displayed. For example, the
specification
%12.4
indicates that the first four characters are to printed in a field width of 12 columns.
Main()
{
static char state[15]= “MADHYA PRADESH”;
printf(“\n \n”);
printf(“----------------------------------\n”);
printf(“%13s\n”, state);
printf(“%5s\n”, state);
printf(“%15.6s \n”, state);
printf(“%15.0s\n”, state);
printf(“%.3s\n”, state);
}
String functions:
C library supports a large number of string functions. The list given below depicts
the string functions
Function Action
54
The strcat function joins two strings together. The general form is
strcat(string1,string2);
string1 and string2 are character arrays. When the function strcat is executed. String2 is
appended to string1. It does so by removing the null character at the end of string1 and
placing string2 from there. The string at string2 remains unchanged.
Example:
Text1= VERY \0
Text2= GOOD\0
Text3= BAD\0
Strcat(text1,text2);
Strcat(text1,text3);
We must make sure that the size of string1 is large enough to accommodate the final
string.
Strcat function may also append a string constant to string variable.
For example:
strcat(text1,”GOOD”);
The strcmp function compares two strings identified by the arguments and has a value
0 if they are equal.
The general form is :
strcmp(string1,string2);
String1 and string2 may be string variables or string constants.
Examples are:
strcmp(name1,name2);
55
strcmp(name1, “ABHI”);
strcmp(“ROM”, “RAM”);
We have to determine whether the strings are equal, if not which is alphabetically above.
The strcpy() function works almost like a string-assignment operator. The general
format is
strcpy(string1,string2);
It copies the contents of string2 to string1. string2 may be a character variable or a string
constant.
For example, the statement
strcpy(city , “BANGALORE”);
Will assign the string “BANGALORE” to the string variable city.
The statement strcpy(city1,city2); will assign the contents of the string variable city2 to the
string variable city1. The size of the array city1 should be large enough to receive the
contents of city2.
Where n is an integer variable which receives the value of the length of the string.
The argument may be a string constant. The counting ends at the first null character.
String concatenation:
We cannot assign one string to another directly,we cannot join two strings together by
the simple arithmetic addition. The characters from string1 and string2 should be copied into
the string3 one after the other. The size of the array string3 should be large enough to hold
the total characters.
Main()
{
int i,j,k;
static char first_name={“ATAL”};
static char sec_name={“RAM”};
static char last_name={“KRISHNA”};
char name[30];
for(i=0;first_name[i]!=’\0’;i++)
56
name[i]=first_name;
for(i=0;second_name[j]!=’\0’; j++)
name[i+j+1]=sec_name[j];
name[i+j+1] =’ ‘;
for(k=0;last_name[k]!=’\0’;k++)
name[i+j+k+2]=last_name[k];
name[i+j+k+2]=’\0’;
printf(“\n \n”);
printf(“%s \n”, name);
}
Output
ATAL RAM KRISHNA
String comparison:
-----------------------------
i=0;
while(str1[i]==str2[i] && str1[i]!=’\0’
&& str2[i]!=’\0’)
i=i+1;
if(str1[i]==’\0’ && str2[i]==’\0’)
printf(“strings are equal\n”);
else
printf(“strings are not equal\n”);
--------------------------------
String copying:
main()
{
char string1[80],string2[80];
int j;
printf(“Enter a string\n”);
printf(“?”);
scanf(“%s”, string2);
for(j=0;string2[i]!=’\0’;j++)
string1[j]=string2[j];
string1[j]=’\0’;
57
printf(“\n”);
printf(“%s\n”,string1);
printf(“Number of characters=%d\n”, j);
}
#include<stdio.h>
main()
{ char line[80],character
int c=0,i;
printf(“Enter the text\n”);
for(i=0;line[i];!=’\0’;i++)
{ character=getchar();
line[i]=character;
c++;
}
printf(“The length of the string \n”, c);
}
It is also possible to perform arithmetic operations on the character constants and variables.
For example:
y=’z’-1;
Is a valid statement. In ASCII , the value of ‘z’ is 122 and therefore , the statement will
assign the value 121 to the variable Y.
We can convert a character digit to its equivalent integer value using the following
relationship :
y=character –‘0’;
Where y is defined as an integer variable and character contains the character digit.
Example: Let us assume that the character contains the digit ‘7’, then,
58
y=ASCII value of ‘7’-ASCII value of ‘0’
= 55-48
=7
C library has a function that converts a string of digits into their integer values. The function
takes the form
y=atoi(string);
y is an integer variable and string is a character array containing a string or digits
Consider the following example:
num=”1974”
year=atoi(num);
Num is a string variable which is assigned the string constant “1974”. The function atoi
converts the string “1974” to its numeric equivalent 1974 and assigns it to the integer
variable year.
Programming examples:
#define ITEMS 10
#define MAX 25
main()
{
char str [ITEMS][MAX], dum[MAX];
int i=0;j=0;
printf(“Enter names of %d items \n”, ITEMS);
while(i<ITEMS)
scanf(“%s”, str[i++]);
for(i=1;i<ITEMS;i++)
{
for(j=1;j<=ITEMS-i;j++)
{
if(strcmp(string[j-1],string[j])>0)
strcpy(dummy,string[j-1]);
strcpy(str[j-1],str[j]);
strcpy(str[j],dummy);
}
}
for(i=0;i<ITEMS;i++)
printf(“%s”, str[i]);
}
#include<string.h>
main()
59
{
char s1[20],s2[20],s3[20];
int y,len1,len2,len3;
printf(“\n Enter two string constants\n”);
printf(“?”);
scanf(“%s %s”, s1,s2);
x=strcmp(s1,s2);
If(y!=0)
{
printf(“\n\n Strings are not equal\n”);
strcat(s1,s2);
}
else
printf(“\n\n Strings are equal\n”);
strcpy(s3,s1);
len1=strlen(s1);
len2=strlen(s2);
len3=strlen(s3);
printf(“\n s1= %s length= %d character \n”,s1,len1);
printf(“\n s1= %s length= %d character \n”,s2,len2);
printf(“\n s1= %s length= %d character \n”,s3,len3);
}
#include<stdio.h>
main()
{
char text[85];
int i=0;
printf(“Enter a line of text in lowercase:\t”);
scanf(“%[^\n]”,text);
printf(“%s”,text);
printf(“\n Converted to uppercase text is :\t”);
while(text[i]!=’0’)
printf(“%c”, toupper(text[i]));
i++;
}
printf(“\n”);
}
Pointers:
60
When we declare a variable name m as type integer we tell the compiler that a
location in memory where an integer can be stored should be found and it should be given a
name m.
Thus when we write
int m;
Will pick a memory box and give it a name m. The variable name is a symbolic name for the
address of the memory box. We have already used the operator & which was used in scanf
function. This operator is called the address operator.
If we write &m the operator & tells the compiler to find the numeric value of the
address of a memory box whose symbolic name is m.
If we write:
n=&m;
Then the address of variable m is stored in n. When a variable stores an address we
declare that variable as a pointer data type.
Thus n is declared as:
int *n;
This declaration says that n will store the address of an integer variable name.
n=&m;
m 8468 35
This tells the compiler three things about the variable pt_name.
1. The asterisk(*) tells that the variable pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to variable of type data type.
For example:
int *q;
Declares the variable q as a pointer variable that points to an integer data type.
61
Once a pointer variable has been declared, it can be made to point to a
variable using an assignment statement such as
p=&quantity;
This causes p to point to quantity. That is, p now contains the address of quantity.
This is known as pointer initialization.
We must ensure that the pointer variables always point to the corresponding type of data.
Example:
Float a,b;
Int x, *p;
p=&a;
b=*p;
In the above example the result will give an error because we are trying to assign the address
of a float variable to an integer pointer. Care should be taken to avoid wrong pointer
assignments.
Example: int x;
*p=&x;
Once a pointer has been assigned the address of a variable, the question remains as to
how to access the value of the variable using the pointer. This is done by using another unary
operator *(asterisk), usually known as the indirection operator. Consider the following
statements:
int qty, *q,m;
qty=165;
q=&qty;
m=*p;
The first line declares qty and m as integer variables and q as a pointer variable
pointing an integer. The second line assigns the value 165 to qty and the third line
assigns the address of qty to the pointer variable q. The fourth line contains the
indirection operator * . When the operator * is placed before a pointer variable in an
expression , the pointer will return the value of the variable. The * can be called as
‘value at address’ . Thus the value of q would be 165. The two statements
q=&qty;
m=*p;
are equivalent to
m=qty.
62
int m,n;
int *ptr;
m=15;
ptr=&m;
y=*ptr;
When an array is declared , the compiler allocates a base address and sufficient
amount of storage to contain all the elements of the array in memory locations. The base
address is the location of the first element(index 0) of the array.
63
printf(“Element value address\n\n”);
While(j<5)
{
printf(“ y [%d] %d %u \n”, j, *p, p);
sum=sum+p;
i++;
p++;
}
printf(“\n Sum= %d \n”, sum);
printf(“\n &x[0]=%u \n”, &x[0]);
printf(“ \n p = %u \n “, p);
}
64