[go: up one dir, main page]

0% found this document useful (0 votes)
26 views66 pages

2014 C Notes (Repaired)-3(1)

Uploaded by

t.ambika1991
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views66 pages

2014 C Notes (Repaired)-3(1)

Uploaded by

t.ambika1991
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 66

1

UNIT – I

OVERVIEW OF C:

HISTORY OF C

‘C’ seems a strange name for a programming language. ‘C’is a structured, high-level,
machine independent language. It allows software developers to develop programs without
worrying about the hardware platforms where they will be implemented.
The root of all modem languages is ALGOL, introduced in the early 1960s. ALGOL
was the first computer language to use a block structure.

In 1967, Martin Richards developed a language called BCPL (Basic Combined


Programming Language) primarily for writing system software.

In 1970,Ken Thompson created a language using many features of BCPL and called it
simply B. B was used to create early versions of UNIX operating system at Bell Laboratories.

C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories
in 1972. C uses many concepts from these languages and added the concept or data type and
other powerful features. Since it was developed along with the UNIX operating system, it is
strongly associated wilh UNIX.

Today, C is running under a variety of operating system and hardware platforms.


During 1970. C had evolved now known as “traditiono1 C”

1960 ALGOL International Group

1967 BCPL Martin Richards

B
1970 Ken Thompson

1972 TRADITIONAL C Dennis Ritchie

K&R C
1978 Kernighan and Ritchie

ANSI C
1989 ANSI Committee

ANSI/ISO C
1990 ISO Committee

C99
1999 Standardization Committee
2
IMPORTANCE OF C

C has all the advantages of assembly Language and all the significant features of modern high
level ‘Language. So it is called middle Level Language.

C Language is a very powerful and flexible language.

 It consist of rich set of operators.


 Provides dynamic storage allocation.
 It supports a number of data types.
 C Language is a portable Language. A code written in c on a Particular machine can
be compiled and run on another machine.
 C is used for all kinds of applications because of its portability and efficiency.
 Its ability to extend itself.
 It is basically consists of a collection of functions that are supported by c library.
 C is a robust language which is used to write any complex program using of its rich
set of built in functions and operators.

BASIC STRUCTURE OF C PROGRAMS


A C program may consist of one or more following sections:

Documentation section

link section

definition section

Global declaration section

main() function section


{

}
subprogram section
(user defined function)

subprogram section
(user defined function)
3

1) Documentation section – It gives the name of the program, the author and any other details
about the program.

2) Link section – It provides instruction to the compiler to link functions from the system
library.

3) Global declaration section – Global variables are declared in this section.

4) Main( ) function section – Every C program must have one main() function. The program
execution begins at the opening brace and ends at the closing brace of main function section.

5) Subprogram section – It contains all the user-defined functions that are called in the main
function.

CONSTANTS, VARIABLES AND DATA TYPES:

CHARACTER SET

A character denotes any alphabet, digit or symbols to represent information. The


following are the valid alphabets, numbers and special symbols permitted in C .

The charater in C are catgorised into the following categories:

1. Letters

2. Digits

3. Special characters

4. White spaces

Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Letters: a, b,.…z A, B, ……...Z

Arithmetic Operators: +, -, *, /, %(Mod)

Special Characters:

, -comma ‘ -apostrophe

“ -quotation mark ! -exclamation mark

| -vertical bar / -slash

\ -backslash ~ -tilde

_ -underscore . –period
4
; -semicolon : -colon

? -question mark $ - dollar sign

% - percent sign &-ampersand symbol

^-caret *-asterisk

- Minus sign +-plus sign

<-opening angle bracket >-closing angle bracket

(-left paranthesis )-right paranthesis

[-left bracket ]-right bracket

{-left brace }-right brace

#-number sign

TRIGRAPH CHARACTERS

Each trigraph sequence consists of three characters (two question marks followed by another
character)

Trigraph sequence Translation

??= # number sign

?? ( [ left bracket

??) ]Right bracket

??< { left brace

??> }Right brace

??! | vertical bar

?? / \ back slash

??- ~ tilde

C TOKENS

In an individual words and punctuation marks are called tokens. Similarly , In a C program
the smallest individual units are known as C tokens. C has fixed type of tokens as
follows.
1. Keywords ( float, while )
5
2. Identifiers ( amount )
3. Constants ( 100 , 200)
4. Strings (“hello”)
5. Operators ( + - * % )
6. Special symbols { } []

KEYWORDS

Every c word is classified as either a keyword or an identifier. All key words have
fixed meanings cannot be changed. A keyword may not be used as a variable name. All
keywords must be written in lowercasae.

auto Double int struct

break else long switch


case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

IDENTIFIERS

Identifiers refer to the names of variables, functions and arrays. These are user-
defined names and consist of a sequence of letters and digits, with a letter as a first character.
Both lowercase and uppercase letters are permitted. Rules for Identifiers
1. First character must be an alphabet or underscore.
2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. Cannot use a keyword.
5. Must not contain white space.
Example: name, area, amount.

CONSTANTS, VARIABLES AND DATA TYPES:


6
CONSTANTS

A constant is fixed values that do not change any value during the execution of a
program.

There are mainly two types of constants namely: Numeric and character constants.
CONSTANTS

Numeric constants Character constants

Integer Real Single character String


Constants Constants Constants Constants

Integer Constants

The integer constant is

 Whole Numbers (Eg. 25, 35, -25, -46 )


 Computer allocates only 2 bytes in memory.
 16th bit is sign bit. (if 0 then +ve value, if 1 then –ve value)

Single Character Constants


A single character constant is an alphabet, a single digit or a single special symbol
enclosed within inverted commas. The maximum length of a character constant can be 1
character. Allots 1 byte of memory

Ex: ’B’, ’l’, ’#’

Character constants have integer values known as ASCII values. For example, the
statement

Printf(“%d” , ‘a’);

Would print the number 97, the ASCII value of the letter a. Similarly, the statement

Printf(“%d” , ‘97’);

Would print the value ‘a’.

Backslash character constants


7
These constants are used in output functions. Each one of them represents one
character although they consists two characters. These character combinations are known as
escape sequences.

Constants Meaning
‘\a’ Audible alert(bell)
‘\b’ Back space
‘\f’ Form feed
‘\n’ Newline
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\v’ Vertical tab
‘\’ Single quote
‘\”’ Double quote
‘\?’ Question mark
‘\\’ Backslash
‘\0’ null

String Constants:
A combination of characters enclosed within a part of double inverted commas is called
as “String Constant”.
Example :
“Salem” “35.675” ,

VARIABLES

Variable is a quantity whose value changes during the execution of a program.

Variable names are names given to locations in the memory. These locations can
contain integer, real or character constants.

An integer variable can hold only an integer constant, a real variable can hold only a
real constant and a character variable can hold only a character constant. Rules for
Constructing Variable Names

A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some


compilers allow variable names whose length could be up to 247 characters.

 The first character in the variable name must be an alphabet


 It should begin with a letter. Some systems permit underscore as the first character.
8
 Uppercase and lowercase are significant.
 No commas or blanks are allowed within a variable name.
 No special symbol other than an underscore (as in net_sal) can be used in a variable
name.
 It should not be a keyword.
 White space is not allowed.

Ex.: si int e_hra pod_e_81

DATA TYPES

C language data types can be broadly classified as

Primary (or fundamental) data type


Derived data type
User-defined data type

A programming language is proposed to help programmer to process certain kinds of


data and to provide useful output. The task of data processing is accomplished by executing
series of commands called program. A program usually contains different types of data types
(integer, float, character etc.) and need to store the values being used in the program. C language
is rich of data types. A C programmer has to employ proper data type as per his requirement.

All c compilers support five fundamental data types namely integer (int), character
(char), floating point (float), double precision floating point (double) and void. The basic four
types are

i) Integer types

a) Integer

signed : int short int long int

unsigned : unsigned int unsigned short int unsigned long int

b) character

char signed char unsigned char

c) Floating type

float double long double

d) void
9

Integer types:

Integers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -
32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest
15bits for number.
To control the range of numbers and storage space, C has three classes of integer storage
namely short int, int and long int. All three data types have signed and unsigned forms.

A short int requires half the amount of storage than normal integer. Unlike signed
integer, unsigned integers are always positive and use all the bits for the magnitude of the
number. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers
are used to declare a longer range of values and it occupies 4 bytes of storage space.

Syntax: int <variable name>; like


int num1;
short int num2;
long int num3;

Example: 5, 6, 100, 2500.

Integer Data Type Memory Allocation

Floating Point Types:

The float data type is used to store fractional numbers (real numbers) with 6 digits of
precision. Floating point numbers are denoted by the keyword float. When the accuracy of the
floating point number is insufficient, we can use the double to define the number. The double is
same as float but with longer precision and takes double space (8 bytes) than float. To extend
the precision further we can use long double which occupies 10 bytes of memory space.

Syntax: float <variable name>; like


float num1;
10
double num2;
long double num3;

Example: 9.125, 3.1254.

Floating Point Data Type Memory Allocation

Character Type:

Character type variable can hold a single character. As there are singed and unsigned int
(either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte
each, but having different ranges. Unsigned characters have values between 0 and 255, signed
characters have values from –128 to 127.

Syntax: char <variable name>; like


char ch = ‘a’;
Example: a, b, g, S, j.

Void Type:

The void type has no values therefore we cannot declare it as variable as we did in case
of integer and float.
The void data type is usually used with function to specify its type. Like in our first C
program we declared “main()” as void type because it does not return any value. The concept of
returning values will be discussed in detail in the C function hub.

2. Secondary Data Types

 Array in C programming
An array in C language is a collection of similar data-type, means an array can hold
value of a particular data type for which it has been declared. Arrays can be created from
any of the C data-types int,
 Pointers in C Programming
A pointer is derived data type in c. Pointers contain memory addresses as their values.
11
 Structure in C Programming
We used variable in our C program to store value but one variable can store only single
piece information (an integer can hold only one integer value) and to store similar type of
values we had to declare...

3. User defined type declaration

C language supports a feature where user can define an identifier that characterizes an
existing data type. In short its purpose is to redefine the name of an existing data type.
Syntax: typedef <type> <identifier>; like
typedef int number;

User defined type declaration

In C language a user can define an identifier that represents an existing data type. The user
defined data type identifier can later be used to declare variables.

The general syntax is


typedef type identifier;
here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to
the data type.
Example:
typedef int salary;
typedef float average;
Here salary symbolizes int and average symbolizes float. They can be later used to
declare variables as follows:
Units dept1, dept2;
Average section1, section2;
Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and
section2 are indirectly float data type.
The second type of user defined datatype is enumerated data type which is defined as
follows.
Enum identifier {value1, value2 …. Value n};
The identifier is a user defined enumerated datatype which can be used to declare
variables that have one of the values enclosed within the braces. After the definition we can
12
declare variables to be of this ‘new’ type as below.
enum identifier V1, V2, V3, ……… Vn

The enumerated variables V1, V2, ….. Vn can have only one of the values value1,
value2 ….. value n
Example:
enum day {Monday, Tuesday, …. Sunday};
enum day week_st, week end;
week_st = Monday;
week_end = Friday;
if(wk_st == Tuesday)
week_en = Saturday;

DECLARATION OF VARIABLES

The declaration does two things.

1. Tells the compiler the variables name.


2. Specifies what type of data the variable will hold.
a) Primary type declaration

A variable can be used to store value of any data type. The general format of any declaration is
datatype v1, v2, v3, ……….. vn;
Where v1, v2, v3 are variable names. Variables are separated by commas. A declaration
statement must end with a semicolon.
Example:

int sum;
int number, salary;
double average, mean;

Datatype Keyword Equivalent

Character char

Signed Character signed char


Unsigned Character unsigned char
Signed Integer signed int (or) int

Signed Short Integer signed short int (or) short int (or) short

Signed Long Integer signed long int (or) long int (or) long
13

UnSigned Integer unsigned int (or) unsigned

UnSigned Short Integer unsigned short int (or) unsigned short

UnSigned Long Integer unsigned long int (or)


unsigned long

Floating Point float

Double Precision Floating Point double

Extended Double Precision Floating Point long double

b) User defined type declaration


The user defined data type identifier can later be used to declare variables.
The general syntax is

typedef type identifier;

here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to
the data type.

Example:

typedef int salary;


typedef float average;

The second type of user defined datatype is enumerated data type which is defined as
follows.

Enum identifier {value1, value2 …. Value n};

The identifier is a user defined enumerated datatype which can be used to declare
variables that have one of the values enclosed within the braces. After the definition we can
declare variables to be of this ‘new’ type as below.

enum identifier V1, V2, V3, ……… Vn

The enumerated variables V1, V2, ….. Vn can have only one of the values value1,
value2 ….. value n

Example:

enum day {Monday, Tuesday, …. Sunday};


enum day week_st, week end;
week_st = Monday;
week_end = Friday;
14
if(wk_st == Tuesday)
week_en = Saturday;

ASSIGNING VALUES TO VARIABLES

Variables are created for use in program statements


a)Assignment Statement:
Values can be assigned to variables using the assignment operator = as follows:
Syntax:
variable_name = constant;
Eg: initial_value = 0;
C permits multiple assignments in one line
Eg: initial_value = 0; final_value = 100;
It is possible to assign a value to a variable at the time the variable is declared.
data-type variable_name = constant;

Example: int final_value = 100;


char yes = ‘x’;
The process of giving initial values to variables to called initialization.
Example: p = q = s = 0;
x = y = z = MAX;

b) Reading Data From Keyboard

Another way of giving values to variables is to input data through keyboard using the scanf
function.
The general format of scanf is as follow:
scanf(“control string”, & variable1,&variable2,…….)

Example: scanf(“%d”, &number);

c) Declaring Variable As Constant


15
The values of some variable may be required to remain constant through-out the
program. We can do this by using the qualifier const at the time of initialization. Example:
Const int class_size = 40;

The const data type qualifier tells the compiler that the value of the int variable class_size may
not be modified in the program.

d) Declaring Variable As Volatile


The qualifier volatile used to tell explicitly the compiler that a variable’s value may be
changed at any time by some external sources.

Volatile int date;

When we declare a variable as volatile, the compiler will examine the value of the
variable each time it is encountered to see whether any external alteration has changed the
value.
The value of the variable declared as volatile can be modified by its own program as
well. The value must not be modified by the program while it may be altered by some other
process, then we declare the variable as both const and volatile
Volatile const int location =100;

OPERATORS AND EXPRESSIONS:

OPERATORS:

Operators are the symbol which operates on value or a variable. For example: + is a operator to
perform addition. C programming language has wide range of operators to perform various
operations. For better understanding of operators, these operators can be classified as:

Operators in C programming

Arithmetic Operators

Increment and Decrement Operators

Assignment Operators

Relational Operators
16
Logical Operators

Conditional Operators

Bitwise Operators

Special Operators

Arithmetic Operators

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* Multiplication

/ Division

% remainder after division( modulo division)

Example of working of arithmetic operators

/* Program to demonstrate the working of arithmetic operators in C. */


#include <stdio.h>
int main(){
int a=9,b=4,c;
c=a+b;
printf("a+b=%d\n",c);
c=a-b;
printf("a-b=%d\n",c);
c=a*b;
printf("a*b=%d\n",c);
c=a/b;
printf("a/b=%d\n",c);
c=a%b;
printf("Remainder when a divided by b=%d\n",c);
return 0;
}
}

OUTPUT:
a+b=13
a-b=5
a*b=36
17
a/b=2
Remainder when a divided by b=1

Explanation

Here, the operators +, - and * performed normally as you expected. In normal calculation, 9/4
equals to 2.25. But, the output is 2 in this program. It is because, a and b are both integers. So,
the output is also integer and the compiler neglects the term after decimal point and shows
answer 2 instead of 2.25. And, finally a%b is 1,i.e. ,when a=9 is divided by b=4, remainder is 1.

Suppose a=5.0, b=2.0, c=5 and d=2


In C programming,
a/b=2.5
a/d=2.5
c/b=2.5
c/d=2

Note: % operator can only be used with integers.

Increment and decrement operators

In C, ++ and -- are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts
1 to operand respectively. For example:

Let a=5 and b=10


a++; //a becomes 6
a--; //a becomes 5
++a; //a becomes 6
--a; //a becomes 5

Difference between ++ and -- operator as postfix and prefix

When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return
it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and
then only increment it. This can be demonstrated by an example:

#include <stdio.h>
int main()
{
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is displayed.
return 0;
}

Output

2 4
18
Assignment Operators

The most common assignment operator is =. This operator assigns the value in right side to the
left side. For example:

var=5 //5 is assigned to var


a=c; //value of c is assigned to a
5=c; // Error! 5 is a constant.

Operator Example Same as

= a=b a=b

+= a+=b a=a+b

-= a-=b a=a-b

*= a*=b a=a*b

/= a/=b a=a/b

%= a%=b a=a%b

Relational Operator

Relational operator’s checks relationship between two operands. If the relation is true, it returns
value 1 and if the relation is false, it returns value 0. For example:

a>b. Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it
returns 0.

Relational operators are used in decision making and loops in C programming.

Operator Meaning of Operator Example

== Equal to 5= =3 returns false (0)

> Greater than 5>3 returns true (1)

< Less than 5<3 returns false (0)

!= Not equal to 5!=3 returns true(1)

>= Greater than or equal to 5>=3 returns true (1)

<= Less than or equal to 5<=3 return false (0)


19
Operator Meaning of Operator Example

Logical Operators

Logical operators are used to combine expressions containing relation operators. In C, there are
3 logical operators:

Meaning of
Operator Example
Operator

If c=5 and d=2 then,((c==5) && (d>5))


&& Logical AND
returns false.

If c=5 and d=2 then, ((c==5) || (d>5)) returns


|| Logical OR
true.

! Logical NOT If c=5 then, !(c==5) returns false.

Explanation

For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is
false in the given example. So, the expression is false. For expression ((c= =5) || (d>5)) to
be true, either the expression should be true. Since, (c= =5) is true. So, the expression is
true. Since, expression (c= =5) is true! (c= =5) is false.

Conditional Operator

Conditional operator takes three operands and consists of two symbols? and: . Conditional
operators are used for decision making in C. For example:

c=(c>0)?10:-10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.

Bitwise Operators

A bitwise operator works on each bit of data. Bitwise operators are used in bit level
programming.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR
20
Operators Meaning of operators

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Bitwise operator is advance topic in programming

Other Operators

Comma Operator

Comma operators are used to link related expressions together. For example:

int a,c=5,d;

The sizeof operator

It is a unary operator which is used in finding the size of data type, constant, arrays, structure
etc. For example:

#include <stdio.h>
int main(){
int a;
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
}

Output

Size of int=4 bytes


Size of float=4 bytes
Size of double=8 bytes
Size of char=1 byte

Conditional operators (? :)

Conditional operators are used in decision making in C programming, i.e, executes different
statements according to test condition whether it is either true or false.
21
Syntax of conditional operators
conditional_expression? expression1:expression2

If the test condition is true, expression1 is returned and if false expression2 is returned.

Example of conditional operator


#include <stdio.h>
int main(){
char feb;
int days;
printf("Enter l if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days=(feb=='l')?29:28;
/*If test condition (feb=='l') is true, days will be equal to 29. */
/*If test condition (feb=='l') is false, days will be equal to 28. */
printf("Number of days in February = %d",days);
return 0;
}

Output

Enter l if the year is leap year otherwise enter n: l


Number of days in February = 29
22

UNIT II

DECISION MAKING AND BRANCHING:

if, if..Else and Nested if...else Statement:

Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. In C, decision making can be performed with following two
statements.

1. IF STATEMENT:

if statement syntax

if (test expression){
Statement/s to be executed if test expression is true;
}
If the test expression is true then, statements for the body if, i.e, statements inside parenthesis
are executed. But, if the test expression is false, the execution of the statements for the body of
if statements are skipped.

Flowchart of if statement
23
2. IF...ELSE STATEMENT:

The if...else statement is used, if the programmer wants to execute some code, if the test
expression is true and execute some other code if the test expression is false.

Syntax of if...else

if (test expression)
Statements to be executed if test expression is true;
else
Statements to be executed if test expression is false;

Flowchart of if...else statement

Example of if...else statement

#include <stdio.h>
int main(){
int num;
printf("Enter a number you want to check.\n");
scanf("%d",&num);
if((num%2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
}
24
Output

Enter a number you want to check.


25
25 is odd.

3. NESTED IF...ELSE STATEMENT (IF...ELSE IF....ELSE STATEMENT)

The if...else statement can be used in nested form when a serious decision are involved.

Syntax of nested if...else statement.

if (test expression)
statements to be executed if test expression is true;
else
if(test expression 1)
statements to be executed if test expressions 1 is true;
else
if (test expression 2)
.
.
.
else
statements to be executed if all test expressions are false;

How nested if...else works?

If the test expression is true, it will execute the code before else part but, if it is false, the control
of the program jumps to the else part and check test expression 1 and the process continues. If
all the test expression are false then, the last statement is executed.

The ANSI standard specifies that 15 levels of nesting may be continued.

Example of nested if else statement

#include <stdio.h>
int main(){
int numb1, numb2;
printf("Enter two integers to check".\n);
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d=%d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d>%d",numb1,numb2);
else
25
printf("Result: %d>%d",numb2,numb1);
return 0;
}

Output 1

Enter two integers to check.


5
3
Result: 5>3

ELSE IF LADDER

There is another way of putting ifs together when multipath decisions are involved. A
multipath decision is a chain of it’s in which the statement associated with each else is an if. It
takes the following general form:

if (condition 1)
statement 1 ;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
else if (condition n)
statement n;
else
default statement;
statement x;

This construct is known as the else if ladder. The conditions are evaluated from the top (of the
ladder), downwards. As soon as a true condition is found, the statement associated with is
executed and the control is transferred to the statement x (skipping the rest of the ladder).

When all the n conditions become false, then the final else containing the default
statement will be executed.

4. SWITCH....CASE STATEMENT
26
Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. If a programmer has to choose one among many alternatives
if...else can be used but, this makes programming logic complex. This type of problem can be
handled in C programming using switch...case statement.

Syntax of switch...case

switch (expression)
{
case constant1:
codes to be executed if expression equals to constant1;
break;
case constant2:
codes to be executed if expression equals to constant3;
break;
.
.
.
default:
codes to be executed if expression doesn't match to any cases;
}

In switch...case, expression is either an integer or a character. If the value of switch expression


matches any of the constant in case, the relevant codes are executed and control moves out of
the switch...case statement. If the expression doesn't matches any of the constant in case, then
the default statement is executed.

Flow chart:

Example of switch...case statement


27
# include <stdio.h>
int main(){
char operator;
float num1,num2;
printf("Enter operator +, - , * or / :\n");
operator=getche();
printf("\nEnter two operands:\n");
scanf("%f%f",&num1,&num2);
switch(operator)
{
case '+':
printf("num1+num2=%.2f",num1+num2);
break;
case '-':
printf("num1-num2=%.2f",num1-num2);
break;
case '*':
printf("num1*num2=%.2f",num1*num2);
break;
case '/':
printf("num2/num1=%.2f",num1/num2);
break;
default:
printf(Error! operator is not correct");
break;
}
return 0;
}

Output
Enter operator +, -, * or /:
/
Enter two operators:
34
3
Num2/num1=11.33

GOTO STATEMENT

In C programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
Syntax of goto statement

goto label;
.............
.............
.............
label:
28
statement;

In this syntax, label is an identifier. When, the control of program reaches to goto statement, the
control of the program will jump to the label: and executes the code/s after it.

Reasons to avoid goto statement

Though, using goto statement give power to jump to any part of program, using goto statement
makes the logic of the program complex and tangled. In modern programming, goto statement is
considered a harmful construct and a bad programming practice.

The goto statement can be replaced in most of C program with the use of break and continue
statements. In fact, any program in C programming can be perfectly written without the use of
goto statement. All programmers should try to avoid goto statement as possible as they can.

DECISION MAKING AND LOOPING:

Loops causes program to execute the certain block of code repeatedly until some conditions are
satisfied, i.e., loops are used in performing repetitive work in programming.

Suppose you want to execute some code/s 10 times. You can perform it by writing that code/s
only one time and repeat the execution 10 times using loop.

There are 3 types of loops in C programming:

 for loop
 while loop
 do...while loop

WHILE LOOP:

Syntax of while loop

while (test expression)


{
Statements to be executed.
}
29
In the beginning of while loop, test expression is checked. If it is true, codes inside the body of
while loop,i.e, code/s inside parentheses are executed and again the test expression is checked
and process continues until the test expression becomes false.

Example of while loop

#include <stdio.h>
int main(){
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0){ /* while loop continues util test condition number>0 is true */
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
return 0;
}

Output

Enter a number.
5
Factorial=120

DO...WHILE LOOP:

In C, do...while loop is very similar to while loop. Only difference between these two loops is
that, in while loops, test expression is checked at first but, in do...while loop code is executed at
first then the condition is checked. So, the code are executed at least once in do...while loops.

Syntax of do...while loops

do {
some code/s;
30
}
while (test expression);

At first codes inside body of do is executed. Then, the test expression is checked. If it is true,
code/s inside body of do are executed again and the process continues until test expression
becomes false (zero).

Notice, there is semicolon in the end of while (); in do...while loop.

Example of do...while loop

#include <stdio.h>
int main(){
int sum=0,num;
do /* Codes inside the body of do...while loops are at least executed once. */
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return 0;
}

Output

Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
31
In this C program, user is asked a number and it is added with sum. Then, only the test condition
in the do...while loop is checked. If the test condition is true, i.e, num is not equal to 0, the body
of do...while loop is again executed until num equals to zero.

FOR LOOP

for Loop Syntax

for(initial expression; test expression; update expression)


{
code/s to be executed;
}

How for loop works in C programming?

The initial expression is initialized only once at the beginning of the for loop. Then, the test
expression is checked by the program. If the test expression is false, for loop is terminated. But,
if test expression is true then, the codes are executed and update expression is updated. Again,
the test expression is checked. If it is false, loop is terminated and if it is true, the same process
repeats until test expression is false.

Flow chart:

Example Program:

#include <stdio.h>
int main ()
{
/* for loop execution */
for( int a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}

When the above code is compiled and executed, it produces the following result:
32
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

JUMPS IN LOOPS:

 Loops perform a set of operations repeatedly until the control variables fails to
satisfy the test conditions.
 The number of times the loop is repeated is decided in advance and the test
conditions is returned to achieve this.
 Some times, when executing a loop it becomes desirable to skip a part of the loop
or to leave the loop as soon as a certain conditions occurs.
 C permits a jump form one statement to another within a loop as well as jump out of a
loop.
Jumping Out of a Loop:

 Exit from a loop can be accomplished by using the break statement or the goto
statement.
 These statements can also be used within while, do or for loops.
 When a break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop.
 When the loops are nested the break would only exit from the loop containing it. i.e the
break will exit only a single loop.
while (------) do for (-------)

{ { {

------- ------- ------

if (condition) if (condition)
if(error)
33
break; break; break;

-------- -------- Exit --------

} } from }

------- while (-------); loop ---------

UNIT - III
ARRAYS
An array is a fixed-size sequenced collection of elements of the same data type. It
is simply a grouping of like-type data. In its simplest form, an array can be used to
represent a list of numbers or a list of items.
An array is a group of related data items that share a common name.
An array is a collection of similar quantities. It is referenced by a common
name.
Each element of an array is stored in successive locations of memory.
Arrays to represent not only simple list of values but also tables of data tin two,
three or more dimensions.
 There are three types of arrays. They are
1. One-dimensional arrays.
2. Two-dimensional arrays.
3. Multidimensional arrays.

ONE DIMENSIONAL ARRAY

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 single subscripted variable xi can be expressed as x[1],x[2],x[3],….x[n] . The subscript


can begin with number 0.

Declaration of arrays:
Like any other variable arrays must be declared before they are used.
34
The general form of declaration is:

type variable-name[size or subscript of the array];

Where

The type specifies the type of the elements that will be contained in the array, such as
int, float or char

the size indicates the maximum number of elements that can be stored inside the array .

for ex: int a[5];

a is the name of the array with 5 subscripts of integer data types 0 to 4 and the computer
reserves five storage location as shown below.

a[0]

a[1]

a[2]

a[3]

a[4]

A value stored into an element in the array simply by specifying the array element on the
left hand side of the equals sign. In the statement

grades [100]=95;

The value 95 is stored into the element number 100 of the grades array.
The ability to represent a collection of related data items by a single array enables us to develop
concise and efficient programs. For example we can very easily sequence through the elements
in the array by varying the value of the variable that is used as a subscript into the array. So the
for loop

for(i=0;i < 100;++i);


sum = sum + grades [i];

Will sequence through the first 100 elements of the array grades (elements 0 to 99) and
will add the values of each grade into sum. When the for loop is finished, the variable sum will
35
then contain the total of first 100 values of the grades array (Assuming sum were set to zero
before the loop was entered)

Initialization of arrays:

An array can be initialized at either of the following stages:

 At compile time
 At run time

Compile time initialization


We can initialize the elements in the array in the same way as the ordinary variables
when they are declared. The general form of initialization of arrays is:

type array_name[size]={list of values};

The values in the list care separated by commas, for example the statement

int number[3]={0,0,0};

Will declare the array size as a array of size 3 and will assign zero to each element if the
number of values in the list is less than the number of elements, then only that many elements
are initialized. The remaining elements will be set to zero automatically.

In the declaration of an array the size may be omitted, in such cases the compiler allocates
enough space for all initialized elements. For example the statement

int counter[]={1,1,1,1};

Will declare the array to contain four elements with initial values 1. This approach works
fine as long as we initialize every element in the array.

The initialization of arrays in c suffers two draw backs


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

Run time initialization


36
An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays. For example

------
-------
For(i=0;i<100; i=i+1)
{ if i<50
Sum[i]=0.0;
else
sum[i]=1.0;
}
The first 50 elements of the array sum are initialized to zero while the remaining 50
elements are initialized to 2.0 at run time.

/* Program to count the no of positive and negative numbers*/


#include< stdio.h >
void main( )
{
int a[50],n,count_neg=0,count_pos=0,I;
printf(“Enter the size of the arrayn”);
scanf(“%d”,&n);
printf(“Enter the elements of the arrayn”);
for I=0;I < n;I++)
scanf(“%d”,&a[I]);
for(I=0;I < n;I++)
{
if(a[I] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the arrayn”,count_neg);
printf(“There are %d positive numbers in the arrayn”,count_pos);
}

Two-Dimensional Arrays

Two dimensional arrays are used in situation where a table of values needs to be stored
in an array.

C allows us to define such tables of items by using two-dimensional arrays.


Two- dimensional arrays are declared as follows:
type array_name [row-size][column-size];

Example:
int a[3][3];
37
Two-dimensional arrays are stored in memory. 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 --> 310 275 365

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


Row 1- 310 275 365

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


Row 2- 310 275 365

Initializing Two-dimensional Arrays

The two-dimensional arrays may be initialized by following their declaration with a list of initial
values enclosed in braces.
Example:
int table[2][3] = { 0, 0, 0, 1, 1, 1};
initializes the elements of the first two row to zero and the second row to one. The
initialization is done row by row.
int table[2][3] = {{ 0, 0, 0}, {1, 1, 1}};
int table[2][3] = {
{0, 0, 0}, Matrix form
{1, 1, 1}
};
int table[ ][3] = {
{0, 0, 0}, is permitted
{1, 1, 1}
};
If the values are missing in an initializer, they are automatically set to zero.
int table[2][3] = {
{1, 1}, is permitted
{2}
};

MULTI DIMENSIONAL ARRAY:


38
An array of three or more dimension are called multi-dimensional array.
The general form of a multi dimensional array is
Data type array-name[s1][s2]...[sn];
where si is the size of the ith dimension.
Some examples are
float sales[4][5][12];
int table[2][4][5][8];
Where sales is the three dimensional array, contains 240 float type elements.
Initialization of multidimensional arrays:
Like the one dimension arrays, 2 dimension arrays may be initialized by following their
declaration with a list of initial values enclosed in braces
Example:
int table[2][3]={0,0,0,1,1,1};
Initializes the elements of first row to zero and second row to 1. The initialization is done
row by row. The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}}

DYNAMIC ARRAYS:
 The process of allocating memory at compile time is known as static allocation and the
arrays that receive static memory allocation are called static arrays.
 The process of allocate memory to arrays at run-time is known as dynamic memory
allocation.
 The arrays created at run time are called Dynamic arrays.
 The functions used in the dynamic memory management are :
1. malloc()
2. calloc()
3. realloc()
 These functions are included in the header file <stdlib.h>.
 The concept of dynamic arrays is used in creating and manipulating data structures
such as linked lists, stacks and queues.
39
/* Program to add two matrices & store the results in the 3rd matrix */
#include< stdio.h >
#include< conio.h >
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
clrscr();
printf(“enter the order of the matrixn”);
scanf(“%d%d”,&p,&q);
if(m==p && n==q)
{
printf(“matrix can be addedn”);
printf(“enter the elements of the matrix a”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the elements of the matrix b”);
for(i=0;i < p;i++)
for(j=0;j < q;j++)
scanf(“%d”,&b[i][j]);
printf(“the sum of the matrix a and b is”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i < m;i++)
{
for(j=0;j < n;j++)
printf(“%dt”,&a[i][j]);
printf(“n”);
}
}

Program to find the largest and smallest number in arrays

#include<stdio.h>
void main()
{
int a[20];
int i,n,max,min;
print f("enter no of elements:");
scan f("%d",&n);
print f("reading array elements:");
for(i=0;i<n;i++)
{
print f("enter a[%d]elements:");
scan f("%d",&a[i]);
}
print f("array elements:");
for(i=0;i<n;i++)
{
print f("%dt",a[i]);
}
max=a[0];
min=a[0];
for(i=0;i<n;i++)
{
if(max<a[i])
{
max=a[i];
40
}
if(min>a[i])
{
min=a[i];
}
}
print f("n max=%dt min=%d",max,min);
}

How to write a 'C' program to read an array of 10 numbers and print the prime numbers?
#include <stdio.h>
void main ()
{
int arr[10], i, j, flag;

for (i=0;i<10;i++)

scanf ("%d", &arr[i]);

for (i=0;i<10;i++)
{
flag=1;

for (j=2;j<=(arr[i]/2); j++)


{
if (arr[i]%j==0)
{
flag=0;
break;

}
}
}

for (i=0;i<10;i++)
{
if (flag=1)

printf ("%d", arr[i]);


}
}

Multiplication of Two Matrix

#include<stdio.h>
main()
{
int a[10][10] b[10][10] c[10][10]:
int i j k;
printf("enter the elements in A matrix");
for(i 0;i< 5;i++)
41
for(j 0;j<+5;j++)
{
scanf(" d" &a[i][j]); }
printf("enter b matrix");
for(i 0;i< 5;i++)
for(j 0;j<+5;j++)
{
scanf(" d" &b[i][j]);
}
c[0][0] 0;
for(i 0;i< 5;i++)
{ [ this is main logic ]
for(j 0;j< 5;j++)
{
for(k 0;k< 5;k++)
{
c[i][j] c[i][j] c[k][j]+a[i][k]*b[k][j];

}
}
printf("multiplication matrix is");
for(i 0;i< 5;i++)
for(j 0;j< 5;j++)
printf(" d" c[i][j]):
}

UNIT-IV
42
USER DEFINED FUNCTIONS

INTRODUCTION

We have mentioned earlier that one of the strengths of C language is that C functions are
easy to define and use. C functions can be classified into two categories, namely, library
functions and user-defined functions. main is an example of user defined function. printf and
scanf belong to the category of library functions. The main distinction between user-defined and
library function is that the former are not required to be written by user while the latter have to
be developed by the user at the time of writing a program. However the user defined function
can become a part of the C program library.

WHAT IS FUNCTION IN C LANGUAGE?

A function in C language is a block of code that performs a specific task. It has a name
and it is reusable i.e. it can be executed from as many different parts in a C Program as required.
It also optionally returns a value to the calling program

So function in a C program has some properties discussed below.

 Every function has a unique name. This name is used to call function from “main()”
function. A function can be called from within another function.

 A function is independent and it can perform its task without intervention from or
interfering with other parts of the program.

 A function performs a specific task. A task is a distinct job that your program must perform
as a part of its overall operation, such as adding two or more integer, sorting an array into
numerical order, or calculating a cube root etc.

 A function returns a value to the calling program. This is optional and depends upon the
task your function is going to accomplish. Suppose you want to just show few lines
through function then it is not necessary to return a value. But if you are calculating area of
rectangle and wanted to use result somewhere in program then you have to send back
(return) value to the calling function.

NEED FOR USER-DEFINED FUNCTION:


43
Functions are easier to write, debug and understand. Simple function can be
written to do unique specific tasks. Programs containing the functions are also easier to
maintain. Functions are also put in a library and later used by many programs

The use of functions in C serves many advantages:

1. It facilitates top-down modular programming. In this programming style, the high level
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 a appropriate
places.
It is easy to locate and isolate a faulty function for further investigations.
3. A function may be used by many other programs. This means that a C programmer can
build on what others have already done, instead of starting from scratch.

A MULTI-FUNCTION PROGRAM
A function in simple terms can be viewed as a black box which takes in some value (if
required) and outputs some result. The internal details of the function are hidden from rest of the
program. Every C program can be designed using a collection of these black boxes.
Consider an example as follows:

displayname()
{
printf("\nResult of displayname function call");
}
Above function can be used as follows
main()
{
printf("\nThis demonstrates user-defined functions");
displayname();
}

Output of this program is:

This demonstrates user-defined functions


Result of displayname function call
44
First the printf statement in the main program is executed. This is followed by the
call to the user-defined function displayname(), which results in execution of the statements
within the body of the function

ELEMENTS OF USER DEFINED FUNCTIONS

In order to make use of a user-defined function, we need to establish three elements that
are related to functions.

1. Function definition
2. Function call
3. Function declaration

1. FUNCTION DEFINITION

It is an independent program module that is specially written to implement the


requirements of the function. A function definition , also known as function implementation
shall include the following elements.

 Function name
 Function type
 List of parameters
 Local variable declaration
 Function statements and
 a return statement.
All the six elements are grouped into two parts
Function header( first three elements) and
Function body(second three elements)
We begin here, the general format of a function definition is
Function –type function-name(argument list)
{
local variable declarations;
executable statement1;
executable statement2;
----------
45
----------
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.
Function header-> it consists of three parts: function type, the function name and the formal
parameter list
Name and type-> The function name is any valid c identifier. The function type specifies the
type value that the function is expected to return to the program calling the function.
Formal parameter list-> The parameter list declares the variables that will receive the data sent
by the calling program. They serve as input data to the function to carry out the specified task.
The parameters are also known as arguments.
The parameter list separated by commas and surrounded by parentheses. And there is
no semicolon after the closing parentheses. The declaration of parameter variables cannot be
combined. Ex( int a,b) is illegal.
A function need not always receive values from the calling program. In such cases
function have no formal parameters. It is empty, so we can use the keyword void between the
parentheses.
Function body-> The function body contains the declarations and statements. The body
enclosed in braces, contains three parts.
1. Local declarations that specify the variables needed by the function
2. Function statements that perform the task of the function
3. A return statement that return the value evaluated by the function
A function does not return any value we can omit the return statement.

Return Values and Their Types ->A function may or may not send back any value to the
calling function. If it does, it is done through the return statement. While it is possible to pass to
the called function any number of values, the called function can only return one value per call,
at the most we can have

return
or
return(expression)
46
The first, the 'plain' return does not return any value; it acts much as the closing brace of the
function. When a return is encountered, the control is immediately passed back to the calling
function. An example of the use of a simple return is as follows:

if(error)
return;

The second form of return with an expression returns the value of the expression. For example,

mul(x,y)
int x,y;
{
int p;
p = x*y;
return(p);
}

We could have also combined the last two statements as follows:

return(x*y);

Now by default all functions return int type data. If a function wants to return some other type of
value (can be float, character, string, structure, pointer, etc) whether it is user-defined or inbuilt
data type, it can be achieved by giving a type specifier in the function header.

Example:

double sum(w,r)
char rait(c)

When a value is returned it is automatically cast to the function's type. In functions that do
computations using double, yet return int, the returned value will be truncated to an integer.

FUNCTION CALLS-> A function can be called by simply using the function name followed
by a list of actual parameters, if any, enclosed parentheses.
Note:
 If the actual parameters are more than the formal parameters, the extra actual arguments
will be discarded.
 On the other hand, if the actual are less than the formals, the unmatched formal
arguments will be initialized to some garbage.
47
 Any mismatch in data types may also result in some garbage values.
FUNCTION DECLARATION-> All functions in c program must be declared, before they are
invoked. A function declaration consists of four parts
Function type(return type)
Function name
Parameter list
Terminating semicolon
Its general form is
Function type function name(parameter list);

Note:
 The parameter list must be separated by commas
 The parameter names do not need to be the same in the prototype declaration and the
function definition
 The types must match the types of parameters in the function definition, in number and
order
 Use of parameter names in the declaration is optional
 If the function has no formal parameters, the list is written as(void)
 When the declared types do not match with the types in the function definition, compiler
will produce an error.
TYPES OF FUNCTIONS
A function may belong to any one of the following categories:

1. Functions with no arguments and no return values.


2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions that return multiple values.
5. Functions with no arguments and return values.

Example of a simple function to add two integers

1. #include<stdio.h>
2. #include<conio.h>
3. void add(int x,int y)
4. {
5. int result;
6. result = x+y;
7. printf("Sum of %d and %d is %d.\n\n",x,y,result);
8. }
48
9. void main()
10. {
11. clrscr();
12. add(10,15);
13. add(55,64);
14. add(168,325);
15. getch();
16. }

Program Output

1. Functions with no arguments and no return value.


49
A C function without any arguments means you cannot pass data (values like int, char etc) to the
called function. Similarly, function with no return type does not pass back data to the calling
function. It is one of the simplest types of function in C. This type of function which does not
return any value cannot be used in an expression it can be used only as independent statement.
Let’s have an example to illustrate this.

1. #include<stdio.h>
2. #include<conio.h>
3. void printline()
4. {
5. int i;
6. printf("\n");
7. for(i=0;i<30;i++)
8. {
9. printf("-");
10. }
11. printf("\n");
12. }
13. void main()
14. {
15. clrscr();
16. printf("Welcome to function in C");
17. printline();
18. printf("Function easy to learn.");
19. printline();
20. getch();
21. }

See all 9 photos


50
Logic of the functions with no arguments and no return value.

Output

2. Functions with arguments and no return value.

A C function with arguments can perform much better than previous function type. This type of
function can accept data from calling function. In other words, you send data to the called
function from calling function but you cannot send result data back to the calling function.
Rather, it displays the result on the terminal. But we can control the output of function by
providing various values as arguments. Let’s have an example to get it better.

#include<stdio.h>
#include<conio.h>
void add(int x, int y)
{
int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}
void main()
{
clrscr();
add(30,15);
add(63,49);
add(952,321);
getch();
}
51

Logic of the function with arguments and no return value.

Output

3.Functions with arguments and return value.

This type of function can send arguments (data) from the calling function to the called
function and wait for the result to be returned back from the called function back to the calling
function. And this type of function is mostly used in programming world because it can do two
way communications; it can accept data as arguments as well as can send back data as return
value. The data returned by the function can be used later in our program for further
calculations.
#include<stdio.h>
#include<conio.h>
52
int add(int x, int y)
{
int result;
result = x+y;
return(result);
}
void main()
{
int z;
clrscr();
z = add(952,321);
printf("Result %d.\n\n",add(30,55));
printf("Result %d.\n\n",z);
getch();
}

Logic of the function with arguments and return value.

4. Functions with no arguments but returns value.

We may need a function which does not take any argument but only returns values to the
calling function then this type of function is useful. The best example of this type of function is
“getchar()” library function which is declared in the header file “stdio.h”. We can declare a
similar library function of own. Take a look.

1. #include<stdio.h>
2. #include<conio.h>
3. int send()
4. {
53
5. int no1;
6. printf("Enter a no : ");
7. scanf("%d",&no1);
8. return(no1);
9. }
10. void main()
11. {
12. int z;
13. clrscr();
14. z = send();
15. printf("\nYou entered : %d.", z);
16. getch();
17. }

Functions with no arguments and return values.

5. Functions that return multiple values.

We have used arguments to send values to the called function, in the same way we can
also use arguments to send back information to the calling function. The arguments that are used
to send back data are called Output Parameters. It is a bit difficult for novice because this type
of function uses pointer. Let’s see an example:

1. #include<stdio.h>
2. #include<conio.h>
3. void calc(int x, int y, int *add, int *sub)
4. {
5. *add = x+y;
54
6. *sub = x-y;
7. }
8. void main()
9. {
10. int a=20, b=11, p,q;
11. clrscr();
12. calc(a,b,&p,&q);
13. printf("Sum = %d, Sub = %d",p,q);
14. getch();
15. }

We have used arguments to send values to the called function, in the same way we can
also use arguments to send back information to the calling function. The arguments that are used
to send back data are called Output Parameters.It is a bit difficult for novice because this type of
function uses pointer. Let’s see an example:

1. #include<stdio.h>
2. #include<conio.h>
3. void calc(int x, int y, int *add, int *sub)
4. {
5. *add = x+y;
6. *sub = x-y;
7. }
8. void main()
9. {
10. int a=20, b=11, p,q;
11. clrscr();
12. calc(a,b,&p,&q);
13. printf("Sum = %d, Sub = %d",p,q);
14. getch();
15. }
55

NESTING OF FUNCTIONS

C permits nesting of functions freely. Main can call function1, which calls functions2,
which calls function3 etc…. and so on. Consider the following program.
Void main()
{
void add();
add()
}
void add ()
{
printf(“ PROGRAMMING”);
add1();
}
void add1()
{
printf(“LANGUAGE”);
}

RECURSION

When a called functions in turn calls another function a process of “ chaining “


occurs. Recursion is a special case of this process , where a function calls itself .
Eg:
Main()
{
printf(“ this is the example for recursion”);
main();
}
56

UNIT V

POINTERS
INTRODUCTION

In c a pointer is a variable that points to or references a memory location in which data is stored.
Each memory cell in the computer has an address that can be used to access that location so a
pointer variable points to a memory location we can access and change the contents of this
memory location via the pointer. It is a derived data type.

Benefits of pointers:

 Pointers are more efficient in handling arrays and data tables.


 Pointers can be used to return multiple values from a function via function arguments.
 Pointers permit references to functions and thereby facilitating passing of function as
arguments to other functions.
 The use of pointer arrays to character strings results in saving of data storage space in
memory
 Pointers allow c to support dynamic memory management.
 Pointers provided an efficient tool for manipulating dynamic data structures such as
structures, linked lists, queues, stacks and trees.
 They increase the execution speed and thus reduce the program execution time.

UNDERSTANDING POINTERS
57
Definition: A pointer is a variable; it may contain the memory address of another variable.
Pointer can have any name that is legal for other variable. It is declared in the same manner like
other variables. It always denoted by *
A pointer is a variable whose value is also an address. Each variable has two attributes:
address and value. A variable can take any value specified by its data type. A pointer to an
integer is a variable that can store the address of that integer.
Assigning values directly to variables, we can indirectly manipulate a variable by
creating a variable called a pointer, which contain the memory address of another variable.
Value at address  30 4567-> address of the variable

First variable second variables

The second variable contains the address of the first variable. 30 is the value at the address,
4567 is the address of the first variable.
ACCESSING THE ADDRESS OF A VARIABLE

The actual location of a variable in the memory is system dependent and therefore, the
address of a variable is not known to us. It can be done with the help of & operator. The
operator & immediately preceding a variable returns the address of the variable associated with
it.
For ex:
S=&quality;
This would assign the address 5000(the location of quality) to the variable s. The & operator can
be named as ‘address of’.
Note: the & operator can be used only with a simple variable or an array element.

Declaring pointer variables

For defining a pointer variable ‘*’ symbol is used. A pointer variable must be declared
with * preceding the variable name. The general structure for declaring a pointer variable is
data_type*ptr_name;

For example
int*p
This declares the variable p as a pointer variable that points to an integer data type.

For example:
58
main()
{
int*p;
int i=30;
p=&i;
}

p 30

INITIALIZATION OF POINTER VARIABLES

The process of assigning the address of a variable to a pointer variable is known as


initialization. Once the pointer variable has been declared we can use the assignment operator to
initialize the variable.
Example:
int quality;
int *p /* declaration */
p=&quality; /* Initialization */
We can also combine the initialization with the declaration
Example:
Int *p=&quality;
We could also define a pointer variable with an initial value of NULL or 0(zero)
Example:
int *p=NULL;
int *p=0;
Pointers are flexible. We can make the same pointer to point to different data variables in
different statements. Example
int x,y,z,*p; x y z
-----
P=&x;
-------
P=&y;
----------
P=&z;
--------- p

We can also use different pointers to point to the same data variable. Example

int x P1 P2 P3
int *p1=&x;
int *p2=&y;
int *p3=&z;
x
59
----
-------

Accessing variable though its pointers

Once the pointer is declared and assigned to the address of another variable. The variable
can be accessed through its pointers. This is done by using another unary operator * (asterisk),
usually known as the indirection operator. Another name for the indirection operator is the
dereferencing operator.
Example:
int *p;
x=15;
p=&x;

Variable Value Address


X 15 2001
P 2001 2005

Program to accessing through variable pointer

#include<stdio.h>
main()
{
/* local definition */
int a=22, *a;
float b=2.25, *b;
/* statements */
a=&a; /* ‘&’ is a address of letter and it represents the address of the variable */
b=&b;
printf(“\n Value of a =%d”,*a);
printf(“\n value of b=%d”,*b);

}
Output
Value of a=22
Value of b=2.25

CHAIN OF POINTERS

Any pointer variable points to another pointer variable to access the content of other
memory location of variable is called chain of pointers.

Address2 Address1 Value


P2 p1 Variable
60
Ptr -> Ptr -> memory

Here, the pointer variable p2 contains the address of the pointer variable p1, which points to the
location that contains the desired value. This is known as multiple directions
For example:
Main()
{
int x, *p1,**p2;
X=100;
P1=&x; /* address of x*/
P2=&p1; /* address of p1 */
Printf(“%d”,**p2);
}
This code will display the value 100. Here p1 is declared as a pointer to an integer and p2 as a
pointer to a pointer to an integer.

POINTER EXPRESSIONS & POINTER ARITHMETIC

Like other variables pointer variables can be used in expressions. For example if p1 and
p2 are properly declared and initialized pointers, then the following statements are valid.

y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;

C allows us to add integers to or subtract integers from pointers as well as to subtract one
pointer from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2;
etc.,
we can also compare pointers by using relational operators the expressions such as p1 >p2 ,
p1==p2 and p1!=p2 are allowed.
/*Program to illustrate the pointer expression and pointer arithmetic*/
#include< stdio.h >
main()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
61
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a +%u”,ptr1);
printf(“\nAddress of b %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(“\na=%d, b=%d”,a,b);
}

POINTER TO ARRAYS

When an array is declared, the compile allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations. The base
address is the location of the first element (index 0) of the array. The compiler also defines the
array name as a constant pointer to the first element. Suppose we declare an array x as follows
int x[5]=1,2,3,4,5}
Suppose the base address of x is 1000 and assuming that each integer requires two bytes,
the five elements will be stored as

Element x[0] x[1] x[2] x[3] x[4]


value 1 2 3 4 5
address 1000 1002 1004 1006 1008

The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the
value of x is 1000, the location where x[0] is stored. That is x=&x[0]=1000

If we declare p as an integer pointer, then we can make the pointer p to point to the array x by
the following assignment: p=x; This will be equivalent to p=&x[0];

POINTERS AND CHARACTER STRINGS

Strings are treated like character arrays and therefore, they are declared and initialized as
follows:

Char str[5]=”good”;
62
The compiler automatically inserts the null character’\0’ at the end of the strings. C
supports an alternative method to create strings pointer variables of type char.

Ex: char *str=”good”;

This creates a string for the literal and then stores its address in the pointer variable str.

The pointer str now points to the first character of the string “good” as shown in fig.

g o o d \0 str

ARRAY OF POINTERS

The array notation can be accessed by two methods

 Standard array notation

 Pointer arithmetic

Array notation is form of relative addressing. The compiler treats the subscripts as a relative
offset from the beginning of the array. When a pointer variable set to the start of an array and is
incremented to find the next element, absolute addressing is being implemented.

It has the following advantages:

Accessing arrays through pointers is marginally faster than using array notation.

Pointers give better control over array processing

Pointer allows us to perform certain functions that are externally difficult with array notation.

Program:

#include<stdio.h>
main()
{
int *a[3];
int b=10,c=20,d=30,i;
a[0] =&b;
a[1] =&c;
a[2] =&d;
63
for(i=0;i<3;i++)
{
Printf(“address=%u”,a[i]);
Printf(“value=%d”,*(a[i]));
}
}
b c d
10 20 30
a[0] a[1] a[2]
400 500 600
0 0 0

Output
Address=4000 value=10
Address=5000 value=20
Address=6000 value=30
POINTERS AS FUNCTION ARGUMENTS

When we pass addresses to function, the parameters receiving the addresses should be
pointers. The process of calling a function using pointers to pass the addresses of variable is
known as call by reference. (You know, the process of passing the actual value of variables is
known as call by value.) The function which is called by ‘reference’ can change the value of
the variable used in the call. Consider the following code:

Main()
{
int x;
x = 20;
change(&x);
printf(“%d \n”,x);
}
change(p);
int *p;
{
*p = *p + 10;
}

The statement *p=*p+10 to the value stored at the address p. Since p represents the address of x,
the value of x is changed from 20 to 30. Therefore, the output of the program will be 30, not 20.

FUNCTIONS RETURNING POINTERS


64
A function can return a single value by its name or return multiple values through pointer
parameters to the calling function.

int *larger(int *, int *); /* prototype */


main()
{
int a=10;
int b=20;
int *p;
p=larger(&a,&b); /* function call */
printf(“%d”, *p);
}
int *larger(int *x, int *y)
{
if(*x>*y)
return(x); /* address of a */
Else
return(y) /* address of b*/
}

The function large receives the address of the variables a and b, decides which one is
lager using the pointers x and y and then returns the address f its location. The returned value is
then assigned to the pointer variable p in the calling function. In this case, the address of b is
returned and assigned p and therefore the output will be the value of b, namely 20.

POINTERS TO FUNCTIONS

A function has a type and an address location in the memory. It is therefore possible to
declare a pointer to a function , which can be used as an argument in another function.
A pointer to a function is described as follows.
Type (* fptr) ();

This tells the compiler that fptr is a pointer to a function, which returns type value. The
parentheses around *fptr are necessary.
We can make a function pointer to point to a specific function b simply assigning the name of
the function to the pointer.
For example
double mul (int, int);
65
double (*p1) ();
p1=mul;

Here p1 as a pointer to a function and mul is a function to which p1 points. To call the
function mul, we may now use the pointer p1 with the list of parameters, i.e.,
(*p1) (x,y) /* function call*/

The above function call is equivalent to mul(x,y)

POINTERS AND STRUCTURES

We know the name of an array stands for the address of its zeroth element the same
concept applies for names of arrays of structures. Suppose item is an array variable of struct
type. Consider the following declaration:
struct products
{
char name[30];
int manufac;
float net;

}
item[2],*ptr;

this statement declares item as array of two elements, each type struct products and ptr as a
pointer data objects of type struct products, the following assignment statement is

ptr=item;

would assign the address of zeroth element of product to ptr. The pointer ptr will now point to
item[0]. Its members can be accessed by using the following notation.

ptr- >name;
ptr- >manufac;
ptr- >net;

The symbol - > is called arrow pointer and is made up of minus sign and a greater than
sign. Note that ptr- > is simple another way of writing product[0].

When the pointer is incremented by one it is made to pint to next record ie item[1]. The
following statement will print the values of members of all the elements of the product array.
66
for(ptr=item; ptr< item+2;ptr++)
printf(“%s%d%f\n”,ptr- >name,ptr- >manufac,ptr- >net);

We could also use the notation (*ptr).number to access the number. The parenthesis around
*ptr are necessary because the member operator ‘.’ has a higher precedence than the operator *.

You might also like