C

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 64

C programming

TABLE OF CONTENTS:

1. Algorithms and Flowcharts:


a. The meaning of alogorithms/flowcharts and their need.
b. Writing algorithms and drawing flowcharts.
Exercises:
Finding the biggest of three numbers
To solve a quadratic equation
To find the biggest and smallest to given set of numbers and other examples.

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.

3. Numeric Constants and Variables


a. Integer Constants
b. Floating-point constants
c. Character constants
d. Backslash constants
e. String constants
f. Meaning of variables
g. Rules for defining variables
h. Declaration of variables
i. Assignment operators
j. Assignment expressions and assignment statements
k. Arithmetic conversion.
l. The four fundamental data types
m. Short hand assignment operators
n. Declaring variables as constant and as Volatile, Symbolic constants
o. Multiple assignment statements

4. Input and Output Functions


a. The scanf() and printf() functions for input and output operations respectively.
b. Formatted input and output using format specifiers.
c. The address operator(&).
d. The getchar() and putchar() functions.
e. Writing complete C programs

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 and flowcharts:

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.

The example below will make you understand the specifications:

Example: Recipe for Mutter paneer

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.

We will look at another example to examine another sequence of instructions:

Instructions to knit Sweater:

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

The above example shows:


1. The instructions are much more precise and unambiguous when compared to the recipe for
mutter paneer.
2. The number of different types of actions to be carried out are very few.
3. By a proper permutation and combination of this elementary set of actions a virtually
infinite number of patterns may be created.

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.

Algorithm and flowchart for finding biggest of three numbers:

Finding the biggest of three numbers


Step1: Read three numbers A, B, C
Step2: Compare A with B
Step3: If A is larger compare it with C
Step4: If A is larger than C then A is the largest otherwise C is the largest.
Step5: If A is smaller than or equal to B in the first step then B is compared with C.
Step6: If B is larger than C then B is the largest number otherwise C is the largest
number.
Step7: Stop

The above algorithm may be expressed much more clearly and concisely using a
flowchart.

Flowchart depicting the largest of three numbers. - A

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.

Flowchart depicting the solution for the quadratic equation….?

Algorithm to find the biggest and smallest of given set of numbers

Step1: Read Number


Step2: Assign the number to the value Largest
Assign the number to the value Smallest
Step3: Repeat steps 4 and 5 as long as numbers are there.
Step4: Read number
Step5: If the number is greater than largest then the number is largest.
If the number is lesser than smallest then the number is smallest.
Step6: Write Largest number
Write Smallest number
Step 7: Stop
Flowchart to depict the biggest and smallest of given set of numbers. - B

5
Algorithm to count the number of non-zero data

Step1: Initialize the non-zero data counter nzdcount to 0


Step2: Repeat 100 times all steps up to Step4
Step3: Read d
Step4: If d is not equal to 0 then
nzdcount =nzdcount+1
Step5: Print nzdcount
Step6: Stop

Flowchart depicting the number of non-zero data - C

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

Executing a program written in C involves a series of steps. These are


1. Creating the program.
2. Compiling the program.
3. Linking the program with functions that are needed from the C library.
4. Executing the 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.

Input and Output Functions:

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

For example, in the statement:


Scanf(“%d %d”, &p, &q);
The two variables in which numbers are used to be stored are p and q. The data to be
stored are integers. The integers will be separated by a blank in the data typed on the
keyboard.

A sample data line may thus be:


456 18578

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:

The general format of an output function is


Printf(format-string, var1,var2…..varn);
Where format-string gives information on how many variables to expect, what type of
arguments they are , how many columns are to be reserved for displaying them and any
character string to be printed. The printf() function may sometimes display only a
message and not any variable value. In the following example:
printf(“Answers are given below”);
The format-string is:
Answers are given below
And there are no variables. This statement displays the format-string on the video display
and there are no variables. After displaying, the cursor on the screen will remain at the
end of the string. If we want it to move to the next line to display information on the next
line, we should have the format-string:
printf(“Answers are given below\n”);
In this string the symbol \n commands that the cursor should advance to the beginning of
the next line.

In the following example:


printf(“Answer x= %d \n”, x);
%d specifies how the value of x is to be displayed. It indicates the x is to be displayed as
a decimal integer. The variable x is of type int. %d is called the conversion specification
and d the conversion character . In the example:
printf(“a= %d, b=%f\n”, a, b);
the variable a is of type int and b of type float or double. % d specifies that a is to be
displayed as an integer and %f specifies that, b is to be displayed as a decimal fraction. In
this example %d and %f are conversion specifications and d, f are conversion characters.

Example to indicate how printf() displays answers.

/*Program illustrating printf()*/


# include<stdio.h>

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

Example for illustrating scanf and printf statements:

/* Program for illustrating use of scanf and printf statements */

#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:

The first four data displayed


-768 362 abf6 3856
Display of the rest of the data read
-26.680000 2.800000 e-03 1.256000e+22 6.866000
End of display

The getchar function

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.

The general syntax


Character variable=getchar();
Where character variable refers to some previously declared character variable.

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.

The putchar function:


Single characters can be displayed using the C library function putchar. This function
is complementary to the character input function getchar. The putchar function, like getchar,
is a part of the standard C I/O library. It transmits a single character to a standard output
device. The character being transmitted will normally be represented as a character type
variable. It must be expressed as an argument to the function, enclosed in parentheses,
following the word putchar.
The general syntax is
putchar(character variable)

where character variable refers to some previously declared character variable.

A C program contains the following statements

Char c;
………
putchar(c);

C programs:

1) Program to demonstrate printf statement

11
#include<stdio.h>

main()
{
printf(“hello, world\y”);
printf(“hello, world\7”);
printf(“hello, world\?”);
}

2) Program to convert farenheit to Celsius

#include<stdio.h>
main()
{
float fahr, Celsius;

printf(“ enter the value for farenheit\n”);


scanf(“ %f”, &fahr);
Celsius=(5.0/9.0)*fahr-32.0;
printf(“%f %f \n”, fahr,Celsius);
}

3) Program to depict interactive computing using scanf function.

#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

Enter an integer number


54
Your number is smaller than 100

12
Enter an integer number
108
Your number contains more than digits

4) Program to depict interactive investment program

#include<stdio.h>

main()
{
int year,period;
float amount,inrate,value;

printf(“Input amount , interest rate and period \n\n”);


scanf(“%f %f %d”, &amount, &inrate,&period);
printf(“\n”);
year=1;

while(year<=period)
{
value amount + inrate*amount;
printf(“%2d Rs. %8.2f\n”, year, value);
amount=value;
year=year+1;
}
}

5) Program to calculate the average of a set of N numbers

#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);
}

6) Program to convert days to months and days

#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:

(i) He should get 50 percent or more in Physics and 40 percent or more


in Mathematics.
(ii) If he gets less than 50 percent in Physics he should get 50 percent or
more in Mathematics. He should get atleast 40 percent in Physics.
(iii) If he gets less than 40 percent in Mathematics and 60 percent or more
in Physics he is allowed to reappear in an examination in Mathematics
to qualify.
(iv) In all the other cases he is declared to have failed.

A Decision Table for Examination Results

Chemistry marks >=50 >=35 >= 60 Else


Physics Marks >=35 >=50 <35

Pass x x - -
Repeat Physics - - x -
Fail - - - x

/*This program implements above rules*/

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)))

Printf(“%d %d %d Pass\n”, roll_no, chem_marks, physics_marks);

Else

If (( chem_marks>=60)) && physics_marks<35))

Printf(“%d %d %d Repeat Physics\n”, roll_no,physics_marks,chem_marks);

Else
Printf(“%d %d %d Failed \n”, roll_no, physics _marks, chem_marks);
}
}/*End while*/
}/*End main*/

Precedence of relational operators and logical operators:

Example:

(a>b *5) &&(x<y+6)

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 .

In general within parentheses:

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 conditional operators:

An operator called ternary operator pair “?:” is available in C to construct conditional


expressions of the form.
exp1? exp2: exp3;
where exp1,exp2, and exp3 are expressions.

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.

For example, consider the following statements


x=3;
y=15;
z=(x>y)?x:y;

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:

C has a distinction of supporting special operators known as bitwise operators for


manipulation of data at bit level. These operators are used for testing the bits, or shifting
them right or left. Bitwise operators may not be applied to float or double.
where the filename is the name containing the required definitions or functions. At this point,
the preprocessor inserts the entire contents of the filename into the source code of the
program. When the filename is included within the double quotation marks, the search for
the file is made first in the directory and then in the standard directories.

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.

Some examples are given below:

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:

Each operator in C has a precedence associated with it. This precedence is


used to determine how an expression involving more than one operator is
evaluated. The operator at the higher level of precedence are evaluated first.

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 defines a macro substitution


#undef Undefines a macro
#include Specifies the files to be included.
#ifdef Tests for a macro definition
#endif Specifies the end of #if
#ifndef Tests whether a macro is not defined
#if Tests a compile-time condition
#else Specifies alternatives when #if tests fails

#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”

The #include directive can take the form

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.

General form of if statement :

The general form of if statement looks like

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

The three logical operators used are

&& and
|| or
! not

&& operator return true when all conditions are evaluated to true. Otherwise it return false.
For example

((5 > 4) && ( 2 < 3)) return true.

|| operator return true when one of the condition returns true, otherwise it returns false. For
example

((5 > 4) || ( 2 > 4)) return true

! operator is used to negate the result. For example


(!(5>4)) return false.

Let us see some of the 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);
}

Multiple statements within if

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;

printf(“input the coefficients of a b and c\n”);

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.

Let us consider an example.

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”);
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.

The default case is optional and catches any other cases.

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:

expression1 ? expression2: expression3

It simply states:

if expression1 then expression2 else expression3

For example to assign the maximum of a and b to z:

z = (a>b) ? a : b;

which is the same as:

if (a>b)
z = a;
else
z=b;

problem : Find out larger of two numbers using ternary operator

#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 :

C language provides three types of loop, while, do while and for.

• 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

We use a while statement to continually execute a block of statements while a condition


remains true. The following is the general syntax of the 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.

Let us consider a simple example, to calculate the factorial of a number

#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.

Let us consider an example to calculate the factorial using do-while loop.

#include < stdio.h>


main()
{
int n, fact, i;

printf(“input an integer\n”);
scanf(“%d”,&n);
fact=1;
i=1;
do
{
fact=fact*i;
++i;
}
while ( i <= n);

printf(“factorial = %d\n”, fact);


}

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.

for (initialization; termination; increment) {


statement(s)
}

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.

for ( ; ; ) { //infinite loop


...

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.

In C language ,single-subscripted variable xi can be represented as


x[1],x[2],x[3]……………x[n]

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 values can be assigned as follows:


Num[0]=57;
Num[1]=20;
Num[2]=56;
Num[3]=17;
Num[4]=23;

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:


There are certain situations where a table of values will have to be stored. C allows us
to define such table using two dimensional arrays.
Two dimensional arrays are declared as follows:
Type array_name [row_size][column_size]
In c language the array sizes are separated by its own set of brackets.

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.

Column0 Column1 Column2

[0][0] [0][1] [0][2]

Row 0 210 340 560

31
[1][0] [1][1] [1][2]

Row 1 380 290 321

[2][0] [2][1] [2][2]

Row2 490 235 240

Row3 [3][0] [3][1] [3][2]

240 350 480

Declaration and initialization of arrays:

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:

The general form of initialization of arrays is:

Static type array-name[size]={ list of values};


The values in the list are separated by commas.
For example, the statement below shows
Static int num[3]={2,2,2};
Will declare the variable num as an array of size 3 and will assign two to each element. If the
number of values is less than the number of elements, then only that many elements will be
initialized. The remaining elements will be set to zero automatically.
For example:
Static float num1[5]={0.1,2.3,4.5};
Will initialize the first three elements to 0.1,2.3 and 4.5 and the remaining two elements to
zero. The word static used before type declaration declares the variable as a static variable.
In some cases the size may be omitted. In such cases, the compiler allocates enough space for
all initialized elements. For example, the statement
Static int count[ ]= {2,2,2,2};
Will declare the counter array to contain four elements with initial values 2.

Character arrays may be initialized in a similar manner. Thus, the statement


Static char name[ ]={ ‘S ‘W,’A,’N}
Declares the name to be an array of four characters, initialized with the string “SWAN”

There certain draw backs in initialization of arrays.


1. There is no convenient way to initialize only selected elements.
2. There is no shortcut method for initializing a large number of array elements.

Reading Writing and manipulation of above types of arrays.

Program to read and write two dimensional 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”);
}

Program showing one-dimensional array

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:

Program to print multiplication tables

#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

1) Write a C program to convert a binary number to decimal number using one-


dimensional array.

#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);
}

2) Program to calculate the total cost of tubes

#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);
}

3) Program to show swapping of numbers.

#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”);
}

4) Program to sort a list of numbers:

#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]);
}

5) Program to calculate standard deviation

#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);
}

6) Program to find the largest and smallest of numbers:

#include<stdio.h>
main()
{
int I,s, largcount,smcount;
float num[30],lar,small;

printf(“\n size of array (MAX 30): \t”);


scanf(“%d”, &size);

printf(“\n Array elements:\t”);

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:

Need for user-defined functions:


The function main() is a specially recognized function in C. Every program
must have a main function to indicate where the program has to begin its execution. It is
possible to code any program utilizing only main function, it leads to a number of
problems. The program may become too large and complex and as a result the task of
debugging, testing and maintaining becomes difficult. If a program is divided into
functional parts, then each part may be independently coded and later combined into a
single unit. These subprograms called ‘functions’ are much easier to understand, debug,
and test. Sometimes it is also called “divide and conquer “.

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.

This approach clearly results in a number of advantages.

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

Function 1 Function2 Function3 Function4 Function5

39
Top-down modular programming using functions
Defining and using functions:

All the functions have the form:


Function-name(argument list)
{
local variable declarations;
executable statement1;
executable statement2;
---------------------------;
--------------------------- ;
return(expression);
}

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.

Category 1: Functions with no arguments and no return values.


Category 2: Functions with arguments and no return values.
Category 3: Functions with arguments and return values.

No arguments and no return values:

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.

Function1() No input function2()

{ {
----------------
function2() --------------
---------------- --------------
---------------- --------------
} }

A program with three user-defined functions is given below.


Functions with no arguments, no return values:

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);
}

Functions with arguments and no return values:


We can make the calling function to read data from the terminal and pass it on to the
called function. The nature of data communication between the calling function and
the called function with arguments but no return values is shown below.

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.

Program to show functions with arguments but no return values

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);
}

Arguments with return values:

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
}

Program to show functions with arguments and return values

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.

Returning non-integer value from functions:

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.

1. The explicit type_specifier, corresponding to the data type required must be


mentioned in the function header. The general form of the function definition is.
Type-specifier function-name(argument list)
argument declaration;
{
function statements;
}
The type-specifier tells the compiler, the type of data the function is to return.

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.

Program showing the transfer of a floating-point value between functions.

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.

It is possible to pass the values of an array to a function. To pass an array to a called


function, it is sufficient to list the name of the array without any subscripts, and the size
of the array as arguments.
The largest(a,n):
Will pass all the elements contained in the array a of size n. The called function expecting
this call must be defined appropriately. The largest function header might look like:
float largest(array,size)
float array[ ];
int size;
The function largest is defined to take arguments , the array name and the size of the
array to specify the number of elements in the array. The declaration of the formal
argument array is made as follows:
float array[ ];
The pair of brackets informs the compiler that the argument is an array of numbers. It is
not necessary to specify the size of the array here.

Consider the following example:


main()
{
float large();
static float value[5]={ 3.4,-12.78,1.23,5.67,8.90};
printf(“%f \n”, large(value,5));
}
float large(x,n)
float a[ ];
int n;
{
int j;
float max;
max=a[0];

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;
------------
------------
}

Program to show the working of local variables.

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.

Program to show static variable

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);
}

Program to show sorting of array elements.

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.

Declaring and initializing string variables:


The general form of string variable is
char string_name[size];
The size determines the number of characters in the string-name.
Some examples are:
char state[10];
char name[30];
When the compiler assigns a character string to a character array, it automatically supplies a
null character(‘\0’) at the end of the string.

Character arrays may be initialized when they are declared. C permits a character array to be
initialized in either of the following two forms:

Static char state[10]=” KARNATAKA”;


Static char state[10]={‘K’,’A’,’R’,’N’,’A’,’T’,’A’,’K’,’A’\O’};

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.

C also permits us to initialize a character array without specifying the number of


elements.
For example, the statement

static char string[ ] ={‘H’, ‘E’, ‘L’, ‘L’, ‘O’ \O};

Defines the array string as a six element array.

Reading and writing strings:


To read a string of characters input function scanf can be used with %s
format specification.
Example:
char add[20];
Scanf(“%s”, add);
Note that unlike previous scanf calls, in the case of character arrays, the &(ampersand) is not
required before the variable name. The scanf function automatically terminates the string
that is read with a null character and therefore the character array should be large enough to
hold the input string plus the null character.

Program to read a series of words using scanf function

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);

Can be used to display the entire contents of the array name.

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.

Program to illustrate writing strings using %s format

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

strcat() concatenates two strings


strcmp() compares two strings
strcpy() copies one string with another
strlen() finds the length of a string.

String Concatenation :strcat() function:

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);

Text1= VERY GOOD\0


Text2= GOOD\0

Strcat(text1,text3);

Text1= VERY BAD


Text2= BAD

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”);

C permits nesting of strcat functions. The statement


strcat(strcat(string1,string2),string3);
Is allowed and concatenates all the three strings together. The resultant string is stored in
string1.

String comparison/strcmp() function:

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.

String copying/strcpy() function:

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.

Finding the length of a string/strlen();

This function counts and returns the number of characters in a string.


The general syntax is n=strlen(string);

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.

Implementing the above functions without using string functions:

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.

Program to show concatenation of strings:

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:

Comparison of two strings cannot be compared directly. It is therefore necessary to


compare the strings to be tested, character by character. The comparison is done until there is
a mismatch or one of the strings terminates into a null character.
The following segment of a program illustrates this,

-----------------------------
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:

Program to show copying of two strings:

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);
}

Program to find the length of a string:

#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);
}

Arithmetic operations on characters:


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

To write a character in its integer representation , we may write it as an integer. For


example:
y=’a’;
printf(“%d\n”, y);
will display the number 97 on the screen.

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 may also use character constants in relational expressions. For example:


ch>=’a’ && ch<=’z’
Would test whether the character contained in the variable ch is an lower-case letter.

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:

Program to sort strings in alphabetical order:

#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]);
}

Program to show string handling functions:

#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);
}

Program to convert lowercase characters in to upper case characters:

#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:

Pointer data type:

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;

variable address contents


name

m 8468 35

Declaring and initializing variables:

Since pointer variables contain addresses that belong to a separate


data type, they must be declared as pointers before we use them. The declaration of a pointer
variable has the following form:

Data type *pt_name;

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.

Similarly, the statement


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

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.

A pointer variable can be initialized in its declaration .

Example: int x;
*p=&x;

Accessing a variable through its pointer:

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.

Program for accessing variables using pointers


main()

62
int m,n;
int *ptr;

m=15;
ptr=&m;
y=*ptr;

printf(“Value of m is %d\n\n”, m);


printf(“%d is stored at address %u \n”, m,&m);
printf(“%d is stored at address %u \n”, &m, &m);
printf(“%d is stored at address %u \n”, ptr, &ptr);
printf(“%d is stored at address %u \n”, y, &y);
*ptr=30;
printf(“\n Now m=%d\n”,x);
}

Pointers and one dimensional arrays:

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.

static int y[4]= {1,2,3,4,5};


Suppose the base address of y is defined as a constant pointer pointing to the first
element , y[0] and therefore the value of y is 1000.
That is,
y=&y[0]=1000
If we declare p as an integer pointer , then we can make the pointer p to point to the array y
by the following assignment:
p=y;
This is equivalent to
p=&y[0];
The relationship between p and y is shown below.
P =&y[0] (=1000)
P+1 =&y[1](=1002)
P+2 =&y[2](=1004)
P+3 =&y[3](=1006)
P+4 =&y[4](=1008)
Program to show pointers in one-dimensional arrays:
main()
{
int *p,sum,j;
static int y[5]={4,5,7,8,0};
j=0;
p=y;
sum=0;

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

You might also like