0% found this document useful (0 votes)
19 views

C Complete Notes1

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

C Complete Notes1

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

******************************************************************************

ERODE ARTS AND SCIENCE COLLEGE (AUTONOMOUS)


ERODE – 638009
Department Of Computer Applications
I – B.Sc (CS) –Programming in C
Unit – I [Students Notes]

*****************************************************************************

UNIT – I

Introduction to Computers: Types of Computers- Characteristics of Computers-


Classification of Digital Computers.
Operating System: Introduction – Functions of OS-Classification of OS.
Programming Languages: Machine language – Assembly Language – High level
Language – Types of High level language.
Introduction to C: Basic structures of C program – Character set- C tokens-
Keywords –Identifier- Constants – Variables – Data types-Declaration and
Initialization of variables.

TYPES OF COMPUTERS

Computers are divided into three types:

1
Microcomputers (Personal Computer)

• A microcomputer is the smallest general


purpose processing system.
• They are designed to be used by one person
at a time.
• Ram 64MB, 128MB, 512MB, 1GB. Its CPU is microprocessor has separate
components (keyboard, mouse, etc.)
• Examples: - IBM PCs, APPLE computers Microcomputer can be classified
• Desktops
• Portables
• Hand-helds

• Data Storage
Hard disk & Floppy disk drivers are used
to enter and store data and programs

• Softcopy Output
–A visual display screen (monitor) and / or
a printer is used to get the output

The different portable computers are: -


1) Laptop 2) Notebooks 3) Palmtop (hand held) 4) Wearable
computers
Laptop: - this computer is similar to a desktop computers
but the size is smaller. They are expensive than desktop. The
weight of laptop is around 3 to 5 kg.

Notebook: - These computers are as powerful as desktop


but size of these computers are comparatively smaller than
laptop and desktop. They weigh 2 to 3 kg. They are more
2
costly than laptop.

Palmtop (Hand held): - They are also called as personal


Digital Assistant (PDA). These computers are small in size.
They can be held in hands. It is capable of doing word
processing, spreadsheets and hand writing recognition,
GAME playing, faxing and paging. These computers are not
as powerful as desktop computers

Wearable computer: - The size of this computer is very


small so that it can be worn on the body. It has smaller
processing power. It is used in the field of medicine. For
example pace maker to correct the heart beats

PDAs
Personal Digital Assistants
Generally used to maintain an electronic appointment book,
address book, calculator, and notepad

Mainframe
• Mainframe computers can support hundreds or thousands
of users, handling massive amounts of input, output, and
storage.
• Mainframe computers are used in large organizations
where many users need access to shared data and programs.
• Mainframes are also used as e-commerce servers, handling
transactions over the Internet.

Super computer are those computer which are designed for


scientific job like whether forecasting and artificial
intelligence etc. They are fastest and expensive. A super
computer contains a number of CPU which operate in
parallel to make it faster. It also known as grand father
computer.
•Application – weather forecasting, weapons research and development.
3
Mini Computers

This setup (mini Computers) allowed more people


to have access to computers.
•minicomputer is a class of multi-user Computer
that lies between the largest Multi-user systems
(mainframe computer) and the smallest
Microcomputers or personal computers.
–Mainframe computers are used to run
commercial applications and other large-scale computing purposes.
–It is also used in banking and insurance businesses.
–For example millions of records , each day.

Workstation
•Personal computer=Workstation
•Workstations are more powerful and higher in
performance than desktop computers, especially with
respect to CPU and Graphics, memory capacity and
multitasking capability.
•Its Powerful desktop computer designed for
specialized tasks.
•Lot of processing speed.
•Can also be an ordinary personal computer attached to a LAN (local area network).

CHARACTERISTICS OF COMPUTERS

Speed
• A computer is very fast device.
• It can perform large amount of work in a few seconds.
• Where human being worked a particular work for whole day, computer
does the same in very short time.
• Today, computers can perform 100 million computations in one second.
• The speed of computers are measured in terms of microseconds,
• Nano seconds and even in Pico seconds.
Where 1 second =10-6micro second
=10-9nano second
=10-12Pico second
4
Accuracy
• The computer is 100% accurate.
• Capable to perform arithmetical calculation and logic operations with the
same accuracy.
• It can never make mistakes.
Diligence
• A computer can operate twenty four hours continuously without taking any
rest.
• It has no feelings or no emotions, if you work continuously for 3 hours.

High Memory
• Computer has made more memory or storage capacity than human beings.
• It can store millions of data and instructions, which can be retrieved and
recalled even after a number of years.
• This is not possible in case of human brain

CLASSIFICATION OF DIGITAL COMPUTERS

• Computer for simple use


• Computers for Organizational Use
Personal Computers (Simple use)
Laptops, PDA (Personal Digital Assistant), Workstations.
Organizational Use
Servers, Mainframes, mini computers and Super computers
(Already this Topic covered. You see these types of computer.)

5
OPERATING SYSTEM

Introduction

Operating System, or OS, is low-level


software that enables a user and higher-level
application software to interact with a
computer’s hardware and the data and other
programs stored on the computer

Functions of OS

• Provide a user interface


• Run programs
• Manage hardware devices
• Organized file storage

Classification of OS

• Microsoft Windows

• Mainframe

• DOS

• OS/2

• Linux

• Mac OS

• AmigaOS

6
PROGRAMMING LANGUAGES
Machine language
There are three types of programming language:
▪ Machine language(Low-level language)
▪ Assembly language(Low-level language)
▪ High-level language

Machine Language
▪ Machine language is a collection of binary digits orbits that the computer read
sand interprets.
▪ Machine languages are the only languages understood by computers.
▪ While easily understood by computers, machine languages are
almost impossible for humans to use because they consist entirely of numbers

Machine Language
169 1 160 0 153 0 128 153 0 129 153 130 153 0 131 200 208 241 96
High level language
5 FOR I=1 TO 1000: PRINT "A";: NEXT I

Assembly Language
▪ Consists of a series of instructions mnemonics that correspond to a
stream of executable instructions, when translated by an assembler that
can be loaded into memory and executed.
▪ Assembly languages use keywords and symbols, much like English, to
form a programming language but at the same time introduce a new
problem.
Machine language
10110000 01100001
Assembly language :
mov a1, #061h

7
Meaning:
Move the hexadecimal value 61 (97 decimal) into the processor register named
"a1".

High Level Language

▪ High-level languages allow us to write computer code using instructions


resembling everyday spoken language (for example: print, if, while) which are
then translated into machine language to be executed.
▪ Programs written in a high-level language need to be translated into machine
language before they can be executed.
▪ Some programming languages use a compiler to perform this translation and
others use an interpreter.

High-Level Language Types:


▪ ADA
▪ C
▪ C++
▪ JAVA
▪ BASIC
▪ COBOL
▪ PASCAL
▪ PHYTON

INTRODUCTION TO PROGRAMMING LANGUAGE – C

• C is a general-purpose, high-level language that was originally developed by


Dennis M. Ritchie to develop the UNIX operating system at Bell Labs.
• C was originally first implemented on the DEC PDP-11 computer in 1972.
• C has now become a widely used professional language for various reasons:
▪ Easy to learn
▪ Structured language
▪ It produces efficient programs
▪ It can handle low-level activities
▪ It can be compiled on a variety of computer platforms

8
Basic structures of C program

1) Documentation Section:
Consists of a set of command lines giving the name of program.
2) Link Section:
Provides Instruction to compiler to link functions from the system library.
3) Definition Section:
Define Symbolic constants.
4) Global Declaration Section:
Declare the variable that is outside of all the functions.
5) Main () Function:
Every C program must have one main () function section. These section two
Parts, declaration part and executable part.
❖ Declaration Part: declare all the variables inside of main function.
❖ Executable Part: declare the variables outside of main function
❖ The program execution begins at the opening brace and end at the closing
brace. { }
❖ All statement in the declaration and executable parts end with a semicolon(;).

9
Character set

C Tokens

10
11
12
VARAIABLES

13
14
15
UNIT II
MANAGING INPUT OUTPUT OPERATION
As we all know the three essential functions of a computer are reading, processing and
writing data.

Majority of the programs take data as input, and then after processing the processed data
is being displayed which is called information.

In C programming you can use scanf() and printf() predefined function to read and print
data.

#include<stdio.h>

void main()

int a,b,c;

printf("Please enter any two numbers: \n");

scanf("%d %d", &a, &b);

c = a + b;

printf("The addition of two number is: %d", c);

Output:

Please enter any two numbers:12 3

The addition of two number is:15

In this above program scanf() is used to take input from the user, and respectively printf() is
used to display output result on the screen.

16
MANAGING INPUT/OUTPUT
I/O operations are useful for a program to interact with users. stdlib is the standard C
library for input-output operations.

While dealing with input-output operations in C, two important streams play their role.
These are:

1. Standard Input (stdin)

2. Standard Output (stdout)

Standard input or stdin is used for taking input from devices such as the keyboard as a data
stream.

Standard output or stdout is used for giving output to a device such as a monitor. For using I/O
functionality, programmers must include stdio header-file within the program.

The easiest and simplest of all I/O operations are taking a character as input by reading that character
from standard input (keyboard).

getchar() function can be used to read a single character.

This function is alternate to scanf() function.

Syntax:

var_name = getchar();

Example:

#include<stdio.h>

void main()

char title;

title = getchar();

17
There is another function to do that task for files: getc which is used to accept a character from standard
input.

Syntax:

int getc(FILE *stream);

Writing Character In C

Similar to getchar() there is another function which is used to write characters, but one at a time.

Syntax:

putchar(var_name);

Example:

#include<stdio.h>

void main()

char result = 'P';

putchar(result);

putchar('\n');

Similarly, there is another function putc which is used for sending a single character to the standard
output.

Syntax:

int putc(int c, FILE *stream);

18
Formatted Input

It refers to an input data which has been arranged in a specific format. This is possible in C using scanf().
We have already encountered this and familiar with this function.

Syntax:

scanf("control string", arg1, arg2, ..., argn);

The field specification for reading integer inputted number is:

%w sd

Here the % sign denotes the conversion specification; w signifies the integer number that defines the
field width of the number to be read. d defines the number to be read in integer format.

Example:

#include<stdio.h>

void main()

int var1= 60;

int var2= 1234;

scanf("%2d %5d", &var1, &var2);

Input data items should have to be separated by spaces, tabs or new-line and the punctuation
marks are not counted as separators.

Reading and Writing Strings in C

19
There are two popular library functions gets() and puts() provides to deal with strings in C.

gets: The char *gets(char *str) reads a line from stdin and keeps the string pointed to by the str and
is terminated when the new line is read or EOF is reached.

The declaration of gets() function is:

Syntax:

char *gets(char *str);

Where str is a pointer to an array of characters where C strings are stored.

puts: The function - int puts(const char *str) is used to write a string to stdout, but it does not
include null characters. A new line character needs to be appended to the output. The declaration is:

Syntax:

int puts(const char *str)

C FORMAT SPECIFIERS
Format specifiers can be defined as the operators which are used in association with
printf() function for printing the data that is referred by any object or any variable.

When a value is stored in a particular variable, then you cannot print the value stored in
the variable straightforwardly without using the format specifiers.

You can retrieve the data that are stored in the variables and can print them onto the
console screen by implementing these format specifiers in a printf() function.

Format specifiers start with a percentage % operator and followed by a special character
for identifying the type of data.

There are mostly six types of format specifiers that are available in C.

20
Format Specifier Description

%d Integer Format Specifier

%f Float Format Specifier

%c Character Format Specifier

%s String Format Specifier

%u Unsigned Integer Format Specifier

%ld Long Int Format Specifier

Integer Format Specifier %d

The %d format specifier is implemented for representing integer values. This is used with
printf() function for printing the integer value stored in the variable.

Syntax:

printf("%d",<variable name>);

Float Format Specifier %f

The %f format specifier is implemented for representing fractional values. This is


implemented within printf() function for printing the fractional or floating value stored in the
variable.

Whenever you need to print any fractional or floating data, you have to use %f format
specifier.

Syntax:

printf("%f", <variable name>);

21
Charter Format Specifier %c

The %c format specifier is implemented for representing characters. This is used with
printf() function for printing the character stored in a variable.

When you want to print a character data, you should incorporate the %c format specifier.

Syntax:

printf("%c",<variable name>);

String Format Specifier %s

The %s format specifier is implemented for representing strings. This is used in printf()
function for printing a string stored in the character array variable.

When you have to print a string, you should implement the %s format specifier.

Syntax:

printf("%s",<variable name>);

Unsigned Integer Format Specifier %u

The %u format specifier is implemented for fetching values from the address of a
variable having unsigned decimal integer stored in the memory.

This is used within printf() function for printing the unsigned integer variable.

Syntax:

printf("%u",<variable name>);

Long Int Format Specifier %ld

The %ld format specifier is implemented for representing long integer values. This is
implemented with printf() function for printing the long integer value stored in the variable.

Syntax:

22
printf("%ld",<variable name>);

C OPERATORS AND EXPRESSIONS:

C operators are symbols that are used to perform mathematical or logical manipulations.
The C programming language is rich with built-in operators.
Operators take part in a program for manipulating data and variables and form a part of
the mathematical or logical expressions.
C programming language offers various types of operators having different functioning
capabilities.

TYPES OF OPERATOR IN C

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

5. Increment and Decrement Operators

6. Conditional Operator

7. Bitwise Operators

8. Special Operators

1. ARITHMETIC OPERATORS

Arithmetic Operators are used to performing mathematical calculations like addition (+),
subtraction (-), multiplication (*), division (/) and modulus (%).

Operator Description

+ Addition

- Subtraction

23
* Multiplication

/ Division

% Modulus

C Program to Add Two Numbers


Example:

#include <stdio.h>

void main()

int i=3,j=7,k; /* Variables Defining and Assign values */ k=i+j;

printf("sum of two numbers is %d\n", k);

Program Output:

1. INCREMENT AND DECREMENT OPERATORS

Increment and Decrement Operators are useful operators generally used to minimize the
calculation, i.e. ++x and x++ means x=x+1 or -x and x−−means x=x-1. But there is a slight
difference between ++ or −− written before or after the operand. Applying the pre-increment first
add one to the operand and then the result is assigned to the variable on the left whereas post-
increment first assigns the value to the variable on the left and then increment the operand.

24
Operator Description

++ Increment

−− Decrement

Example: To Demonstrate prefix and postfix modes.

#include <stdio.h>

//stdio.h is a header file used for input.output purpose.

void main()

//set a and b both equal to 5.

int a=5, b=5;

//Print them and decrementing each time.

//Use postfix mode for a and prefix mode for b.

printf("\n%d %d",a--,--b);

printf("\n%d %d",a--,--b);

printf("\n%d %d",a--,--b);

printf("\n%d %d",a--,--b);

printf("\n%d %d",a--,--b);

Program Output:

25
54

43

32

21

10

2. RELATIONAL OPERATORS

Relational operators are used to comparing two quantities or values.

Operator Description

== Is equal to

!= Is not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

3. LOGICAL OPERATORS
C provides three logical operators when we test more than one condition to make
decisions. These are: && (meaning logical AND), || (meaning logical OR) and ! (meaning
logical NOT).

Operator Description

26
&& And operator. It performs logical conjunction of two
expressions. (if both expressions evaluate to True, result is
True. If either expression evaluates to False, the result is False)

|| Or operator. It performs a logical disjunction on two


expressions. (if either or both expressions evaluate to True,
the result is True)

! Not operator. It performs logical negation on an expression.

4. BITWISE OPERATORS
C provides a special operator for bit operation between two variables.

Operator Description

<< Binary Left Shift Operator

>> Binary Right Shift Operator

~ Binary Ones Complement Operator

& Binary AND Operator

^ Binary XOR Operator

| Binary OR Operator

5. ASSIGNMENT OPERATORS
Assignment operators applied to assign the result of an expression to a variable. C has a
collection of shorthand assignment operators.

Operator Description

27
= Assign

+= Increments then assign

-= Decrements then assign

*= Multiplies then assign

/= Divides then assign

%= Modulus then assign

<<= Left shift and assign

>>= Right shift and assign

&= Bitwise AND assign

^= Bitwise exclusive OR and assign

|= Bitwise inclusive OR and assign

6. CONDITIONAL OPERATOR
C offers a ternary operator which is the conditional operator (?: in combination) to construct
conditional expressions.

Operator Description

?: Conditional Expression

7. SPECIAL OPERATORS

28
C supports some special operators

Operator Description

sizeof() Returns the size of a memory location.

& Returns the address of a memory location.

* Pointer to a variable.

Program to demonstrate the use of sizeof operator


Example:

#include <stdio.h>

void main()

int i=10; /* Variables Defining and Assign values */ printf("integer: %d\n", sizeof(i));

Program Output:

ARITHMATIC EXPRESSIONS

An arithmetic expression contains only arithmetic operators and operands. We know that
the arithmetic operators in C language include unary operators (+ - ++ -- ), multiplicative
operators (* / %) and additive operators (+ - ).

29
The arithmetic operands include integral operands (various int and char types) and
floating-type operands (float, double and long double).

Example Simple arithmetic expressions

a) Several valid arithmetic expressions are given below. Assume that variables a and b are of
type int.

Observe that the operators are used correctly. The unary operators in expressions -1.23,
a++ and -a + b /5 correctly operate on a single operand.

The unary minus (-) is used as a prefix operator whereas the increment operator (++) is
used in the postfix form.

All other operators (multiplicative and additive) are used as infix operators and they
operate on two operands. Also, the modulo-arithmetic(s) operator operates on integer operands
as required.

The expression 'A' + 2 is valid and its value is equal to 67, as the ASCII value of
character 'A' is 65. Note that the operands and operators need not be separated by spaces.

For example, the last two expressions in the first row can also be written as -a+b/5 and 3
.142*a*b. However, the spaces are often used to improve readability.

b) The expressions given below are invalid

Evaluation of Simple Arithmetic Expressions

We use the operator precedence and associativity rules to determine the meaning and
value of an expression in an unambiguous manner.

30
Recall that the operators in an expression are bound to their operands in the order of their
precedence. If the expression contains more than one operator at the same precedence level, they
are associated with their operands using the associativity rules.

Table summarizes these rules for arithmetic and assignment operators.

If the given expression is simple, we can often directly convert it to its mathematical form
and evaluate it. However, if the given expression is complex, i. e., it contains several operators at
different precedence levels, we need a systematic approach to convert it to a mathematical
equation and evaluate it.

The steps to convert a given valid C expression to its mathematical form (if possible) and
to evaluate it are as follows:

1. First determine the order in which the operators are bound to their operands by applying the
precedence and associativity rules. Note that after an operator is bound to its operand(s), that
sub-expression is considered as a single operand for the adjacent operators.

2. Obtain the equivalent mathematical equation for given C expression (if possible) by following
the operator binding sequence (obtained in step 1).

3. Determine the value of the given expression by evaluating operators in the binding sequence.

The steps to determine operator binding in an arithmetic expression are explained below
with the help of the expression -a+ b * c - d I e + f.

1. The unary operators (unary +, unary - , ++ and - -) have the highest precedence and right-to-
left associativity. Thus, the given expression is first scanned from right to left and unary
operators, if any, are bound to their operands. The order is indicated below the expression as
follows:

2. The multiplicative operators (*, I and %) have the next highest precedence and left to- right
associativity. Thus, the expression is scanned from left-to-right and the multiplicative operators,
if any, are bound to their operands as shown below. (Observe that after completion of the above
step, sub-expressions -a, b * c and d I e will be operands for the remaining operator bindings.)

3. The additive operators (+ and -) have the next highest precedence and left-to-right
associativity. Hence, the expression is scanned from left-to-tight and the additive operators, if
any, are bound to their operands as shown below. Observe that the operands for the first +

31
operator are the sub-expressions -a and b * c. Similarly, the operands for the - operator are -a+ b
* c and d /e.

Now we can write the mathematical equation for the given C expression by following the
operator binding sequence as shown below:

Now the given expression can be evaluated, again by following the operator binding sequence, as
shown below. Assume that the variables a, b, c, ct, e and f are of type float and are initialized
with values as a= 1. 5, b = 2. 0, c = 3. 5, ct= 5.0, e = 2. 5 and f = 1. 25.

Remember that except for some operators (& & || ? : and the comma operator), the C
language does not specify the order of evaluation of sub-expressions. Thus, the sub expressions

32
at the same level can be evaluated in any order. For example, the sub expressions -a, b * c and
ct I e in the above expression can be evaluated in any order.

The procedure explained above can also be used to check the validity of an expression.
The given expression is valid if we arrive at a single operand (or value) after all the operators in
the given expression are considered.

Consider a more complex arithmetic expression: -a--+ -b++ * --c. This expression
appears to be invalid due to the excessive use of operators. It contains three operands a, b and c
and seven operators, five of which are unary (-, ++ and --) and the other two are binary operators
(+ and *). However, using the operator binding steps, we can easily verify that it is a valid
expression:

C DECISION MAKING AND BRANCHING

C conditional statements allow you to make a decision, based upon the result of a
condition. These statements are called Decision Making Statements or Conditional
Statements.

So far, we have seen that all set of statements in a C program gets executed sequentially
in the order in which they are written and appear.

This occurs when there is no jump based statements or repetitions of certain calculations.
But some situations may arise where we may have to change the order of execution of statements
depending on some specific conditions.

33
This involves a kind of decision making from a set of calculations. It is to be noted that C
language assumes any non-zero or non-null value as true and if zero or null, treated as false.

This type of structure requires that the programmers indicate several conditions for
evaluation within a program.

The statement(s) will get executed only if the condition becomes true and optionally,
alternative statement or set of statements will get executed if the condition becomes false.

The flowchart of the Decision-making technique in C can be expressed as:

C languages have such decision-making capabilities within its program by the use of following
the decision making statements:

Conditional Statements in C

• If statement

o if statement

o if-else statement

o Nested if-else statement

o else if-statement

• goto statement

• switch statement

• Conditional Operator

34
IF STATEMENT

If statements in C is used to control the program flow based on some condition, it's used
to execute some statement code block if the expression is evaluated to true.

Otherwise, it will get skipped. This is the simplest way to modify the control flow of the
program.

There are four different types of if statement in C. These are:

• Simple if Statement

• if-else Statement

• Nested if-else Statement

• else-if Ladder

The basic format of if statement is:

Syntax:

if(test_expression)

statement 1;

statement 2;

...

'Statement n' can be a statement or a set of statements, and if the test expression is
evaluated to true, the statement block will get executed, or it will get skipped.

Figure - Flowchart of if Statement:

35
Example of a C Program to Demonstrate if Statement
Example:

#include<stdio.h>

main()

int a = 15, b = 20;

if (b & gt; a) {

printf("b is greater");

Program Output:

36
Example:

#include<stdio.h>

main()

int number;

printf( & quot; Type a number: & quot;);

scanf( & quot; % d & quot;, & amp; number);

/* check whether the number is negative number */ if (number & lt; 0) {

/* If it is a negative then convert it into positive. */

number = -number;

printf( & quot; The absolute value is % d\ n & quot;, number);

grtch();

Program Output:

IF ELSE STATEMENTS

37
If else statement in C is also used to control the program flow based on some condition,
only the difference is: it's used to execute some statement code block if the expression is
evaluated to true, otherwise executes else statement code block.

The basic format of if else statement is:

Syntax:

if(test_expression)

//execute your code

else

//execute your code

Figure - Flowchart of if-else Statement:

38
Example of a C Program to Demonstrate if-else Statement
Example:

#include<stdio.h>

main()

int a, b;

printf("Please enter the value for a:");

scanf("%d", & amp; a);

printf("\nPlease the value for b:");

scanf("%d", & amp; b);

if (a & gt; b) {

printf("\n a is greater");

} else {

printf("\n b is greater");

Program Output:

39
Example:

#include<stdio.h>

main() {

int num;

printf("Enter the number:");

scanf("%d", num);

/* check whether the number is negative number */ if (num < 0)

printf("The number is negative.");

else

printf("The number is positive.");

Program Output:

NESTED IF ELSE

Nested if else statements play an important role in C programming, it means you can use
conditional statements inside another conditional statement.

40
The basic format of Nested if else statement is:

Syntax:

if(test_expression one)

if(test_expression two) {

//Statement block Executes when the boolean test expression two is true.

else

//else statement block

Example of a C Program to Demonstrate Nested if-else Statement


Example:

#include<stdio.h>

main()

int x=20,y=30;

if(x==20)

if(y==30)

printf("value of x is 20, and value of y is 30.");

41
}

Execution of the above code produces the following result.

Output:

value of x is 20, and value of y is 30.

ELSE-IF STATEMENTS

else-if statements in C is like another if condition, it's used in a program when if


statement having multiple decisions.

else-if statements in C is like another if condition, it's used in a program when if


statement having multiple decisions.

OUTPUT:

GOTO STATEMENTS

So far we have discussed the if statements and how it is used in C to control statement
execution based on some decisions or conditions.

42
The flow of execution also depends on other statements which are not based on
conditions that can control the flow.

C supports a unique form of a statement that is the goto Statement which is used to
branch unconditionally within a program from one point to another.

Although it is not a good habit to use the goto statement in C, there may be some
situations where the use of the goto statement might be desirable.

The goto statement is used by programmers to change the sequence of execution of a C


program by shifting the control to a different part of the same program.

The general form of the goto statement is:

Syntax:

goto label;

A label is an identifier required for goto statement to a place where the branch is to be
made.

A label is a valid variable name which is followed by a colon and is put immediately
before the statement where the control needs to be jumped/transferred unconditionally.

Syntax:

goto label;

- - -- - -

--------

label:

statement - X;

/* This the forward jump of goto statement */

or

label:

- - -- - -

--------

43
goto label;

/*This is the backward jump of goto statement */

An Example of a C Program to Demonstrate goto Statement


Example:

#include<stdio.h>

void main()

int age;

printf("you are Eligible\n");

printf("you are not Eligible");

printf("Enter you age:");

scanf("%d", &age);

if(age>=18)

goto g; //goto label g

else

goto s; //goto label s

getch();

SWITCH STATEMENT

C switch statement is used when you have multiple possibilities for the if
statement. Switch case will allow you to choose from multiple options.

When we compare it to a general electric switchboard, you will have many


switches in the switchboard but you will only select the required switch, similarly, the
switch case allows you to set the necessary statements for the user.

44
The basic format of the switch statement is:

Syntax:

switch(variable)

case 1:

//execute your code

break;

case n:

//execute your code

break;

default:

//execute your code

break;

BREAK STATEMENT

After the end of each block it is necessary to insert a break statement because if the
programmers do not use the break statement, all consecutive blocks of codes will get executed
from every case onwards after matching the case block.

#include<stdio.h>

main()

int a;

printf("Please enter a no between 1 and 5: ");

45
scanf("%d",&a);

switch(a)

case 1:

printf("You chose One");

break;

case 2:

printf("You chose Two");

break;

case 3:

printf("You chose Three");

break;

case 4:

printf("You chose Four");

break;

case 5:

printf("You chose Five.");

break;

default :

printf("Invalid Choice. Enter a no between 1 and 5");

break;

Program Output:

46
47
UNIT-III
DECISION MAKING AND LOOPING

INTRODUCTION:

➢ Sometimes it is necessary for the program to execute the statement several times,
and C loops execute a block of commands a specified number of times until a
condition is met.
➢ In this chapter, you will learn about all the looping statements of C programming
along with their use.

WHAT IS LOOPING?

A computer is the most suitable machine to perform repetitive tasks and can tirelessly do
a task tens of thousands of times.

Every programming language has the feature to instruct to do such repetitive tasks with
the help of certain form of statements.

The process of repeatedly executing a collection of statement is called looping.

The statements get executed many numbers of times based on the condition.

But if the condition is given in such logic that the repetition continues any number of
times with no fixed condition to stop looping those statements, then this type of looping is
called Infinite Looping.

C supports the following types of loops:

➢ while loops
➢ do while loops
➢ for loops

• All are slightly different and provides loops for different situations.

Figure - Flowchart of Looping:

48

• Loop control statements are used to change the normal sequence of execution of the loop.

Statement Syntax Description

break statement break; Is used to terminate loop or switch


statements.

continue continue; Is used to suspend the execution of current


statement loop iteration and transfer control to the
loop for the next iteration.

goto statement goto labelName; It transfers the current program execution


sequence to some other part of the program.
labelName: statement;

C BREAK STATEMENT

C break statement terminates any type of loop e.g., while loop, do while loop or for loop.
The breakstatement terminates the loop body immediately and passes control to the next
statement after the loop.

The break statement is only meaningful when you put it inside a loop body, and also in
the switch case statement.

We often use the break statement with the if statement, which specifies the condition to
terminate the loop.

49
The following example illustrates how to use the break statement:

#include <stdio.h>
int main() {
char key;
printf("Press any key or E to exit:\n");
while(1) {
scanf("%c", &key);
// if E or e, exit
if (key == 'E' || key == 'e')
break;
}
printf("Goodbye!\n");
}

The program asked users to enter any character. If the user enters E or e,
the break statement terminates the loop and control is passed to the statement after the loop that
displays the Goodbyemessage.
Besides using the break statement to terminate a loop, we also use the break statement
to terminate the processing of a case branch in the switch case statement.

C CONTINUE STATEMENT

C continue statement skips the rest of the current iteration in a loop and returns to the
top of the loop.
The continue statement works like a shortcut to the end of the loop body.
The following example illustrates the continue statement:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int haystack[SIZE] = {1, 3, 2, 4, 7, 6, 9, 5, 8, 0};
int needle;
printf("Enter a number (0-9) to see its position:");
scanf("%d",&needle);
int i;
for (i = 0; i < SIZE; i++)
{
if (needle != haystack[i])

50
{
printf("Finding at position %d: %d\n", i, haystack[i]);
continue;
}
printf("Number %d found at position %d\n", needle,i);
break;
}
return 0;
}

GOTO STSTEMENT:
C supports a unique form of a statement that is the goto Statement which is used to
branch unconditionally within a program from one point to another.
Although it is not a good habit to use the goto statement in C, there may be some
situations where the use of the goto statement might be desirable.
The goto statement is used by programmers to change the sequence of execution of a C
program by shifting the control to a different part of the same program.

The general form of the goto statement is:

Syntax:
goto label;

A label is an identifier required for goto statement to a place where the branch is to be
made. A label is a valid variable name which is followed by a colon and is put immediately
before the statement where the control needs to be jumped/transferred unconditionally.

Syntax:
goto label;

- - -- - -
--------
label:
statement - X;
/* This the forward jump of goto statement */

or

51
label:

- - -- - -
--------
goto label;
/*This is the backward jump of goto statement */

An Example of a C Program to Demonstrate goto Statement


Example:
#include<stdio.h>
void main()
{
int age;

g: //label name
printf("you are Eligible\n");
s: //label name
printf("you are not Eligible");

printf("Enter you age:");


scanf("%d", &age);
if(age>=18)
goto g; //goto label g
else
goto s; //goto label s
getch();
}

C WHILE LOOPS
C while loops statement allows to repeatedly run the same block of code until a condition
is met.
WHILE LOOP is a most basic loop in C programming. while loop has one control
condition, and executes as long the condition is true.
The condition of the loop is tested before the body of the loop is executed, hence it is
called an entry-controlled loop.

52
The basic format of while loop statement is:
Syntax:
While (condition)
{
statement(s);
Incrementation;
}

Figure - Flowchart of while loop:

example

#include<stdio.h>

int main ()
{
/* local variable Initialization */ int n = 1,times=5;

/* while loops execution */ while( n <= times )


{
printf("C while loops: %d\n", n);
n++;
}

return 0;
}

Program Output:

53
DO WHILE LOOPS

C do while loops are very similar to the while loops, but it always executes the code
block at least once and furthermore as long as the condition remains true. This is an exit-
controlled loop.

The basic format of do while loop statement is:

Syntax:
do
{
statement(s);

}while( condition );

Figure - Flowchart of do while loop:

Example:

#include<stdio.h>

int main ()
{

54
/* local variable Initialization */ int n = 1,times=5;

/* do loops execution */ do
{
printf("C do while loops: %d\n", n);
n = n + 1;
}while( n <= times );

return 0;
}
Program Output:

C FOR LOOPS

C for loops is very similar to a while loops in that it continues to process a block of code
until a statement becomes false, and everything is defined in a single line. The for loop is
also ENTRY-CONTROLLED loop.

The basic format of for loop statement is:

Syntax:
for ( init; condition; increment )
{
statement(s);
}

Figure - Flowchart of for loop:

55
Example of a C Program to Demonstrate for loop
Example:
#include<stdio.h>

int main ()
{
/* local variable Initialization */ int n,times=5;;

/* for loops execution */ for( n = 1; n <= times; n = n + 1 )


{
printf("C for loops: %d\n", n);
}

return 0;

Program Output:

SWITH STATEMENT

56
C switch statement is used when you have multiple possibilities for the if statement.
Switch case will allow you to choose from multiple options.

When we compare it to a general electric switchboard, you will have many switches in
the switchboard but you will only select the required switch, similarly, the switch case allows
you to set the necessary statements for the user.

The basic format of the switch statement is:

Syntax:
switch(variable)
{
case 1:
//execute your code
break;

case n:
//execute your code
break;

default:
//execute your code
break;
}

After the end of each block it is necessary to insert a break statement because if the
programmers do not use the break statement, all consecutive blocks of codes will get executed
from every case onwards after matching the case block.

#include<stdio.h>

main()
{
int a;
printf("Please enter a no between 1 and 5: ");
scanf("%d",&a);

switch(a)
{
case 1:
printf("You chose One");

57
break;
case 2:
printf("You chose Two");
break;
case 3:
printf("You chose Three");
break;
case 4:
printf("You chose Four");
break;
case 5:
printf("You chose Five.");
break;
default :
printf("Invalid Choice. Enter a no between 1 and 5");
break;
}

}
Program Output:

C ARRAYS

➢ The array is a data structure in C programming, which can store a fixed-size sequential
collection of elements of the same data type.
➢ For example, if you want to store ten numbers then instead of defining ten variables, it's
easy to define an array of 10 lengths.

In the C programming language, an array can be

➢ One-Dimensional,
➢ Two-Dimensional and
➢ Multidimensional.

58
ONE DIMENSIONAL ARRAY:

Define an Array in C

Syntax:

type arrayName [ size ];

This is called a one-dimensional array. An array type can be any valid C data types, and array
size must be an integer constant greater than zero.

Example:

double amount[5];

Arrays can be initialized at declaration time:

int age[5]={22,25,30,32,35};

Initializing each element separately in a loop:

int myArray[5];
int n = 0;

// Initializing elements of array seperately


for(n=0;n<sizeof(myArray);n++)
{
myArray[n] = n;
}

A Pictorial Representation of the Array:

Accessing Array Elements in C

Example:

59
int myArray[5];
int n = 0;

// Initializing elements of array seperately


for(n=0;n<sizeof(myArray);n++)
{
myArray[n] = n;
}

int a = myArray[3]; // Assigning 3rd element of array value to integer 'a'.

Single Dimensional Array:

1. Single or One Dimensional array is used to represent and store data in a linear form.

2. Array having only one subscript variable is called One-Dimensional array

3. It is also called as Single Dimensional Array or Linear Array

Syntax :

<data-type> <array_name> [size];

Example of Single Dimensional Array :

int iarr[3] = {2, 3, 4};

char carr[20] = "c4learn" ;

float farr[3] = {12.5,13.5,14.5} ;

2. Multi Dimensional Array :

1. Array having more than one subscript variable is called Multi-Dimensional array.

2. Multi Dimensional Array is also called as Matrix.

Syntax :

<data-type> <array_name> [row_subscript][column-subscript];

60
Example : Two Dimensional Array

int a[3][3] = { 1,2,3


5,6,7
8,9,0 };

in C programming, you can create array of an array known as multidimensional array. For example,

float x[3][4];

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You
can think the array as table with 3 row and each row has 4 column.

Similarly, you can declare a three-dimensional (3d) array. For example,

float y[2][4][3];

Here,The array y can hold 24 elements.

You can think this example as: Each 2 elements have 4 elements, which makes 8 elements and
each 8 elements can have 3 elements. Hence, the total number of elements is 24.

C STRINGS

61
In C programming, the one-dimensional array of characters are called strings, which is
terminated by a null character '\0'.

There are two ways to declare a string in C programming:

Example:

Through an array of characters.

char name[6];

Through pointers.

char *name;

Strings Initialization in C

Example:

char name[6] = {'C', 'l', 'o', 'u', 'd', '

char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};

'};

or

char name[] = "Cloud";

Memory Representation of Above Defined String in C

Example:

62
#include<stdio.h>

int main ()
{
char name[6] = {'C', 'l', 'o', 'u', 'd', '
#include<stdio.h>

int main ()
{
char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};

printf("Tutorials%s\n", name );

return 0;
}
'};

printf("Tutorials%s\n", name );

return 0;
}

Program Output:
TutorialsCloud

C STRING FUNCTIONS:
• String.h header file supports all the string functions in C language. All the string
functions are given below.
• Click on each string function name below for detail description and example programs.
String
functions Description

strcat ( ) Concatenates str2 at the end of str1

strncat ( ) Appends a portion of string to another

strcpy ( ) Copies str2 into str1

strncpy ( ) Copies given number of characters of one string to another

strlen ( ) Gives the length of str1

Returns 0 if str1 is same as str2. Returns <0 if strl <


strcmp ( ) str2. Returns >0 if str1 > str2

63
Same as strcmp() function. But, this function negotiates case.
strcmpi ( ) “A” and “a” are treated as same.

strchr ( ) Returns pointer to first occurrence of char in str1

strrchr ( ) last occurrence of given character in a string is found

strstr ( ) Returns pointer to first occurrence of str2 in str1

strrstr ( ) Returns pointer to last occurrence of str2 in str1

strdup ( ) Duplicates the string

strlwr ( ) Converts string to lowercase

strupr ( ) Converts string to uppercase

strrev ( ) Reverses the given string

strset ( ) Sets all character in a string to given character

strnset ( ) It sets the portion of characters in a string to given character

strtok ( ) Tokenizing given string using delimiter

C String function – strlen

Syntax:

size_t strlen(const char *str)


size_t represents unsigned short
It returns the length of the string without including end character (terminating char ‘\0’).

Example of strlen:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}

64
Output:
Length of string str1: 13

C String function – strcmp

int strcmp(const char *str1, const char *str2)


It compares the two strings and returns an integer value. If both the strings are same (equal) then
this function would return 0 otherwise it may return a negative or positive value based on the
comparison.
If string1 < string2 OR string1 is a substring of string2 then it would result in a negative
value. If string1 > string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for compare strings.

Example of strcmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:

string 1 and 2 are different

C String function – strncmp

int strncmp(const char *str1, const char *str2, size_t n)


size_t is for unassigned short
It compares both the string till n characters or in other words it compares first n characters of
both the strings.

Example of strncmp:

65
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:

string1 and string 2 are equal

C String function – strcat

char *strcat(char *str1, char *str2)


It concatenates two strings and returns the concatenated string.

Example of strcat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:

Output string after concatenation: HelloWorld

String function – strncat

66
char *strncat(char *str1, char *str2, int n)
It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will always be
appended at the end of the concatenated string.

Example of strncat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:

Concatenation using strncat: HelloWorld

C String function – strcpy

char *strcpy( char *str1, char *str2)


It copies the string str2 into string str1, including the end character (terminator char ‘\0’).

Example of strcpy:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m gonna copied into s1


C String function – strncpy

67
char *strncpy( char *str1, char *str2, size_t n)
size_t is unassigned short and n is a number.
Case1: If length of str2 > n then it just copies first n characters of str2 into str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1 and appends several
terminator chars(‘\0’) to accumulate the length of str1 to make it n.

Example of strncpy:

#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m

C String function – strstr

char *strstr(char *str, char *srch_term)


It is similar to strchr, except that it searches for string srch_term instead of a single char.

Example of strstr:

#include <stdio.h>
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
return 0;
}
Output:

Output string is: BeginnersBook.COM

68
UNIT IV
C POINTERS
INTRODUCTION
Pointers in C language is a variable that stores/points the address of another variable.
A Pointer in C is used to allocate memory dynamically i.e. at run time.

69
The pointer variable might be belonging to any of the data type such as int, float, char,
double, short etc.
A pointer is a variable in C, and pointers value is the address of a memory location.
Syntax:

type *variable_name;

Example:

int *width;

char *letter;

BENEFITS OF USING POINTERS IN C

• Pointers allow passing of arrays and strings to functions more efficiently.


• Pointers make it possible to return more than one value from the function.
• Pointers reduce the length and complexity of a program.
• Pointers increase the processing speed.
• Pointers save the memory.

Example program:

• #include<stdio.h>

• int main ()
• {
• int n = 20, *pntr; /* actual and pointer variable declaration */
• pntr = &n; /* store address of n in pointer variable*/
• printf("Address of n variable: %x\n", &n );

• /* address stored in pointer variable */ printf("Address stored in pntr variable: %x\n",
pntr );

• /* access the value using the pointer */ printf("Value of *pntr variable: %d\n", *pntr );

• return 0;
• }
• Address of n variable: 2cb60f04

• Address stored in pntr variable: 2cb60f04

70
• Value of *pntr variable: 20

UNDERSTANDING POINTER

Pointers in C language is a variable that stores/points the address of another variable.


A Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable
might be belonging to any of the data type such as int, float, char, double, short etc

ACCESSING THE ADDRESS OF A VARIABLE

The actual locations of a variable in the memory are system dependent and therefore, the address
of a variable is not known to us immediately.

Example: p=&quantity

The & operator can be remembered as address

➢ &125(pointing at constsnts)
➢ Int x[10]
➢ &x (pointing at array names)
➢ &(x+y) (pointing at expressions)

Example program:
void main()

{ int x,y, *ptr;

x=10;

ptr=&x;

y = *ptr;

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

printf(“%d is stored at address %u\n”, x, &x);

71
printf(“%d is stored at address %u\n”, *&x, &x);

printf(“%d is stored at address %u\n”, *ptr, &x);

printf(“%d is stored at address %u\n”, y, &*ptr);

printf(“%d is stored at address %u\n”,ptr,&ptr);

printf(“%d is stored at address %u\n”, y, &y);

*ptr=25;

printf(“\n Now x = %d\n”,x)

Output:

Value of X is 10

10 is stored at address 4104

10 is stored at address 4104

10 is stored at address 4104

10 is stored at address 4104

4104 is stored at address 4106

10 is stored at address 4108

Now x = 25

DECLARING, INITIALIZING AND USING A POINTER VARIABLE


In this concept, we will learn how to declare, initialize and use a pointer. We will also
learn what NULL pointer are and where to use them. Let's start!

DECLARATION OF POINTER VARIABLE


General syntax of pointer declaration is,
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer
variable is pointing. void type pointer works with all data types, but is not often used.
Here are a few examples:

72
int *ip // pointer to integer variable
float *fp; // pointer to float variable
double *dp; // pointer to double variable
char *cp; // pointer to char variable

INITIALIZATION OF POINTER VARIABLE


Pointer Initialization is the process of assigning address of a variable to
a pointer variable.
Pointer variable can only contain address of a variable of the same data type. In C
language address operator & is used to determine the address of a variable.The & (immediately
preceding a variable name) returns the address of the variable associated with it.
#include<stdio.h>
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointer variables always point to variables of same data type. Let's have an example to
showcase this:
#include<stdio.h>
void main()
{
float a;
int *ptr;
ptr = &a; // ERROR, type mismatch
}

If you are not sure about which variable's address to assign to a pointer variable while
declaration, it is recommended to assign a NULL value to your pointer variable. A pointer
which is assigned a NULLvalue is called a NULL pointer.

#include <stdio.h>

int main()
{
int *ptr = NULL;
return 0;
}

ACCESSING VARIABLE THROUGH POINTER

73
Steps:

1. Declare a normal variable, assign the value.


2. Declare a pointer variable with the same type as the normal variable.
3. Initialize the pointer variable with the address of normal variable.
4. Access the value of the variable by using asterisk (*) - it is known as dereference operator.

Code for ACCESSING VARIABLES USING POINTERS in C Programming

main()
{
int x, y;
int *ptr;
x = 10;
ptr = &x;
y = *ptr;
printf("Value of x is %d\n\n",x);
printf("%d is stored at addr %u\n", x, &x);
printf("%d is stored at addr %u\n", *&x, &x);
printf("%d is stored at addr %u\n", *ptr, ptr);
printf("%d is stored at addr %u\n", y, &*ptr);
printf("%d is stored at addr %u\n", ptr, &ptr);
printf("%d is stored at addr %u\n", y, &y);
*ptr = 25;
printf("\nNow x = %d\n",x);

}
Output
Value of x is 10
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
4104 is stored at addr 4106
10 is stored at addr 4108
Now x = 25

CHAIN OF POINTERS

74
Program

POINTER EXPRESSIONS
• Pointers expression :
void main()
{
int a,b,*p1,*p2, x, y, z ;
a =12; b = 4;
p1=&a; p2 = &b;
x = *p1 * *p2 – 6;
printf(“Address of a = %u\n”,p1);
printf(“Address of b=%u\n”,p2);
printf(“\n”);
printf(“a=%d, b=%d\n”,a , b);
printf(“x=%d \n”,x);

75
*p2 = *p2 + 3 ;
*p1 = *p2 – 5 ;
y = *p1 + *p2;
z= *p1 * *p2 – 6 ;
printf(\n a = %d , b = %d “, a ,b);
printf(“z = %d\n”, z);
}

Out put :-

Address of a = 4020
Address of b =4016
a = 12 b=4
x=42 y=9
a=2 b=7 z=8

POINTER INCREMENTS AND SCALE FACTOR :

➢ p1++ will cause the pointer p1 points to the next value of its type.
➢ Ex :- if p1 is an integer pointer with the initial value say 2800,then after the operations
p1=p1+1,the value of p1 will be 2802,not 2801
➢ when we increment pointer its value is increased by the length of the data type that it
points to. This length is called scale factor.

RULES FOR USING POINTER:

1. Pointer Variable Can be Assigned the address of another Variable


int main() {
int num = 10;
int *ptr;
ptr = &num;
return(0);
}

2. Pointer Variable Can be Assigned the value of another Pointer Variable


int *sptr,*tptr;
sptr = &num;

tptr = sptr;

3. Pointer Variable Can be initialized with zero or NULL value.


int *sptr,*tptr;
sptr = 0;

76
tptr = NULL;

4. Pointer variable Can be Perform Pre/Post fix Increment/Decrement Operation


int arr[20];
int *ptr;
ptr = &arr;
ptr++;

5. Integer value can be added or Subtracted from Pointer variable


int arr[20];
int *ptr;
ptr = &arr;
ptr = ptr + 2; //arr[2] will be accessed

6. When two Pointer points to same array then one Pointer variable can be Subtracted from

another

7. Two Pointers pointing to objects of same data type then they can be compared using the

Relational Operator

8. Value cannot be assigned to arbitrary address


int *ptr;
ptr = 100; //Illegal

9. Pointer Variable cannot be multiplied by Constant


int *ptr;
ptr = ptr * 6; //Illegal

POINTER AND ARRAYS


When an array is declared, compiler allocates sufficient amount of memory to contain all
the elements of the array. Base address i.e address of the first element of the array is also
allocated by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows:

77
Here variable arr will give the base address, which is a constant pointer pointing to the
first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In
short, arr has two purpose - it is the name of the array and it acts as a pointer pointing towards
the first element in the array.
arr is equal to &arr[0] by default

We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of the array arr using p++ to move from one element to
another.

POINTER TO ARRAY
As studied above, we can use a pointer to point to an array, and then we can use that
pointer to access the array elements. Lets have an example,
#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}

return 0;
}

78
In the above program, the pointer *p will print all the values stored in the array one by
one. We can also use the Base address (a in above case) to act as a pointer and print all the
values.

The generalized form for using pointer with an array,


*(a+i)
is same as:
a[i]

POINTER TO MULTIDIMENSIONAL ARRAY


A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point
to such an array. As we know now, name of the array gives its base address. In a[i][j], a will
give the base address of this array, even a + 0 + 0 will also give the base address, that is the
address of a[0][0]element.
Here is the generalized form for using pointer with multidimensional arrays.
*(*(a + i) + j)
which is same as,
a[i][j]

79
POINTER AND CHARACTER STRINGS
Pointer can also be used to create strings. Pointer variables of char type are treated as
string.
char *str = "Hello";
The above code creates a string and stores its address in the pointer variable str. The
pointer strnow points to the first character of the string "Hello". Another important thing to note
here is that the string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //this is Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not
need to use indirection operator *.

ARRAY OF POINTERS
We can also have array of pointers. Pointers are very helpful in handling character array
with rows of varying length.
char *name[3] = {
"Adam",
"chris",
"Deniel"
};
//Now lets see same array without using pointer
char name[3][20] = {
"Adam",
"chris",
"Deniel"
};

80
In the second approach memory wastage is more, hence it is preferred
to use pointer in such cases.
When we say memory wastage, it doesn't means that the strings will start occupying less
space, no, characters will take the same space, but when we define array of characters, a
contiguous memory space is located equal to the maximum size of the array, which is a wastage,
which can be avoided if we use pointers instead.

81
UNIT V
USER DEFINED FUNCTIONS
➢ A function is a block of code that performs a specific task.
➢ C allows you to define functions according to your need. These functions are known as
user-defined functions. For example:
➢ Suppose, you need to create a circle and color it depending upon the radius and color.
You can create two functions to solve this problem:
• create Circle() function
• color() function
Example: User-defined function

Here is an example to add two integers. To perform this task, an user-defined


function addNumbers() is defined.

1. #include <stdio.h>
2.
3. int addNumbers(int a, int b); // function prototype
4.
5. int main()
6. {
7. int n1,n2,sum;
8.
9. printf("Enters two numbers: ");
10. scanf("%d %d",&n1,&n2);
11.
12. sum = addNumbers(n1, n2); // function call
13.
14. printf("sum = %d",sum);
15.
16. return 0;
17. }
18.
19. int addNumbers(int a,int b) // function definition
20. {
21. int result;
22. result = a+b;
23. return result; // return statement
24. }

82
ELEMENTS OF USER-DEFINED FUNCTION IN C PROGRAMMING

There are multiple parts of user defined function that must be established in order to
make use of such function.

1. Function declaration or prototype


2. Function call
3. Function definition
4. Return statement

FUNCTION CALL

Here, function square is called in main

sqr = square (x); //function call

FUNCTION DECLARATION OR PROTOTYPE


int square(int a); //function prototype

Here, int before function name indicates that this function returns integer value to the
caller while intinside parentheses indicates that this function will recieve an integer value from
caller.

FUNCTION DEFINITION
Function definition provides the actual body of the function.

Syntax of function definition


return_value_type function_name (parameter_list)
{

83
// body of the function
}
It consists of a function header and a function body. The function_name is an identifier.
The return_value_type is the data type of value which will be returned to a caller.

Some functions perform the desired task without returning a value which is indicated by void as
a return_value_type. All definitions and statements are written inside the body of the function.

RETURN STATEMENT
Return statement returns the value and transfer control to the caller.

return s; //returns the square value s

There are three ways to return control.


return;
The above return statement does not return value to the caller.
return expression;
The above return statement returns the value of expression to the caller.
return 0;
The above return statement indicate whether the program executed correctly.

What are the elements of function definition?


A function definition also known as fuction implementation shall include the following
elements
1. FUNCTION NAME
2. FUNCTION TYPE.
3. LIST OF PARAMETERS
4. LOCAL VARIABLE DECLARATION
84
5. FUNCTION STATEMENT
6. RETURN STATEMENT
All the six elements are grouped into two parts, namely
➢ FUNCTION HEADER (first three elements)
➢ FUNCTION BODY(second three elements)

Function Definition shall include the following elements:-

FUNCTION HEADER:

The first line of function definition is known as function header.

It consists of three parts: return type, function name and argument list.

FUNCTION BODY:

It consists of three parts: local variable declaration part, executable part and return statement.

All the required variables are declared at the local variable declaration part.

Executable part contains all the executable statements that performs actual task.

Return Statement should be the last statement inside the function body. It is optional.

If return type of function is void then it can be omitted but function having return type other
than void must include return statement.

Example of function definition is given below for above function declaration.

Function Definition Example

float sum ( float x, float y)

85
{

float result ; // local variable

result = x + y ; // executable statement

return result ; // return statement

RETURN VALUES AND THEIR TYPES


The return statement terminates the execution of a function and returns control to the calling
function.
Execution resumes in the calling function at the point immediately following the call.
A return statement can also return a value to the calling function.
Syntax: return (or)
return(expressions)
example
int Sum(int a,int b){
return (a+b);
}

For example,

return a;
return (a+b);

FUNCTIONS CALL

86
There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference
1. CALL BY VALUE:
• In call by value method, the value of the variable is passed to the function as parameter.
• The value of the actual parameter can not be modified by formal parameter.
• Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:
• Actual parameter – This is the argument which is used in function call.
• Formal parameter – This is the argument which is used in function definition

EXAMPLE PROGRAM FOR C FUNCTIONS (USING CALL BY VALUE):


• In this program, the values of the variables “m” and “n” are passed to the function “swap”.
• These values are copied to formal parameters “a” and “b” in swap function and used.
C

1 #include<stdio.h>

2 // function prototype, also called function declaration

3 void swap(int a, int b);

5 int main()

6 {

7 int m = 22, n = 44;

87
8 // calling swap function by value

9 printf(" values before swap m = %d \nand n = %d", m, n);

10 swap(m, n);

11 }

12

13 void swap(int a, int b)

14 {

15 int tmp;

16 tmp = a;

17 a = b;

18 b = tmp;

19 printf(" \nvalues after swap m = %d\n and n = %d", a, b);

20 }

OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22

2. CALL BY REFERENCE:
• In call by reference method, the address of the variable is passed to the function as parameter.
• The value of the actual parameter can be modified by formal parameter.
• Same memory is used for both actual and formal parameters since only address is used by both
parameters.

EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):


• In this program, the address of the variables “m” and “n” are passed to the function “swap”.
• These values are not copied to formal parameters “a” and “b” in swap function.
• Because, they are just holding the address of those variables.
• This address is used to access and change the values of the variables.

88
1 #include<stdio.h>

2 // function prototype, also called function declaration

3 void swap(int *a, int *b);

5 int main()

6 {

7 int m = 22, n = 44;

8 // calling swap function by reference

9 printf("values before swap m = %d \n and n = %d",m,n);

10 swap(&m, &n);

11 }

12

13 void swap(int *a, int *b)

14 {

15 int tmp;

16 tmp = *a;

17 *a = *b;

18 *b = tmp;

19 printf("\n values after swap a = %d \nand b = %d", *a, *b);

20 }

89
OUTPUT:
values before swap m = 22

and n = 44
values after swap a = 44
and b = 22

CATEGORY OF FUNCTIONS:

All C functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Now, we will see simple example
C programs for each one of the below.

1. C function with arguments (parameters) and with return value.


2. C function with arguments (parameters) and without return value.
3. C function without arguments (parameters) and without return value.
4. C function without arguments (parameters) and with return value.

C functions aspects syntax

function declaration:
int function ( int );function call: function ( a );

function definition:
int function( int a )
{
1. With arguments and with statements;
return values return a;
}

function declaration:
void function ( int );function call: function( a );

function definition:
void function( int a )
2. With arguments and without {
return values statements;
}

3. Without arguments and without function declaration:

90
return values void function();function call: function();

function definition:
void function()
{
statements;
}

function declaration:
int function ( );function call: function ( );

function definition:
int function( )
{
4. Without arguments and with statements;
return values return a;
}

NOTE:
• If the return data type of a function is “void”, then, it can’t return any values to the calling
function.
• If the return data type of the function is other than void such as “int, float, double etc”, then, it
can return values to the calling function.

Example 1: No arguments passed and no return Value


1. #include <stdio.h>
2.
3. void checkPrimeNumber();
4.
5. int main()
6. {
7. checkPrimeNumber(); // argument is not passed
8. return 0;
9. }
10.
11. // return type of the function is void because function is not returning anything
12. void checkPrimeNumber()
13. {
14. int n, i, flag=0;
15.
16. printf("Enter a positive integer: ");

91
17. scanf("%d",&n);
18.
19. for(i=2; i <= n/2; ++i)
20. {
21. if(n%i == 0)
22. {
23. flag = 1;
24. }
25. }
26. if (flag == 1)
27. printf("%d is not a prime number.", n);
28. else
29. printf("%d is a prime number.", n);
30. }
The checkPrimeNumber() function takes input from the user, checks whether it is a prime
number or not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside the main() function
indicates that no argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.

Example 2: Argument passed but no return value


1. #include <stdio.h>
2. void checkPrimeAndDisplay(int n);
3.
4. int main()
5. {
6. int n;
7.
8. printf("Enter a positive integer: ");
9. scanf("%d",&n);
10.
11. // n is passed to the function
12. checkPrimeAndDisplay(n);
13.
14. return 0;
15. }
16.
17. // void indicates that no value is returned from the function
18. void checkPrimeAndDisplay(int n)
19. {
20. int i, flag = 0;
21.
22. for(i=2; i <= n/2; ++i)

92
23. {
24. if(n%i == 0){
25. flag = 1;
26. break;
27. }
28. }
29. if(flag == 1)
30. printf("%d is not a prime number.",n);
31. else
32. printf("%d is a prime number.", n);
33. }
The integer value entered by the user is passed to checkPrimeAndDisplay() function.
Here, the checkPrimeAndDisplay() function checks whether the argument passed is a prime
number or not and displays the appropriate message.

Example 3: Argument passed and a return value


1. #include <stdio.h>
2. int checkPrimeNumber(int n);
3.
4. int main()
5. {
6. int n, flag;
7.
8. printf("Enter a positive integer: ");
9. scanf("%d",&n);
10.
11. // n is passed to the checkPrimeNumber() function
12. // the value returned from the function is assigned to flag variable
13. flag = checkPrimeNumber(n);
14.
15. if(flag == 1)
16. printf("%d is not a prime number",n);
17. else
18. printf("%d is a prime number",n);
19.
20. return 0;
21. }
22.
23. // integer is returned from the function
24. int checkPrimeNumber(int n)
25. {
26. int i;
27.

93
28. for(i=2; i <= n/2; ++i)
29. {
30. if(n%i == 0)
31. return 1;
32. }
33.
34. return 0;
35. }
The input from the user is passed to checkPrimeNumber() function.
The checkPrimeNumber() function checks whether the passed argument is prime or not. If
the passed argument is a prime number, the function returns 0. If the passed argument is a non-
prime number, the function returns 1.
The return value is assigned to the flag variable.Depending on whether flag is 0 or 1,
appropriate message is printed from the main()function.

Example 4: No arguments passed but a return value


1. #include <stdio.h>
2. int getInteger();
3.
4. int main()
5. {
6. int n, i, flag = 0;
7.
8. n = getInteger(); // no argument is passed
9.
10. for(i=2; i<=n/2; ++i)
11. {
12. if(n%i==0){
13. flag = 1;
14. break;
15. }
16. }
17.
18. if (flag == 1)
19. printf("%d is not a prime number.", n);
20. else
21. printf("%d is a prime number.", n);
22.
23. return 0;
24. }
25.
26. int getInteger() // returns integer entered by the user
27. {

94
28. int n;
29.
30. printf("Enter a positive integer: ");
31. scanf("%d",&n);
32.
33. return n;
34. }
The empty parentheses in n = getInteger(); statement indicates that no argument is
passed to the function. And, the value returned from the function is assigned to n.

NESTING OF FUNCTIONS

➢ Nested functions in C. Some programmer thinks that defining a function inside


another function is known as “nested function”. ... Because nested functions definitions cannot
access local variables of the surrounding blocks, they can access only global variables of the
containing module.
➢ In some applications, we have seen that some functions are declared inside another function.
This is sometimes known as nested function, but actually this is not the nested function
Example

#include <stdio.h>
main(void) {
auto int my_fun();
my_fun();
printf("Main Function\n");
int my_fun() {
printf("my_fun function\n");
}
printf("Done"); }
Output

my_fun function
Main Function
Done

C RECURSION

A function that calls itself is known as a recursive function. And, this technique is known as
recursion.

HOW RECURSION WORKS?

95
void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}

Example: Sum of Natural Numbers Using Recursion


1. #include <stdio.h>
2. int sum(int n);
3.
4. int main()
5. {
6. int number, result;
7.
8. printf("Enter a positive integer: ");
9. scanf("%d", &number);
10.
11. result = sum(number);
12.
13. printf("sum = %d", result);
14. return 0;
15. }
16.
17. int sum(int num)
18. {
19. if (num!=0)
20. return num + sum(num-1); // sum() function calls itself
21. else
22. return num;
23. }

Output

Enter a positive integer:3


sum = 6

96
ADVANTAGES AND DISADVANTAGES OF RECURSION

Recursion makes program elegant and more readable. However, if performance is vital
then, use loops instead as recursion is usually much slower.

Note that, every recursion can be modeled into a loop.

SCOPE AND LIFETIME OF A VARIABLE

Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope, visibility and
lifetime of a variable.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register

Local Variable
1. The variables declared inside the function are automatic or local variables.
2. The local variables exist only inside the function in which it is declared. When the
function exits, the local variables are destroyed.

int main() {
int n; // n is a local variable to main() function
... .. ...
}

void func() {
int n1; // n1 is local to func() function
}

In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed
when main() exits.
Global Variable

1. Variables that are declared outside of all functions are known as external or global
variables. They are accessible from any function inside the program.

Example 1: Global Variable


1. #include <stdio.h>
2. void display();
3.
4. int n = 5; // global variable

97
5.
6. int main()
7. {
8. ++n; // variable n is not declared in the main() function
9. display();
10. return 0;
11. }
12.
13. void display()
14. {
15. ++n; // variable n is not declared in the display() function
16. printf("n = %d", n);
17. }

Output

n=7

suppose, a global variable is declared in file1. If you try to use that variable in a
different file file2, the compiler will complain. To solve this problem, keyword extern is used
in file2 to indicate that the external variable is declared in another file
.
Register Variable
1. The register keyword is used to declare register variables. Register variables were
supposed to be faster than local variables.
2. However, modern compilers are very good at code optimization and there is a rare chance
that using register variables will make your program faster.
3. Unless you are working on embedded systems where you know how to optimize code for
the given application, there is no use of register variables.

Static Variable
A static variable is declared by using keyword static. For example;

static int i;

The value of a static variable persists until the end of the program.

Example 2: Static Variable


1. #include <stdio.h>
2. void display();

98
3.
4. int main()
5. {
6. display();
7. display();
8. }
9. void display()
10. {
11. static int c = 0;
12. printf("%d ",c);
13. c += 5;
14. }

Output

0 5

During the first function call, the value of c is equal to 0. Then, it's value is increased by 5.
During the second function call, variable c is not initialized to 0 again. It's because c is a static
variable. So, 5 is displayed on the screen.

FILE INPUT/OUTPUT IN C
A file represents a sequence of bytes on the disk where a group of related data is stored.
File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the
functions,

Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

99
putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

OPENING A FILE OR CREATING A FILE


The fopen() function is used to create a new file or to open an existing file.
General Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
filename is the name of the file to be opened and mode specifies the purpose of opening
the file. Mode can be of following types,
mode description

r opens a text file in reading mode

w opens or create a text file in writing mode.

100
a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.

101
INPUT/OUTPUT OPERATION ON FILE
In the above table we have discussed about various file I/O functions to perform reading
and writing on file. getc() and putc() are the simplest functions which can be used to read and
write individual characters to a file.
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);

// closing the file pointer


fclose(fp);

return 0;
}

READING AND WRITING TO FILE USING FPRINTF() AND FSCANF()


#include<stdio.h>

struct emp
{
char name[10];
int age;
};

void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age:");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);

102
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(!feof(q));
}
In this program, we have created two FILE pointers and both are refering to the same file
but in different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file,
which can then be printed on the console using standard printf() function.

DIFFERENCE BETWEEN APPEND AND WRITE MODE


Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are
used to write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will not
happen.
Append mode is used to append or add data to the existing data of file(if any). Hence,
when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in
the file.

READING AND WRITING IN A BINARY FILE


A Binary file is similar to a text file, but it contains only large numerical data. The
Opening modes are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fwrite(data-element-to-be-written, size_of_elements, number_of_elements, pointer-to-file);

fread() is also used in the same way, with the same arguments like fwrite() function.
Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt", "wb");
if (bfp)
{
fwrite(mytext, sizeof(char), strlen(mytext), bfp);
fclose(bfp);
}

103
fseek(), ftell() and rewind() functions

• fseek(): It is used to move the reading control to different positions using fseek function.
• ftell(): It tells the byte location of current position of cursor in file pointer.
• rewind(): It moves the control to beginning of the file.

ERROR HANDLING IN C
C language does not provide any direct support for error handling. However a few
methods and variables defined in error.h header file can be used to point out error using the
return statement in a function.
In C language, a function returns -1 or NULL value in case of any error and a global
variable errno is set with the error code. So the return value can be used to check error while
programming.

WHAT IS ERRNO?
Whenever a function call is made in C language, a variable named errno is associated
with it. It is a global variable, which can be used to identify which type of error was encountered
while function execution, based on its value. Below we have the list of Error numbers and what
does they mean.

errno value Error

1 Operation not permitted

2 No such file or directory

3 No such process

4 Interrupted system call

5 I/O error

6 No such device or address

104
7 Argument list too long

8 Exec format error

9 Bad file number

10 No child processes

11 Try again

12 Out of memory

13 Permission denied

C language uses the following functions to represent error messages associated with errno:

• perror(): returns the string passed to it along with the textual represention of the current errno
value.

• strerror() is defined in string.h library. This method returns a pointer to the string
representation of the current errno value.

Time for an Example


#include <stdio.h>
#include <errno.h>
#include <string.h>

int main ()
{
FILE *fp;
fp = fopen("IWillReturnError.txt", "r");

printf("Value of errno: %d\n ", errno);


printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");

105
return 0;
}

Value of errno: 2
The error message is: No such file or directory
Message from perror: No such file or directory

OTHER WAYS OF ERROR HANDLING


We can also use Exit Status constants in the exit() function to inform the calling
function about the error.
The two constant values available for use are EXIT_SUCCESS and EXIT_FAILURE. These
are nothing but macros defined stdlib.h header file.
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

extern int errno;

void main()
{
char *ptr = malloc( 1000000000UL); //requesting to allocate 1gb memory space
if (ptr == NULL) //if memory not available, it will return null
{
puts("malloc failed");
puts(strerror(errno));
exit(EXIT_FAILURE); //exit status failure
}
else
{
free( ptr);
exit(EXIT_SUCCESS); //exit status Success
}
}
Here exit function is used to indicate exit status. Its always a good practice to exit a
program with a exit status. EXIT_SUCCESS and EXIT_FAILURE are two macro used to
show exit status.
In case of program coming out after a successful operation EXIT_SUCCESS is used to
show successful exit. It is defined as 0. EXIT_Failure is used in case of any failure in the
program. It is defined as -1.

106
DIVISION BY ZERO
There are some situation where nothing can be done to handle the error. In C language
one such situation is division by zero.
All you can do is avoid doing this, becasue if you do so, C language is not able to
understand what happened, and gives a runtime error.
Best way to avoid this is, to check the value of the divisor before using it in the division
operations. You can use if condition, and if it is found to be zero, just display a message and
return from the function.

107

You might also like