C Programming Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Contents:

1. Introduction to C b. Initialization, Condition and


2. Features of C increment/decrement
3. C Character Set c. Pretest and post test
4. C Tokens condition loops
a. Keywords 11. Functions in C
b. Identifiers a. Structure of Program with
c. Constants Function
d. Operators b. Built in and User Defined
e. Strings Functions
f. Special Symbols c. Types of Functions
5. Writing, Compiling and Linking d. Passing Parameters
program e. Recursive Functions
6. Structure of C Program f. Scope of variable and
7. Expressions Storage Class
8. Statements 12. Arrays
9. Decision Making a. 1 D Array
a. Two Way Selection b. 2 D Array
b. Multi way Selection c. Multidimensional Array
10. Repetition d. Passing Array in Function
a. Event Controlled and 13. Strings
Counter Controlled Loops

Introduction to C:
C is a general purpose language and was invented and first implemented by
Dennis Ritchie on a DEC PDP-11 that used the Unix operating system. It was
developed in AT&T Bell Labs in the year 1972. C Language was developed from
the language B. The hierarchy of the languages is as shown below:
ALGOL 60
(International Committee -1960)

CPL
(Cambridge & Univ. Of London-1963)

BCPL
DEVELOPMENT OF C (Martin Richards-cambridge-1967)

B
(Ken Thompson,Bell Labs.1970)

C
(Dennis Ritchie,bell Labs.1972)

Features of C Language:
a. It is relatively low level Language. Also know as middle level language.
b. C is a Structural Language.
c. It is Modular: As C supports functions, each from can be divided into
modules and sub modules thereby helping in achieving the modularity.
d. C is Procedural Language.
e. C language is Portable is nature: It can be used across various platforms, it
is known as portable in nature.
f. C language supports various data type usage.
g. C language is easy to use
h. It makes use of recursion.
i. Even though C is not strongly typed language, it supports type checking.
j. It provides fundamental control flow constructions as decision control,
looping etc.

C Character Set:
a. Alphabets -- A B...... Y Z and a b……y z
b. Digits -- 0,1,2,3,4,5,6,7,8,9
c. Special symbols -- ~ ` ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; " ' < > , . ? /
d. White Spaces – tabs, spaces enter

C Tokens
Token is the smallest unit of a C program. It can be categorized into different
types as shown below:

C Tokens

Keywords Identifiers Constants Operators String Special Symbol

a. Keywords:
The keywords are the reserved words whose meaning is already defined by
the C language. There are total 32 keywords in a C language. These are
used by the compiler as an aid to compile the program. These are always
written in lower case. The following is the list of valid keywords in C
language.
auto int double 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

b. Identifiers:
An identifier is used to name any variable, function or a program in C.
Usually the ideal length of an identifier is 31 characters for TC. So as to
write a valid identifier the following rules must be considered:
 It contains only alphabets, numbers and underscore.
 An Identifier should not start with digit.
 White spaces are not allowed in an identifier.
 Upper case and lower case alphabets are considered to be different.
 Special symbols are not allowed except underscore.
c. Constants:
Constants are the ones whose value remains unchanged throughout the
program. The constants can be categorized into two major categories as:

 Integer Constants:
These contain the integer value without the decimal point. It can be
either positive or negative. The allowed range for defining integer
constants is: -32768 to 32767
 Real Constants:
These are also known as the floating point constants. They can be
written using two methods as:
i. Fractional Method
ii. Exponential Method
 Character Constants:
These contain only single character as the value and the value is
always enclosed in a single quotes.
 String Constants:
These contain single or than one character or value enclosed in
double quotes. String constant always ends with the null character.
Defining the Constants:
The constants can be defined using any one of the following two methods:
i. Symbolic Constant: In this type the constants are defined after the
preprocessor directives and they make use of #define.
Example: #define pi 3.14
ii. Using const Keyword: In this type we define constant by making use of
the const keyword and declare it inside a function.
Syntax: const data_type variable_name = value;
Example: const float pi = 3.14;

d. Operators:
Operator is the one which performs action on the operands to give the
result. C language supports different operators as:
 Arithmetic Operators  Ternary/Conditional
 Logical Operators Operators
 Relational Operators  Bitwise Operators
 Assignment Operators  Special Operators
 Unary Operators
These are described in the following section:
1. Arithmetic Operators:
These are the binary operators. They can be classified as:

+ This performs the addition of numbers. 2+2=4


- This performs the subtraction of numbers. 4-2=2
* This performs multiplication of two numbers. 2*3=6
/ This performs the division and returns the quotient as
answer. 4/2=2
% This performs the mod operation and returns the remainder
as an answer. 4%3=1
2. Logical Operators:
These operators return the value in true or false form. They are
mostly used in checking the conditions. They make use of the logical
data (i.e. 0 or 1). These can be categorized as:

AND (&&) This operation returns true value only if both the
given conditions are true.
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1
OR (||) This operator returns true value if any one of the
operand is true.
A B A||B
0 0 0
0 1 1
1 0 1
1 1 1
NOT (!) This operator changes the true value to false and vice
a versa.

3. Relational Operators:
These operators are used for the purpose of comparison. These can
be classified as:
< Less than. x<y (x is less than y)
<= Less than equal to. x<=y (x is less than or equal to y)
> Greater than. x>y (x is greater than y)
>= Greater than equal to. x>=y (x is greater than or equal to y)
== Equal to. x==y (x is equal to y)
!= Not equal to. x!=y (x is not equal to y)

4. Assignment Operator:
This operator is used to assign a given value to the given variable. It
is denoted by = sign.
Example: x=5; This says that value 5 is assigned to the variable x.

5. Unary Operators:
These operators operate on the single operand. These can be
categorized as:
a. Increment Operator (++):
This operator is used to increment the value by 1.
Pre Increment It increments the value first and
++a considers the incremented value for
further calculation.
Post Increment It considers the value first for
a++ calculation and the increments it.
b. Decrement Operator (--):
This operator is used to decrement the value by 1.
Pre decrement It decrements the value first and
--a considers the decremented value for
further calculation.
Post decrement It considers the value first for
a-- calculation and the decrements it.

6. Ternary Operator:
The ternary operator is also known as the conditional operator. It
operates on three operands. This is denoted by (?:)
Syntax: Condition ? Part A : Part B;
If the given condition is true, then the part A is executed or else part
B is executed.
7. Bitwise Operators:
These operators operate at the bit level and are mostly used by the
compilers. These can be classified as:
Bitwise AND (&) This operation performs AND operation for
bit by bit. This operation returns true value
only if both the given conditions are true.
A B A&B
0 0 0
0 1 0
1 0 0
1 1 1
Bitwise OR (|) This operator returns true value if any one of
the operand is true.
A B A|B
0 0 0
0 1 1
1 0 1
1 1 1
Bitwise X OR (^) This operator returns false if both the
operands have same value or else it returns
true.
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
Bitwise Shift Operators
Left Shift Bit Pattern of the data can be shifted by specified
number of Positions to Left. When Data is Shifted Left ,
(<<) leading zero’s are filled with zero.
Syntax: Variable<<number of bits;
Original Number 0000 0000 0011 1100

Left Shift by 2 0000 0000 1111 0000

Leading 2 Blanks Replaced by 0, Shown


in RED

Movement of Data Left<<<<========


Right Shift Bit Pattern of the data can be shifted by specified
number of Positions to Right. When Data is Shifted
(>>) Right , leading zero’s are filled with zero.
Syntax: Variable>>number of bits;
Original Number 0000 0000 0011 1100

Right Shift by 2 0000 0000 0000 1111

Leading 2 Blanks Replaced by 0, Shown


in RED

Movement of Data Right ========>>>>>>

8. Special Operators:
C language supports special operators for different purpose.
comma operator Comma operator can be used
to link the related expressions
together. They are evaluated
left to right. These are mostly
used in for loops and multiple
variable declaration.
sizeof operator This is a compile time operator
and returns the total number of
bytes the particular operand
occupies.

Operators Precedence and Associativity:

The Expressions in a C language are evaluated based on the precedence of


the operators. The precedence indicated that which of the operator is to be
used first. Whenever in an expression if the operators of same precedence
appear, then the associativity of that operator is followed. It indicates
whether expression is evaluated from left to right or from right to left. The
table below shows the precedence of operators.
Example:
Escape sequences: An escape sequence is used to express non printing
character like a new line, tab etc. it begin with the backslash ( \ ) followed
by letter like a, n, b, t, v, r, etc. the commonly used escape sequence are
\a : for alert \n : new line \0 : null
\b : backspace \f : form feed \? : question mark
\f : horizontal tab \r : carriage return \’ : single quote
\v : vertical tab \” : quotation mark \t: tab
e. Strings:
The strings include any alpha numeric characters enclosed in double
quotes. Example: “Hello How Are You”. The strings ends with the null
characters.
f. Special Symbols:
The C language makes use of various special symbols as comma as
separator, semicolon as a delimiter etc.

Writing Compiling and Linking a Program:


a. Creation of Program:
The C Program must be written in a C text editor. Once it is written, the
program is saved with the .c extension. This is known as the source file.

b. Compiling a Program:
The source program statements must be translated into the object program
which is then executed. The file generated is known as .obj file. The
translation is done only when all the instructions are syntactically correct.

c. Executing a Program:
Once the compilation is done, the file is loaded in the main memory and
executed. The result of this process is given in .exe file.

The complete process is as shown below:


EDITOR

C SOURCE CODE

C PREPROCESSOR

STAGES IN C COMPILER

COMPILATION OF C ASSEMBLY LANG. CODE


PROGRAM
ASSEMBLER

OBJ CODE & LIB FILES

LINKER

EXECUTABLE CODE

LOADER

Structure of a C Program:
The C language is procedural in nature. So it defines its own structure. The
execution of the program starts from the main() function and each of the program
has one main function. The C program consists of variables, input statements,
processing statements, comments, output statements, user defined fuctions and
various other structures. The figure shows the structure of a C Program and the
later part shows the description of each of the element:
Comments if any

Preprocessors Directive

Global Declarations

void main()

{
Local Declarations

STATEMENTS

Input

Processing

Output

}
The Structure is as explained below:

a. Comments:
The comments are the documentary part in a C program and they are not
being executed by the compiler. The comments are for users and
programmers reference. The comments can be given by two different ways:
i. Single line comments: These are given by // symbol.
Example: //This is a Single Line Comment.
ii. Multiline comments: These are given in between / * */
Example: /* This is a Multi Line Comment
and not compiled by compiler*/

b. Preprocessor Directive
The preprocessor directive includes the header files in which all the built in
functions are defined. The header files ends with the .h extension. It tells
the compiler to see the syntax of the functions and their definition in the
header files. The header files must be included using the #include directive.
The header files are always enclosed in the pair of < > brackets.
Example: #include<stdio.h> This is standard input/output header file which
defines different functions such as printf(), scanf() etc.

c. Global Declarations
This part declares the variables which can be accessed throughout the
program and their scope is in complete program.

d. main() function
The main() function is the starting point of the execution of program. Each
program must have one main() function. The void return type says that the
function is not returning any of the value. main() function can be divided
into various parts as:
i. Local Declarations
In this section all the variables that are used in the function are
declared.
ii. Statements
The statements in the C program can be:
 Input Statement: These are used to take the input from the
user.
 Processing Statements: These are the statements in which the
actual calculations are being done.
 Output Statement: This statement is used to display the output
of the given program to the user.

Example: Program to perform Addition of two numbers:

#include<stdio.h> preprocessor directive


void main( ) Beginning of main( ) function
{
int a, b, c; Variable declaration
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b); Input Statement
c=a+b; Processing Statement
printf(“\n Addition is %d”,c); Output Statement
}

Output:
Enter two numbers 4 5
Addition is 9

Variable:

Variable is the one whose value changes. The variable must be declared by using
data type and a valid identifier. The variables must be declared for the following
reasons:

i. It tells the compiler to allocate memory


ii. It also gives name to access that memory.

Declaration:
data_type variable_name;
Example: int a,b,c;
where a,b,c are the three variables which stores the integer type of the data.

Initialization:
data_type variable_name = value;

Example: int a=5;


where a is the integer type of variable which stores the value 5.

Data Types:
The data types are used to specify which type of data is to be stored and how
much amount of the memory is to be allocated. The C language data types can be
classified into different types as:

a. Integer Data type:


 Integers are whole numbers with a range of values. Generally an
integer occupies 2 bytes memory space and its value range limited to
-32768 to +32767.
 A signed integer use one bit for storing sign and rest 15 bits for
number.
 C has three classes of integer storage namely
short int, int and long int.
A short int requires half the amount of storage than normal integer.
The long integers are used to declare a longer range of values and it
occupies 4 bytes of storage space.
Syntax:
int <variable name>;
int num1;
short int num2;
Memory allocation for int:

b. Float Data Type


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. It allocates 4 bytes of memory.
Syntax:
float <variable name>;
float num1;

c. Double Data Type


It is also similar to the float type but is used when the precision needs to be
more accurate. It allocates 8 Bytes of memory. For more storage, long
double can be used which allocates 10 Bytes of memory.
Syntax:
double <variable name>;
double num1;
long double num2;

d. Character Data Type


Character type variable can hold a single character and are declared by
using the keyword char. 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>;
char ch = ‘a’;
e. void type:
The void type has no values therefore we cannot declare it as variable. The
void data type is usually used with function to specify its return type.

Input Statements: scanf()


The scanf() is defined in the stdio.h header file. This the standard input function
and is used to store the value to its own address.
Syntax:
scanf(“format specifiers”,&variable_name);

Format Specifier:
These are the elements in C language that specifies the compiler about the type
of the value to be stored in the declared variable. These are defined based on the
data type of the variable.
%d Used for Integer data types %o Octal numbers
%f Used for Floating point data types %x Hexadecimal numbers
%c Used for Character data types
%s Used for strings
%u Used for storing the address.
Example:
scanf(“%d%d”,&a,&b);
This statements says that the values are of integer type and are to be stored at
the address of variable a and b respectively.

Output Statement: printf()


This function is used to generate or to display the output to the user. This
function is defined in the stdio.h header file.
Syntax:
printf(“String to be printed”); (OR)
printf(“format specifiers”,list of variables);
Example:
printf(“The value of the variables are”);
printf(“value 1 = %d”,a);

Expressions
An expression is a sequence of operators and operands that reduces to a single
value. The value can be of any type. An operator is a language specific syntactical
token that requires the action to be taken. Operand are the one on which an
action is performed. Different types of expressions are:
Type of Expression Categories Example
Primary 1. Identifier name
2. Constant constant value pi
3. Parenthetical (2+2)
Unary 1. Prefix increment ++a
2. Prefix decrement --a
3. size in bytes sizeof(int)
4. minus/negation -2
Binary 1. Multiplicative 2*2 or2/2
2. Additive 2+2 or 6-4
Assignment 1. Simple Assignment x=2
2. Compound Assignment x+=2  x=x+2
Postfix 1. Function any function call
2. Postfix Increment a++
3. Postfix Decrement a--
Type Conversion:

a. Implicit type conversion


 C permits mixing of constants and variables of different types in an
expression. C automatically converts any intermediate values to the
proper type so that the expression can be evaluated without losing any
significance. This automatic type conversion is known as implicit type
conversion. During evaluation it adheres to very strict rules and type
conversion. If the operands are of different types the lower type is
automatically converted to the higher type before the operation
proceeds. The result is of higher type. long double

double

float

unsigned long int

long int
Promotion Hierarchy
unsigned int

int

short

char
b. Explicit Conversion
 Many times there may arise a situation where we want to force a type
conversion in a way that is different from automatic conversion.
 This is known as explicit type conversion.
 The general form is: (type) Expression.

Statements
The statement causes an action to be performed by the program. It translates
directly into one or more executable computer instructions.
The following are the different types of statements:
Expression When we give semicolon to expression, they become
statements. Example: x=a+b;
Compound It is unit of code consisting of zero or more statements. It
is also known as block.
Example
{
a=5;
b=5;
c=a+b;
}
Labeled These consist of goto statements.
Selection These are the branching statements.
Example: if, if-else
Iterative These are the looping statements.
Jump These are the break, continue statements.
Decision Making
Selection or decision making allows us to choose between two or more
alternatives. It can be of different types:
1. Two way Selection
2. Multi way Selection
The selection is done based on the logical data. The logical and relational
operators are mostly used for the process of selection.

Simple if
The simple if statement is used to check the condition. If the give condition is true
or the condition gives non zero value, the block under if statement is executed.

Syntax:
if (condition)
{
Block of statements;
}
if else
The if else structure overcomes the disadvantage of simple if i.e. Even if the given
condition is true, simple if checks the rest of the conditions also.
The if-else structure checks the condition and based on the result of the
condition, it evaluates either of the block.

Syntax:
if(condition)
{
Block of statements if the condition is TRUE;
}
else
{
Block of statement if the condition is FALSE;
}

Nested if-else:
This structure is needed when the user needs to check for more than one
condition. This is the complex structure of the if-else block.
Syntax:
if(condition 1)
{
if(condition 2)
{
Block of Statements when both the conditions are TRUE;
}
else
{
Block of Statements when only condition 1 is TRUE;
}
}
else
{
if(condition 3)
{
Block of Statements when the condition1 is FALSE and 3 is TRUE;
}
else
{
Block of Statements when both the conditions are FALSE;
}
}

Null else:
Sometimes in the programming structure, we have the situation where the else
part is not present at that time the else part is written with only semicolon or it is
skipped. This is known as null else. The structure of the program becomes similar
to the simple if.
Dangling else:
This the erroneous condition in which the else part of the particular if statement
is misplaced. It is also known as misplaced else. It is always created when there is
no matching else for if, in such case, else is placed with the most nearest if
condition in a program.
else if ladder:
This construct is a multi way selection where we give the user with all the possible
options and finally a default else construct is given. It is mostly used when the
selection variable does not have integral value or else the same variable is being
tested in a given expression.
Syntax:

if(condition 1)
statement1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
else if(condition 4)
statement 4;
.
else if(condition n)
statement n;
else
default statement ;

Switch Statement:
The switch statement is also a multi way selection statement. It is used only when
the selection variable has integral value. It consists of four different keywords as:
a. switch
The switch indicates the starting of the switch statement. The selection
takes place based on the value of the selection variable present in the
switch.
b. case
This is used to define different blocks based on the possibilities the
selection variable can have.
c. break
This is the mandatory statement after every case definition. This indicates
that the case is executed and it comes out of the switch case without
checking the further cases. It results to force termination.

d. default
The default statement is similar to the last else in the else if ladder. This
statement is executed only if all the cases are checked and none of the
value is matched. The default is optional statement.

Syntax:
switch(variable_name)
{
case 1: Statement 1;
break;
case 2: Statement 2;
break;
.
.
case n: Statement n;
break;
default: statement;
}
Flowchart:

Continue Statement:
The continue statement works somewhat like the break statement. Instead of
forcing termination, however, continue forces the next iteration of the loop to
take place, skipping any code in between.
Repetition Statements: Looping
The loops are basically used when the user wants the same activity to be
performed again and again. Loops can be classified as:
1. Event Controlled and Counter Controlled Loops
a. Counter-controlled loops
 A loop controlled by a counter variable, generally where the number
of times the loop will execute is known ahead of time.
 Generally used with for loops
 Can generally infer number of repetitions from code.
 Examples:
– read 5 numbers
– print 7 items
– sort n items
b. Event-controlled loops
 The loops where termination depends on an event rather than
executing a fixed number of times.
 Generally used with while, do-while loops.
 Can’t infer number of repetitions from program.
 Examples:
– read until input ends
– read until a number encountered
– search through data until item found
2. Pre test and Post test Condition Loops
These are categorized based on the time the condition is being checked.
Pretest Loops
 A logical condition is checked before each repetition to determine if the
loop should terminate or not.
 If the condition is false, the loop is never executed.
– while loop
– for loop
Posttest Loops
 A logical condition is checked after each repetition for termination.
 In this the loop is executed atleast once even if the condition is false.
– do-while loop

The Basic Statements for Loops:


Each of the loop must have the loop variable. Each loop consists of the following
three important statements.
1. Initialization of loop:
This indicates the starting point of the loop. The variable must be initialized
before starting the loop.
2. Test Condition:
Each of the loop has its own test condition. The loop executes only till the
time the condition is true. Therefore the condition is used to terminate the
loop. If the condition is wrong, the loop may run infinitely.
3. Updation of Loop:
The loop variable must be updatedd at every iteration so that the loop
termination condition is met. The updation is done either by incrementing
the value or by decrementing the value.
We have three different types of loops:

1. while loop
Explanation:
This is the pretest loop in which the condition is checked prior to
entering the loop. It repeats a statement or group of statements while a
given condition is true
Syntax:
initialization statement;
while(condition)
{
Block of statement if condition is TRUE;
increment/decrement;
}
Flowchart:

2. for loop
Explanation:
This is also a pretest loop in which the condition is checked before
entering the loop. In thhis case all the three statements as initialization,
loop condition and update is placed in a single line separated by
semicolons.
We may have variations in foor loop where we have two conditions, which
can be separated by comma.

Syntax:

for(initialization statement; Loop Condition; Increment/decrement)


{
Body of the Loop executed when the condition is TRUE;
}
Flowchart:

3. do while loop
Explanation:
The do while loop is also known as the exit controlled or post test loop
as this loop tests the condition only after the loop is executed. Even if the
loop condition is false, the body of the loop is executed once.
Syntax:
initiaalization statement;
do
{
Block of statement;
increment/decrement;

}while(condition);
Flowchart:
Infinite Loops:
This is the condition when the loop starts its execution, but the loop
termination condition is never met. This happens due to various reasons as:
you forget to increase the counter or the user never enters terminating
data item etc.
Example: Print the numbers from 1 to 10 using all loops.
while loop for loop do while loop
#include<stdio.h> #include<stdio.h> #include<stdio.h>
void main() void main() void main()
{ { {
int i=1; int i; int i=1;
while(i<=10) for(i=1;i<=10;i++) do
{ { {
printf(“\n%d”,i); printf(“\n%d”,i); printf(“\n%d”,i);
i++; i++;
} } }while(i<=10);
} } }

Nested for Loops:


In this we make use of the concept of for within for. The nested loops are mostly
used in the matrices where you have more than one dimension.

exit():
This function is defined in the stdlib.h header file and it is used to exit from the
program. This functions returns a non zero number and hence also written as
exit(0) or exit(1).
Functions in C
C language supports the use of the function. It is also used such that we can have
structural way of programming. As the program is divided into different modules
and submodules, this is also known as the modular programming approach.
The C language functions can be divided into two broad categories as:

1. Built in Functions
The built in functions are the ones which are already defined by the
language. There definition is present in the library of the C compiler by the
developers. For Example: printf(), scanf() etc.
These can also be classified as:
 Memory management functions: malloc(), realloc(), calloc(), free()
 String Manipulation Functions: strcpy(), strcmp(), strupr(), etc.
 Buffer Manipulation Functions: memcpy(), memmove(), etc.
 Character Manipulation Functions: islower(), isupper() etc.
 Error Handling Functions: perror(), strerror(), etc.

2. User Defined Functions


The C language also provides the user defined functions which are used to
perform the customized operation. These functions are basically declared
and defined by the user in the program.

Each of the user defined function must have three different parts as:
1. Function Declaration
2. Function Call
3. Function Definition.

 The structure of a C Program with functions is as shown:


 The Function is declared in the global declarations part and the
fuction is called from some other function.
 The function that is calling other function is known as calling function
and the one which is called is the called function.
 Each function used is being separately in the program.
 The definition shows the task performed by that particular function.
Comments if any

Preprocessors Directive

Global Declarations
Function Declaration
void main()

{
Local Declarations

Input Statements

Function Call();

Processing Statements;

Output Statements;
}

} Function Definition()

Body of Function;

Function Declaration:
As the variables are declared before using, the user defined functions must also
be declared before using them. The function declaration syntax is:
return_type function_name(parameters/arguments if any);
Where, the return_type specifies the type of the value the function is going to
return. Function name is any name that satisfies the rules of identifier.
arguments/parameters are the values the function accept from the calling
function.
Function Call/Invocation of Function:
Once declared, the function must be called from some of the function. The syntax
of the function call depends on the type of value the function is reurning.
Syntax:
If function is returning any value:
some_variable=function_name(parameters if any);
If the function is not returning any value then the syntax is:
function_name(parameters if any);
Function Definition:
The function definition specifies the body of the function in which the tasks
performed by the function are defined.
Syntax:
return_type Function_name(parameters if any)
{
Body of Function;
}
Types of Function:
Based on the return type and the parameters the function can be categorized into
four different categories.
1. Without Return Type, Without Arguments
2. Without Return Type, With Arguments
3. With Return Type, Without Arguments
4. With Return Type, With Arguments
Whenever the function is without the return type, the return type of the
function is given as void or else it depends on the type of the data it is going
to return.

Without Return Type, Without Arguments:


This type of function neither returns any of the value to the calling function nor it
takes any values from the calling function.
Example: Addition of two numbers using function add()
#include<stdio.h>
void add(); // Function without return type without parameters
void main()
{
add(); // Function Call
}
void add() // Function Definition
{
int a, b, c;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“\n Addition is %d”,c);
}

Output:
Enter two numbers 4 5
Addition is 9

Without Return Type, With Arguments:


This type of function takes values from the calling function but it does not returns
any of the value to the calling function. The values are passed using the passing
mechanism.

Example: Addition of two numbers using function add()

#include<stdio.h>
void add(int a, int b); // Function without return type with parameters
void main()
{
int x,y;
printf(“Enter two numbers”);
scanf(“%d%d”,&x,&y);
add(x,y); // Function Call
}
void add(int a, int b) // Function Definition
{
int c;
c=a+b;
printf(“\n Addition is %d”,c);
}

Output:
Enter two numbers 4 5
Addition is 9

With Return Type, Without Arguments:


This type of function does not take any values from the calling function but it does
return the value to the calling function.

Example: Addition of two numbers using function add()

#include<stdio.h>
int add(); // Function with return type without parameters
void main()
{
int ans;
ans=add(); // Function Call
printf(“\n Addition is %d”,ans);
}
int add() // Function Definition
{
int a, b, c;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}
Output:
Enter two numbers 4 5
Addition is 9
With Return Type, With Arguments:
This type of function takes the values as the parameters or arguments from the
calling function and also return the value to the calling function.

Example: Addition of two numbers using function add()


#include<stdio.h>
int add(int a, int b); // Function with return type with parameters
void main()
{
int x, y, ans;
printf(“Enter two numbers”);
scanf(“%d%d”,&x,&y);
ans=add(); // Function Call
printf(“\n Addition is %d”,ans);
}
int add(int a, int b) // Function Definition
{
int c;
c=a+b;
return(c);
}

Output:
Enter two numbers 4 5
Addition is 9

Passing Parameters in C
The C language provides two different ways of passing the arguments or
parameters. These are as described:
Call by Value Call By Reference
 The copy of actual parameter is  Instead of sending the copy, the
passed to the function address is passed as the
 New memory area is created parameter
which can be used only within  Changes in the function are
the function, changes in the reflected in the calling function
function are not reflected also.
Example: Example:

#include<stdio.h> #include<stdio.h>
void swap(int num1,int num2); void swap(int *num1,int *num2);
void main() void main()
{ {
int x,y; int x,y;
printf("\nEnter two numbers : "); printf("\nEnter two numbers : ");
scanf("%d%d",&x,&y); scanf("%d%d",&x,&y);
printf("\nBS x=%d y=%d",x,y); printf("\nBS x=%d y=%d",x,y);
swap(x, y); // Pass By Value swap(&x,&y); // Pass By Reference
printf("\nAS x=%d y=%d",x,y); printf("\nAS x=%d y=%d",x,y);

} }
--------------------------------------- ---------------------------------------
void swap(int num1,int num2) void swap(int *num1,int *num2)
{ {
int temp; int temp;
temp = num1; temp = *num1;
num1 = num2; *num1 = *num2;
num2 = temp; *num2 = temp;
printf("\nAS in function x=%d printf("\nAS in function x=%d
y=%d",num1,num2); y=%d",*num1,*num2);

} }

Output: Output:

Enter two numbers : 12 21 Enter two numbers : 12 21


BS x = 12 and y = 21 BS x = 12 and y = 21
AS x = 12 and y = 21 AS x = 21 and y = 12
AS in function x = 21 and y = 12 AS in function x = 21 and y = 12

Functions Using Recursion:


The process of calling itself again and again is called recursion. Whenever the
function calls itself, it is known as the recursive function. So as to store the data
recursive functions makes use of the stack data structure.
Advantages:
 Recursion is more elegant and requires few variables which make
program clean.
 Recursion can be used to replace complex nesting code by dividing
the problem into same problem of its sub-type.

Disadvantages:
 It is hard to think the logic of a recursive function.
 It is also difficult to debug the code containing recursion.
 It may also lead to stack overflow.

Example: Program to Find Sum of n natural numbers using recursion:


#include <stdio.h>
int sum(int n);

void main()
{
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}

int sum(int n)
{
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}

The function calls itself till the value of n becomes 0


Output:

Enter a positive integer:


5
sum=15
Hand run:
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)

=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15

Scope of Variable and Storage Classes:


A scope of any variable of the program is a region of the program where a defined
variable can have its existence and beyond that the variable cannot be accessed.
Variables can be declared in C programming language with two main Scopes as:

Local: Inside a function or a block which is called local variables,


Global: Outside of all functions which is called global variables.

Local Variables
Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of
code. Local variables are not known to functions outside their own. Following is
the example using local variables. Here all the variables a, b and c are local to
main() function.

#include<stdio.h>
void main( )
{
int a, b, c; // Local Variables
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“\n Addition is %d”,c);
}

Output:
Enter two numbers 4 5
Addition is 9

Global Variables:
Global variables are defined outside of a function, usually on top of the program.
The global variables will hold their value throughout the lifetime of your program
and they can be accessed inside any of the functions defined for the program. A
global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration.

#include<stdio.h>
int c; // Global Declaration

void main( )
{
int a, b; // Local Variables
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“\n Addition is %d”,c);
}
Output:
Enter two numbers 4 5
Addition is 9

Here, even though c is not defined by the main() function, it can be accessed by it
as the scope of variable c is global.
Storage Classes:

A storage class is an attribute that tells us where the variable would be stored,
what will be the initial value of the variable if no value is assigned to that variable,
life time of the variable and scope of the variable.
The C language provides four storage classes as:
1. Automatic Storage Class
2. Extern Storage Class
3. Static Storage Class
4. Register Storage Class

Automatic Storage Class:


 The keyword used for Automatic storage class is ‘auto’.
 The variable declared as auto is stored in the memory.
 Default value of that variable is garbage value.
 Scope of that variable is local to the block in which the variable is defined.
Variable is alive till the control remains within the block in which the
variable id defined.

Extern Storage Class:


 External variable can be accessed by any function.
 They are also known as global variables. Variables declared outside
every function are external variables.
 In case of large program, containing more than one file, if the global
variable is declared in file 1 and that variable is used in file 2 then,
compiler will show error. To solve this problem, keyword extern is
used in file 2 to indicate that, the variable specified is global variable
and declared in another file.
 Example:
#include<stdio.h>
void main()
{
extern int b;
printf(“%d “,b);
}
int b=10;
Output: 10
Static Storage Class
 The value of static variable persists until the end of the program.
 A variable can be declared static using keyword: static.
 The variable declared as static is stored in the memory. Default value of
that variable is zero.
 Life of variable persists between different function calls.
 The variable is initialized only once throughout the program.
 Example:

#include <stdio.h>
void Check();
void main()
{
Check();
Check();
Check();
}

void Check()
{
static int c=0;
printf("%d\t",c);
c=c+2;
}

Output: 0 2 4

Register Storage Class


 Register variables are similar to automatic variable and exists inside
that particular function only.
 If the compiler encounters register variable, it tries to store variable
in microprocessor's register rather than memory. Values stored in
register are much faster to access than that of memory.
 In case of larger program, variables that are used in loops and
function parameters are declared register variables.
 Example: register int i;
Arrays in C
 Array is a collection of homogenous data stored under unique name. The
values in an array are called 'elements of an array.'
 These elements are accessed by numbers called as 'subscripts or index
numbers.'
 Arrays are the derived data types in C language. These are used to store the
continuous block of memory. The data of same data type can be combined
and stored by making use of one array variable.
The arrays can be classified into different types as:
1. One Dimensional array(1D)
2. Two Dimensional array(2D)
3. Multi Dimensional array(m D)

One Dimensional Array:


The array which is used to represent and store data in a linear form is called as
'single or one dimensional array.'
Syntax:
data-type array_name [size];
Where, the data type is any built in data type array_name is valid identifier and
size indicates the number of elements present in that array.
Example: int age[5];
Here, age is an array of 5 elements that stores the value of integer type.
Therefore memory allocated is of 10Bytes.
Total Size can be calculated by: total size = length of array * size of data type

Representation:

Initialization of 1D Array:
The array elements can be initialized in two different ways:
Method 1:

int a[5]={1,2,3,4,5};
Here, the five elements are being initialized. These can be represented as:
index: a[0] a[1] a[2] a[3] a[4]

1 2 3 4 5 Array Elements
Address: 1000 2000 4000 6000 7000

If only some of the values are given during initialization as:


int a[5]={1,2};
In this case the first two elements are initialized and the rest are initialized with 0.
Method 2:
In this method, the array elements are initialized individually, by giving specific
index.
Example: int a[5];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
a[4] = 5;

It is not necessary to define the size of arrays during initialization.


int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number
of elements of an array.

Accessing 1D Array elements:


The array elements can be accessed by writing individual scanf() and printf() for
each element or they can be accessed making use of the for loops.
Individual scanf() statement:

scanf("%d",&a[2]);/* statement to insert value in the third element of array a[]. */


Using for loops:
int a[5],i;
for(i=0;i<=4;i++)
{
scanf(“%d”,&a*i+);
}

Example: To show the use of 1D Array:


#include <stdio.h>
void main()
{
int n[5];
int i;
printf("Enter the elements of an array \n");
for(i=0;i<=4;i++)
{
scanf("%d",&n[i]);
}
printf("Array elements are\n");
for(i=0;i<=4;i++)
{
printf("%d\n",n[i]);
}
}
Two Dimensional Array:
Two-dimensional array are those type of array, which has finite number of rows
and finite number of columns. Matrices are the most common example for the
two dimensional array.
Declaration:
data_type array_name [row size][column size];

Where, the type may be any valid type supported by C. The rule for giving the
array name is same as the ordinary variable. The row size and column size should
be an individual constant.
Example: int a[3][3];
Representation:

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


a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]
In memory the matrix elements can be stored row wise or column wise. The row
wise storage representation is more common. This can be shown as below:
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2]

Initialization:
The 2 D array can be initialized by two different methods:
Method 1:
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

1 2 3
4 5 6
7 8 9
Similar to 1D array, if only few elements are specified, then the rest are initialized
to 0.
Method 2:
In this each element is initialized individually by specifying the index.
int a[2][2];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
a[2][0] = 7;
a[2][1] = 8;
a[2][2] = 9;
Accessing the 2D Array elements:
The 2D array elements can be accessed by making use of the nested for loops.
The outer loop is for the row elements and the inner loop for column elements.
The elements are accessed row wise i.e. for a particular row all the column
elements are taken and then the next row is considered.
Example: Program that calculates sum of all elements of 2D Array
void main()
{
int a[3][3], i, j, sum=0;
/*Accepts input from the user and stores it in 2-D array*/
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
scanf(“%d”,&a*i+*j+);
}
}

/*Calculate sum of elements in 2-D array*/


for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
sum = sum+a[i][j];
}
}
/*Display the value of sum*/
printf(“\nThe sum of the elements of 2-D array is %d”, sum);
}

Here, the first set of nested loops are used to take input from the user whereas
the next ones are used to calculate the sum of elements.

Passing Array as Function Argument:


As the variables can be passed as an argument to the function, we can also pass
the array elements as the argument to the function. It is possible to pass entire
array or single element of an array of multi dimensional array as an argument to
the function. When we pass array as element, we write only array name in
parameter.
Example:
array(x); //This is function call where array is function name and x is array, this
says that the address of the first is passed.
Example: Calculate the average age by making use of array and Function
#include <stdio.h>
float average(float a[]);
void main()
{
float avg, i, c[5];
printf(“Enter ages ”);
for(i=0;i<=4;i++)
{
scanf(“%d”,&c*i+);
}
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
}
float average(float a[])
{
int i;
float avg, sum=0.0;
for(i=0;i<=4;++i)
{
sum+=a[i];
}
avg =(sum/6);
return avg;
}
Strings in C
A string in C is a series of characters in a group that occupy contiguous memory. A
group of characters (Alphabets, digits and special characters) is called as a string.
A string in C language should always be enclosed with in double quotes (“).
If single quote is used then it is treated as character. Hence ‘A’ is different from
“A”. Every string ends with a null character (‘\0′). A null character occupies 1 byte
of memory.

Basic Concepts:
In order to make use of the string handling functions, the header file string.h has
to be included compulsorily.
Strings can be of two different types as:
1. Fixed Size Strings
2. Variable Size Strings
These are further classified as the length controlled and delimeted strings.

Declaration
The string can be declared by making use of the following syntax:
char string_name[size];

Example: char name[20];


The above statement declares an array named “name” capable of holding 20
characters. The 20th character is null character. Hence we can store 19
characters. The 20th character is reserved for null character.

Initialization
The strings can be initialized by making use of the following syntax:
char a*10+ =”Hello hi ”;

Reading Strings
The input to the strings can be given by the user. This is taken by making use of
any of the three different ways:
1. scanf():
This is the standard input function that is used to receive the value from
user. The format specifier for the string is %s. The scanf() function
terminates as it finds the white space.
2. getchar()
This function is used to receive the single character of the string. The syntax
is as shown:
char ch,str[10];
ch=getchar(str);

3. gets()
This the input function used for the strings. It is not formatted input
statement. This function accepts the blank spaces as well as an input. It
terminates only when enter is pressed or EOF occurs.
Syntax: gets(string_name);

Writing Strings
In order to output the values of string,the following three output functions are
used:
1. printf()
This is the standard output function that is used to display the output on
the screen. This function is the formatted output statement.

2. putchar()
This is used to display the single character on the screen. The syntax is as
shown:
putchar(character_variable);

3. puts()
This function is used to display the given string as the output. This is not the
formatted output statement. The syntax is as shown below:
Syntax: puts(string_name);

String Handling Functions:


 The string handling functions are the built in functions included in the
string.h header file.
 These functions are used to perform various operations and manipulations
on the given strings.
 Some of the major strings handling function are as explained in the table
below:
Function
Description Syntax
Name
strupr() This is used to convert strupr(string_name);
the given string into the
upper case.
strlwr() This is used to convert strlwr(string_name);
the given string into the
lower case.
strrev() This is used to reverse strrev(string_name);
the given string.
strlen() This is used to calculate x=strlen(string_name);
the total length of the where x is any integer variable
string. It also counts the
blank spaces in the
string.
strcpy() This is used to copy the strcpy(Destination_string,Source_string);
source string to the
destination string.
strncpy() This is used to copy the strncpy(Destination_string,Source_string,n);
given n characters of the
source string to the
destination string.
strcmp() This is used to compare strcmp(Destination_string,Source_string);
the two strings and it
returns the numeric
value as an answer.
0 – Strings are equal
Positive – String 1 is
greater
Negative – String 2 is
greater
strncmp() This is used to compare strncmp(Destination_string,Source_string,n);
the two strings till the n
characters and it returns
the numeric value as an
answer.
0 – Strings are equal
Positive – String 1 is
greater
Negative – String 2 is
greater
strcat() This is used to join the strcat(Destination_string,Source_string);
source string with
destination string
strncat() This is used to join n strncat(Destination_string,Source_string);
characters of the source
string with destination
string

Character Handling Functions


The character handling functions are used to manipulate the characters and are
used to perform different functions. These functions are built in functions and are
defined in the ctype.h header file.

Function Name Description Syntax


tolower() It converts the character to tolower(character_variable);
lower case.
toupper() It converts the character to toupper(character_variable);
upper case.
isalpha() It checks whether the given isalpha(character_variable);
character is alphabet or not. If
it is alphabet, it returns the
non zero value.
isdigit() It checks whether the given isdigit(character_variable);
character is digit or not. If it is
digit, it returns the non zero
value.
islower() It checks whether the given islower(character_variable);
character is lower case or not.
If it is in the lower case, it
returns the non zero value.
isupper() It checks whether the given isupper(character_variable);
character is in upper case or
not. If it is in upper case, it
returns the non zero value.
isalnum() It checks whether the given isalnum(character_variable);
character is alphanumeric or
not. If it is alphanumeric, it
returns the non zero value.

You might also like