UNIT-1 Introduction To Programming Languages Computer
UNIT-1 Introduction To Programming Languages Computer
UNIT-1
Introduction to Programming Languages
Computer
A computer is a programmable electronic device that accepts data as input and processes it with a set of
instructions (a program) to produce the result as output. Program is a sequence of instruction along with
data.
It is believed that the Analytical Engine was the first computer which was invented by Charles Babbage in
1822. It used punch cards as read-only memory. Charles Babbage is also known as the father of the
computer.
The basic parts without which a computer cannot work are as follows:
o Processor: It executes instructions from software and hardware.
o Memory: It is the primary memory for data transfer between the CPU and storage.
o Motherboard: It is the part that connects all other parts or components of a computer.
o Storage Device: It permanently stores the data, e.g., hard drive.
o Input Device: It allows you to communicate with the computer or to input data, e.g., a keyboard.
o Output Device: It enables you to see the output, e.g., monitor.
Most of us have heard that CPU is called the brain of our computer because it accepts data, provides
temporary memory space to it until it is stored(saved) on the hard disk, performs logical operations on it
and hence processes(here also means converts) data into information. We all know that a computer
consists of hardware and software. Software is a set of programs that performs multiple tasks together. An
operating system is also a software (system software) that helps humans to interact with the computer
system.
Computer Languages
The user of a computer must be able to communicate with it. That means, he must be able to give the
computer commands and understand the output that the computer generates. This is possible due to the
invention of computer languages.
Basically, there are two main categories of computer languages, namely Low Level Language and High Level
Language. Let us take a brief look at both these types of computer languages.
1] Low Level Languages
Low level languages are the basic computer instructions or better known as machine codes. A computer
cannot understand any instruction given to it by the user in English or any other high level language. These
low level languages are very easily understandable by the machine.
The main function of low level languages is to interact with the hardware of the computer. They help in
operating, syncing and managing all the hardware and system components of the computer. They handle all
the instructions which form the architecture of the hardware systems.
Machine Language
This is one of the most basic low level languages. The language was first developed to interact with the first
generation computers. It is written in binary code or machine code, which means it basically comprises of
only two digits – 1 and 0.
Assembly Language
This is the second generation programming language. It is a development on the machine language, where
instead of using only numbers, we use English words, names, and symbols. It is the most basic computer
language necessary for any processor.
2] High Level Language
When we talk about high level languages, these are programming languages. Some prominent examples are
java, php etc. The important feature about such high level languages is that they allow the programmer to
2
write programs for all types of computers and systems. Every instruction in high level language is converted
to machine language for the computer to comprehend.
Scripting Languages
Scripting languages or scripts are essentially programming languages. These languages employ a high level
construct which allows it to interpret and execute one command at a time.
Scripting languages are easier to learn and execute than compiled languages. Some examples are
AppleScript, JavaScript, Pearl etc.
Object-Oriented Languages
These are high level languages that focus on the ‘objects’ rather than the ‘actions’. To accomplish this, the
focus will be on data than logic.
The reasoning behind is that the programmers really cares about the object they wish to manipulate rather
than the logic needed to manipulate them. Some examples include Java, C+, C++, Python, Swift etc.
Procedural Programming Language
This is a type of programming language that has well structured steps and complex procedures within its
programming to compose a complete program.
It has a systematic order functions and commands to complete a task or a program. FORTRAN, ALGOL,
BASIC, COBOL are some examples.
A compiler is a computer program (or a set of programs) that transforms source code written in
a programming language (the source language) into another computer language (the target language),
with the latter often having a binary form known as object code. The most common reason for converting
source code is to create an executable program.
In computer science, an interpreter is a computer program that directly executes, i.e. performs,
instructions written in a programming or scripting language, without previously compiling them into
a machine language program.
Interpreter Vs Compiler
Interpreter Compiler
Translates program one statement at a Scans the entire program and translates it as a
time. whole into machine code.
Interpreters usually take less amount of Compilers usually take a large amount of time
time to analyze the source code. to analyze the source code. However, the
However, the overall execution time is overall execution time is comparatively faster
comparatively slower than compilers. than interpreters.
Programming languages like JavaScript, Programming languages like C, C++, Java use
Python, and Ruby use interpreters. compilers.
Programming Languages
3
Preprocessor Commands: These commands tell the compiler to do preprocessing before doing actual
compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h
file before going to actual compilation.
Functions: are main building blocks of any C Program. Every C Program will have one or more functions
and there is one mandatory function which is called main() function. This function is prefixed with
keyword int which means this function returns an integer value when it exits. This integer value is
returned using return statement.
The C Programming language provides a set of built-in functions. In the above example printf() is a C built-
in function which is used to print anything on the screen.
Variables: are used to hold numbers, strings and complex data for manipulation. You will learn in detail
about variables in C Variable Types.
4
Statements &Expressions: Expressions combine variables and constants to create new values.
Statements are expressions, assignments, function calls, or control flow statements which make up C
programs.
Comments: are used to give additional useful information inside a C Program. All the comments will be
put inside /*...*/ as given in the example above. A comment can span through multiple lines.
Note the followings
• C is a case sensitive programming language. It means in C printf and Printf will have different
meanings.
• C has a free-form line structure. End of each C statement must be marked with a semicolon.
• Multiple statements can be done the same line.
• White Spaces (ie tab space and space bar) are ignored.
• Statements can continue over multiple lines.
Example:
int main()
{
int a;
.
.
Body: Body of a function in C program, refers to the operations that are performed in the functions. It can
be anything like manipulations, searching, sorting, printing, etc.
Example:
int main()
{
int a;
printf("%d", a);
.
.
4. Return Statement: The last part in any C program is the return statement. The return statement refers
to the returning of the values from a function. This return statement and return value depend upon the
return type of the function. For example, if the return type is void, then there will be no return statement.
In any other case, there will be a return statement and the return value will be of the type of the specified
return type.
Example:
int main()
{
int a;
printf("%d", a);
return 0;
}
5. How to execute the above program:
In order to execute the above program, we need to have a compiler to compile and run our programs.
The C character set
The C character set consists of upper and lowercase alphabets, digits, special characters and white
spaces. The alphabets and digits are altogether called as the alphanumeric character. It is of 4 types
• Letters
• Digits
• Special Characters
• White space
Letters
C language comprises the following set of letters to form a standard program. They are:
• A to Z in Capital letters.
• a to z in Small letters.
• In C programming, small letter and caps letter are distinct.(case sensitive)
Digits
C language comprises the following sequence of numbers to associate the letters.
• 0 to 9 digits
6
Special Characters
C language contains the following special character in association with the letters and digits.
Symbol Meaning
~ Tilde
! Exclamation mark
# Number sign
$ Dollar sign
% Percent sign
^ Caret
& Ampersand
* Asterisk
( Left parenthesis
) Right parenthesis
_ Underscore
+ Plus sign
| Vertical bar
\ Backslash
` Apostrophe
- Minus sign
= Equal to sign
{ Left brace
} Right brace
[ Left bracket
] Right bracket
: Colon
" Quotation mark
; Semicolon
< Opening angle bracket
> Closing angle bracket
? Question mark
, Comma
. Period
/ Slash
7
C Keywords
Keywords are predefined; reserved words used in programming that have special meanings to the
compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all keywords
allowed in ANSI C.
C Keywords
Do If Static While
Literals
• Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
• Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are enumeration constants as well.
• Constants are treated just like regular variables except that their values cannot be modified after
their definition.
Constant Definition in C
Syntax:
const type constant_name;
const keyword defines a constant in C.
Example:
#include<stdio.h>
int main()
9
{
int SIDE =10;
int area;
area = SIDE*SIDE;
printf("The area of the square : %d ", area);
return 0;
};
Constant Types in C
Constants are categorized into two basic types, and each of these types has own subtypes/categories.
Primary Constants
1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
Integer Constant
It's referring to a sequence of digits. Integers are of three types viz:
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6
Real constant
The numbers containing fractional parts like 99.25 are called real or floating points constant.
10
\b Backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ Backslash
\0 Null
Strings: -
In C programming, the one-dimensional array of characters are called strings, which is terminated by a null
character ‘\0’.
char name[6 ];
Through pointers.
char*name;
Strings Initialization in C
Example:
char name[6]={'C','l','o','u','d','\0'};
or
char name[]="Cloud";
Memory Representation of Above Defined String in C
Example:
#include<stdio.h>
int main ()
{
char name[6]={'C','l','o','u','d','\0'};
printf("sky%s\n", name );
return 0;
}
Program Output:
skyCloud
Operators: -
C operators are symbols that are used to perform mathematical or logical manipulations. 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.
Types of Operators in C
C offers various types of operators having different functioning capabilities.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Increment and Decrement Operators
• Conditional Operator
• Bitwise Operators
• Special Operators
Arithmetic Operators
Arithmetic Operators are used to performing mathematical calculations like addition (+), subtraction (-),
multiplication (*), division (/) and modulus (%).
12
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
C Program to Add Two Numbers
Example:
#include<stdio.h>
int main()
{
int a,b,c;
a=10;
b=5;
c=a+b;
printf("sum of two numbers is %d",c);
return 0;
}
Increment and Decrement Operators
Increment and Decrement Operators are useful operators generally used to minimize the calculation, i.e.
++x & x++ means x=x+1 or -x & 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 left whereas post-increment first assigns the value to the variable on the left
and then increment the operand.
Operator Description
++ Increment
−− Decrement
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator: ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
EXAMPLE PROGRAM FOR INCREMENT OPERATORS IN C:
In this program, value of “i” is incremented one by one from 1 up to 9 using “i++” operator and output is
displayed as “1 2 3 4 5 6 7 8 9”.
//Example for increment operators
#include <stdio.h>
int main()
{
int i=1;
13
while(i<10)
{
printf("%d ",i);
i++;
}
return 0;
}
OUTPUT:
123456789
EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C:
In this program, value of “I” is decremented one by one from 20 up to 11 using “i–” operator and output is
displayed as “20 19 18 17 16 15 14 13 12 11”.
//Example for decrement operators
#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}
return 0;
}
OUTPUT:
20 19 18 17 16 15 14 13 12 11
DIFFERENCE BETWEEN PRE/POST INCREMENT & DECREMENT OPERATORS IN C:
Below table will explain the difference between pre/post increment and decrement operators in C
programming language.
Operator Operator/Description
{
int i=0;
while(++i<5)
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
1234
• Step 1 : In above program, value of “i” is incremented from 0 to 1 using pre-increment operator.
• Step 2 : This incremented value “1” is compared with 5 in while expression.
• Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “1 2 3 4”.
EXAMPLE PROGRAM FOR POST – INCREMENT OPERATORS IN C:
#include <stdio.h>
int main()
{
int i=0;
while(i++<5)
{
printf("%d ",i);
}
return0;
}
OUTPUT:
12345
• Step 1 : In this program, value of i “0” is compared with 5 in while expression.
• Step 2 : Then, value of “i” is incremented from 0 to 1 using post-increment operator.
• Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “1 2 3 4
5”.
EXAMPLE PROGRAM FOR PRE – DECREMENT OPERATORS IN C:
#include <stdio.h>
intmain()
{
inti=10;
while(--i>5)
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
9876
15
• Step 1 : In above program, value of “i” is decremented from 10 to 9 using pre-decrement operator.
• Step 2 : This decremented value “9” is compared with 5 in while expression.
• Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “9 8 7 6”.
EXAMPLE PROGRAM FOR POST – DECREMENT OPERATORS IN C:
#include <stdio.h>
intmain()
{
inti=10;
while(i-->5)
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
98765
• Step 1 : In this program, value of i “10” is compared with 5 in while expression.
• Step 2 : Then, value of “i” is decremented from 10 to 9 using post-decrement operator.
• Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “9 8 7 6
5”.
Relational Operators
Relational operators are used to compare two quantities or values.
Operator Description
== Is equal to
!= Is not equal to
| Binary OR Operator
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
= Assign
Operator Description
?: Conditional Expression
Special Operators
C supports some special operators
Operator Description
sizeof() Returns the size of a memory location.
* Pointer to a variable.
Program to demonstrate the use of size of operator
Example:
#include<stdio.h>
void main()
{
int i=10;/* Variables Defining and Assign values */
printf("integer: %d\n",sizeof(i));
}
Program Output:
Special characters:
All characters other than alphabets and digits are treated as special characters.
Eg: * , % , $ , { ,etc
Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be changed, and it
can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Let's see the syntax to declare a variable:
1. type variable_name;
The example of declaring the variable is given below:
1. int a;
2. float b;
3. char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
1. int a=10,b=20;//declaring 2 variable of integer type
2. float f=20.8;
3. char c='A';
Rules for defining variables
o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with a digit.
o No whitespace is allowed within the variable name.
18
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.
Valid variable names:
1. int a;
2. int _ab;
3. int a30;
Invalid variable names:
1. int 2;
2. int a b;
3. int long;
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
It must be declared at the start of the block.
void main()
{
int x=10;//local variable
}
You must have to initialize the local variable before it is used.
Global Variable
A variable that is declared outside the function or block is called a global variable. Any function can
change the value of the global variable. It is available to all the functions.
It must be declared at the start of the block.
int value=20;//global variable
void main()
{
int x=10;//local variable
}
Static Variable
A variable that is declared with the keyword is called static variable.
It retains its value between multiple function calls.
int main(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
return 0;
}
If you call this function many times, the local variable will print the same value for each function
call, e.g, 11,11,11 and so on. But the static variable will print the incremented value in each
function call, e.g. 11, 12, 13 and so on.
19
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We can
explicitly declare an automatic variable using auto keyword.
void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
External Variable
We can share a variable in multiple C source files by using an external variable. To declare an external
variable, you need to use extern keyword.
myfile.h
extern int x=10;//external variable (also global)
program1.c
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
Expressions in C:-
L values and R values in C
There are two kinds of expressions in C −
• L value − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue
may appear as either the left-hand or right-hand side of an assignment.
• R value − The term rvalue refers to a data value that is stored at some address in memory. An rvalue
is an expression that cannot have a value assigned to it which means an rvalue may appear on the
right-hand side but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are
rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the
following valid and invalid statements −
int g = 20; // valid statement
10 = 20; // invalid statement; would generate compile-time error
Input and Output Operations
When we say Input, it means to feed some data into a program. An input can be given in the form of a file
or from the command line. C programming provides a set of built-in functions to read the given input and
feed it to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C programming
provides a set of built-in functions to output the data on the computer screen as well as to save it in text
or binary files.
The Standard Files
C programming treats all the devices as files. So devices such as the display are addressed in the same way
as files and the following three files are automatically opened when a program executes to provide access
to the keyboard and screen.
Standard File File Pointer Device
The int printf(const char *format, ...) function writes the output to the standard output
stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read
strings, integer, character or float respectively. There are many other formatting options available which
can be used based on requirements. Let us now proceed with a simple example to understand the concepts
better −
#include<stdio.h>
intmain(){
charstr[100];
inti;
printf("Enter a value :");
scanf("%s %d", str,&i);
printf("\nYou entered: %s %d ", str,i);
return0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then program proceeds and reads the input and displays it as follows −
$./[Link]
Enter a value : seven 7
You entered: seven 7
Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which
means you have to provide valid inputs like "string integer". If you provide "string string" or "integer
integer", then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as
soon as it encounters a space, so "this is test" are three strings for scanf().
Compilation and pre-processing
A compiler is a computer program (or a set of programs) that transforms source code written in
a programming language (the source language) into another computer language (the target language),
with the latter often having a binary form known as object code. The most common reason for converting
source code is to create an executable program.
The name "compiler" is primarily used for programs that translate source code from a high-level
programming language to a lower level language (e.g., assembly language or machine code). If the
compiled program can run on a computer whose CPU or operating system is different from the one on
which the compiler runs, the compiler is known as a cross-compiler. More generally, compilers are a
specific type of translator.
A Preprocessor is a system software (a computer program that is designed to run on computer’s
hardware and application programs). It performs preprocessing of the High Level Language(HLL).
Preprocessing is the first step of the language processing system. Language processing system translates
the high-level language to machine level language or absolute machine code(i.e. to the form that can be
understood by machine).
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In
simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required
pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for
readability, a preprocessor directive should begin in the first column. The following section lists down all
the important preprocessor directives −
[Link]. Directive & Description
1 #define
22
Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:
Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short 1 -128 to 127
int
unsigned short int 1 0 to 255
long int or signed long 4 -2,147,483,648 to
int 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Floating point type
Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
Float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
Void type
void type means no value. This is usually used to specify the type of functions which returns nothing. We
will get acquainted to this datatype as we start learning more advanced topics in C language, like
functions, pointers etc.
24
→ For more details of const keyword and constant variables in C refer to C Constants.
Syntax
Long a;-->bydefault which represent long int.
short
In general int data type occupies different memory spaces for a different operating system; to allocate
fixed memory space short keyword can be used.
Syntax
Short int a;--> occupies 2 bytes of memory space in every operating system.
unsigned
This keyword can be used to make the accepting values of a data type is positive data type.
Syntax
Unsigned int a =100; // right
Unsigned int a=-100; // wrong
Signed
This keyword accepts both negative or positive value and this is default properties or data type
modifiers for every data type.
Example
int a=10; // right
int a=-10; // right
signedint a=10; // right
signedint a=-10; // right
Note: in real time no need to write signed keyword explicitly for any data type.
Operators: -
C operators are symbols that are used to perform mathematical or logical manipulations. 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.
Types of Operators in C
C offers various types of operators having different functioning capabilities.
• Arithmetic Operators
26
• Relational Operators
• Logical Operators
• Assignment Operators
• Increment and Decrement Operators
• Conditional Operator
• Bitwise Operators
• Special Operators
Arithmetic Operators
Arithmetic Operators are used to performing mathematical calculations like addition (+), subtraction (-),
multiplication (*), division (/) and modulus (%).
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
C Program to Add Two Numbers
Example:
#include<stdio.h>
voidmain()
{
inti=3,j=7,k;/* Variables Defining and Assign values */ k=i+j;
printf("sum of two numbers is %d\n", k);
}
Increment and Decrement Operators
Increment and Decrement Operators are useful operators generally used to minimize the
calculation, i.e. ++x & x++ means x=x+1 or -x & 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 left whereas post-increment first assigns the value to
the variable on the left and then increment the operand.
Operator Description
++ Increment
−− Decrement
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
EXAMPLE PROGRAM FOR INCREMENT OPERATORS IN C:
27
In this program, value of “i” is incremented one by one from 1 up to 9 using “i++” operator and output is
displayed as “1 2 3 4 5 6 7 8 9”.
//Example for increment operators
#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
OUTPUT:
123456789
EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C:
In this program, value of “I” is decremented one by one from 20 up to 11 using “i–” operator and output is
displayed as “20 19 18 17 16 15 14 13 12 11”.
//Example for decrement operators
#include <stdio.h>
int tmain()
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}
OUTPUT:
20 19 18 17 16 15 14 13 12 11
DIFFERENCE BETWEEN PRE/POST INCREMENT & DECREMENT OPERATORS IN C:
Below table will explain the difference between pre/post increment and decrement operators in C
programming language.
Operator Operator/Description
Pre increment operator value of i is incremented before assigning
(++i) it to the variable i
Post increment operator value of i is incremented after assigning it
(i++) to the variable i
Pre decrement operator (– value of i is decremented before assigning
i) it to the variable i
Post decrement operator value of i is decremented after assigning it
(i–) to variable i
28
OUTPUT:
9876
• Step 1 : In above program, value of “i” is decremented from 10 to 9 using pre-decrement operator.
• Step 2 : This decremented value “9” is compared with 5 in while expression.
• Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “9 8 7 6”.
EXAMPLE PROGRAM FOR POST – DECREMENT OPERATORS IN C:
#include <stdio.h>
int main()
{
inti=10;
while(i-->5)
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
98765
• Step 1 : In this program, value of i “10” is compared with 5 in while expression.
• Step 2 : Then, value of “i” is decremented from 10 to 9 using post-decrement operator.
• Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “9 8 7 6
5”.
Relational Operators
Relational operators are used to compare two quantities or values.
Operator Description
== Is equal to
!= Is not equal to
| Binary OR Operator
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
= Assign
2. increment (++)
3. decrement (- -)
4. NOT(!)
5. Addressof operator (&)
6. Size of ()
1. unary minus
The minus operator changes the sign of its argument. A positive number becomes negative, and a
negative number becomes positive.
int a = 10;
int b = -a; // b = -10
unary minus is different from subtraction operator, as subtraction requires two operands.
2. increment
It is used to increment the value of the variable by 1. The increment can be done in two ways:
Binary Operator
A binary operator is an operator that operates on two operands and manipulates them to return a result.
Operators are represented by special characters or by keywords and provide an easy way to compare
numerical values or character strings.
Some common binary operators in computing include:
• Equal (==)
• Not equal (!=)
• Less than (<)
• Greater than (>)
• Greater than or equal to (>=)
• Less than or equal to (<=)
• Logical AND (&&)
• Logical OR (||)
• Plus (+)
• Minus (-)
• Multiplication (*)
• Divide (/)
Equal (==) and not-equal (!=) are called equality operators. They produce a result of true (or 1) or false
(or 0). This type of operator returns "true" if both operands have the same value, or "false" if they don’t
have the same value.
For example, the following conditional operation will be performed if the operands are equal:
if(operand1 == operand2)
{
//do the operation
}
Greater than (>), less than (<), greater than or equal to (>=) and less than or equal to (<=) are relation
operators, which compare two operands and produce a result of either true or false. When two operands
are compared, the result depends on the relative location of the two operands.
Logical AND (&&) and logical OR (||) are called logical operators. They compare operands and return a
result of either true (1) or false (0). In logical AND, if both operands are true then the result is true. If
either one of the operands is false, the result will be false. In logical OR, if both operands are true or either
one of the operands is true then the result is true. If both operands are false then the result will be false.
32
Ternary Operator
C offers a ternary operator which is the conditional operator (?: in combination) to construct conditional
expressions.
Operator Description
?: Conditional Expression
Special Operators
C supports some special operators
Operator Description
sizeof() Returns the size of a memory location.
* Pointer to a variable.
C Expressions
An expression is a formula in which operands are linked to each other by the use of operators to compute
a value. An operand can be a function reference, a variable, an array element or a constant.
Let's see an example:
a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
There are four types of expressions exist in C:
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of operators. Evaluation of
a particular expression produces a specific value.
For example:
1. x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is an expression.
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic operators. An
arithmetic expression computes a value of type int, float or double.
When an expression contains only integral operands, then it is known as pure integer expression when it
contains only real operands, it is known as pure real expression, and when it contains both integral and
real operands, it is known as mixed mode expression.
Evaluation of Arithmetic Expressions
The expressions are evaluated by performing one operation at a time. The precedence and associativity
of operators decide the order of the evaluation of individual operations.
When individual operations are performed, the following cases can be happened:
33
o When both the operands are of type integer, then arithmetic will be performed, and the result of
the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the fractional part
is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the result of the
operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed arithmetic
will be performed. In this case, the first operand is converted into a real operand, and then
arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first
value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.
Let's understand through an example.
6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)
Evaluation of expression Description of each operation
x%2 = = 0 This condition is used to check whether the x is an even number or not. The
relational expression results in value 1 if x is an even number otherwise
results in value 0.
a+b = = x+y It is used to check whether the expression "a+b" is equal to the expression
"x+y".
int x=4;
if(x%2==0)
{
printf("The number x is even");
}
else
printf("The number x is not even");
return 0;
}
Output
Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero value.
o It is a complex test condition to take a decision.
Let's see some example of the logical expressions.
Logical Description
Expressions
( x> 4 ) && ( x It is a test condition to check whether the x is greater than 4 and x is
<6) less than 6. The result of the condition is true only when both the
conditions are true.
! ( x> 10 ) && ( It is a test condition used to check whether x is not greater than 10
y==2) and y is equal to 2. The result of the condition is true if both the
conditions are true.
Let's see a simple program of "&&" operator.
#include <stdio.h>
int main()
35
{
int x = 4;
int y = 10;
if ( (x <10) && (y>5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Output
Conditional Expressions
o A conditional expression is an expression that returns 1 if the condition is true otherwise 0.
o A conditional operator is also known as a ternary operator.
The Syntax of Conditional operator
Suppose exp1, exp2 and exp3 are three expressions.
exp1 ? exp2 : exp3
36
The above expression is a conditional expression which is evaluated on the basis of the value of the exp1
expression. If the condition of the expression exp1 holds true, then the final conditional expression is
represented by exp2 otherwise represented by exp3.
Let's understand through a simple example.
#include<stdio.h>
#include<string.h>
int main()
{
int age = 25;
char status;
status = (age>22) ? 'M': 'U';
if(status == 'M')
printf("Married");
else
printf("Unmarried");
return 0;
}
Output
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than
+, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom. Within an expression, higher precedence operators will be evaluated first.
‘C’ language processes decision making capabilities supports the flowing statements known as control
or decision-making statements
1. If statement
2. Switch statement
3. Conditional operator statement
4. Go to statement
If Statement: The if statement is powerful decision-making statement and is used to control the flow of
execution of statements. The If statement may be complexity of conditions to be tested
(a)Simple if statement
(b)If else statement
(c)Nested If-else statement
( d)Else –If ladder
if Statement:
The simplest form of the control statement is the If statement. It is very frequently used in decision
making and allowing the flow of program execution.
The If structure has the following syntax
If (condition)
{
Statement;
}
The statement is any valid C’ language statement and the condition is any valid C’ language expression,
frequently logical operators are used in the condition statement. The condition part should not end with a
semicolon, since the condition and statement should be put together as a single statement. The command
says if the condition is true then performs the following statement or if the condition is fake the computer
skips the statement and moves on to the next instruction in the program.
Example program
# include <stdio.h>
int main ()
{
int number;
printf ("Type a number:");
scanf ("%d", &number);
if (number < 0)
{
number = -number ;
printf ("The absolute value is %d \n", number);
}
return 0;
}
The above program checks the value of the input number to see if it is less than zero. If it is then the
following program statement which negates the value of the number is executed. If the value of the
number is not less than zero, we do not want to negate it then this statement is automatically skipped.
The absolute number is then displayed by the program, and program execution ends.
The If else construct:
The syntax of the If else construct is as follows: -
39
if (condition)
{
Statement1;
}
Else
{
Statement2;
}
The if else is actually just on extension of the general format of if statement. If the result of the condition
is true, then program statement 1 is executed, otherwise program statement 2 will be executed. If any
case either program statement 1 is executed or program statement 2 is executed but not both when
writing programs this else statement is so frequently required that almost all programming languages
provide a special construct to handle this situation.
Sample Code
#include <stdio.h> //include the stdio.h header file in your program
void main () // start of the main
{
int num ; // declare variable num as integer
printf ("Enter the number") ; // message to the user
scanf ("%d", &num) ; // read the input number from keyboard
if (num < 0) // check whether number is less than zero
{
printf ("The number is negative") ; // if it is less than zero then it is negative
}
else // else statement
{
printf ("The number is positive") // if it is more than zero then the given number is positive
}
}
In the above program the If statement checks whether the given number is less than 0. If it is less than
zero then it is negative therefore the condition becomes true then the statement The number is negative
is executed. If the number is not less than zero the If else construct skips the first statement and prints
the second statement declaring that the number is positive.
Nested if Statement
The if statement may itself contain another if statement is known as nested if statement.
Syntax:-if (condition1)
if (condition2)
statement-1;
else
statement-2;
else
statement-3;
40
The if statement may be nested as deeply as you need to nest it. One block of code will only be executed
if two conditions are true. Condition 1 is tested first and then condition 2 is tested. The second if
condition is nested in the first. The second if condition is tested only when the first condition is true else
the program flow will skip to the corresponding else statement.
Sample Code
#include <stdio.h>
int main()
{
int m=40,n=20;
if(m>n)
{
printf("m is greater than n");
}
else if(m<n)
{
printf("m is less than n");
}
else
{
printf("m is equal to n");
}
return 0;
}
OUTPUT:
m is greater than n
Example:
#include<stdio.h>
int main()
{
int a, b;
printf("Please enter the value for a:");
scanf("%d", &a);
printf("\nPlease enter the value for b:");
scanf("%d", & b);
if (a > b)
{
printf("\n a is greater than b");
}
else if (b > a)
{
printf("\n b is greater than a");
}
else
{
printf("\n Both are equal");
}
return 0;
}
41
Sample Code
#include <stdio.h> //Includes stdio.h file to your program
void main () // start of the program
{
int year, rem_4, rem_100, rem_400; // variable declaration
printf ("Enter the year to be tested"); // message for user
scanf ("%d", &year) ;// Read the year from standard input.
rem_4 = year % 4 ;//find the remainder of year by 4
rem_100 = year % 100; //find the remainder of year by 100
rem_400 = year % 400 ;//find the remainder of year by 400
if ((rem_4 == 0 && rem_100 != 0) rem_400 == 0)
//apply if condition 5 check whether remainder is zer
printf ("It is a leap year. \n") ;// print true condition
else
printf ("No. It is not a leap year. \n") ;//print the false condition
}
#include <stdio.h>
int main()
{
int year;
/*
* Input year from user
*/
printf("Enter any year: ");
scanf("%d",&year);
/*
* If year%4==0 and year%100==0 then
* print leap year
* else if year%400==0 then
* print leap year
* else
* print common year
*/
(year%4==0&& year%100!=0)?printf("LEAP YEAR"):
(year%400==0)?printf("LEAP YEAR"):printf("COMMON YEAR");
return 0;
}
The ELSE If Ladder
When a series of many conditions have to be checked we may use the ladder else if statement which
takes the following general form.
Syntax:-if (condition1)
statement – 1;
else if (condition2)
statement2;
42
else if (condition3)
statement3;
else if (condition)
statement n;
else
default statement;
statement-x;
This construct is known as if else construct or ladder. The conditions are evaluated from the top of the ladder to
downwards. As soon on the true condition is found, the statement associated with it is executed and the control is
transferred to the statement– x (skipping the rest of the ladder. When all the condition becomes false, the final else
containing the default statement will be executed.
* Example program using If else ladder to grade the student according to the following rules.
Marks
Grade
70 to 100 DISTINCTION
60 to 69 IST CLASS
50 to 59 IIND CLASS
40 to 49 PASS CLASS
0 to 39 FAIL
Sample Code
#include <stdio.h> //include the standard stdio.h header fil
int main () //start the function main
{
int marks; //variable declaration
printf ("Enter marks\n"); //message to the user
scanf ("%d", &marks); //read and store the input marks.
if (marks <= 100 && marks >= 70) //check whether marks is less than 100 or greater than 70
{
printf ("\n Distinction") ; //print Distinction if condition is True
}
else if (marks >= 60) //else if the previous condition fails Chec
{
printf("\n First class"); //whether marks is > 60 if true print Statement
}
else if (marks >= 50) //else if marks is greater than 50 prin
{
printf ("\n second class"); //Second class
}
else if (marks >= 39) //else if marks is greater than 39 print
{
printf ("\n pass class"); //pass class
}
43
else
{
printf ("Fail"); //If all condition fail apply default condition print Fail
}
}
return 0;
}
The Switch Statement:
Unlike the If statement which allows a selection of two alternatives the switch statement allows a
program to select one statement for execution out of a set of alternatives. During the execution of the
switch statement only one of the possible statements will be executed the remaining statements will be
skipped. The usage of multiple If else statement increases the complexity of the program since when the
number of If else statements increase it affects the readability of the program and makes it difficult to
follow the program. The switch statement removes these disadvantages by using a simple and straight
forward approach.
The general format of the Switch Statement is: -
When the switch statement is executed the control expression is evaluated first and the value is
compared with the case label values in the given order. If the label matches with the value of the
expression, then the control is transferred directly to the group of statements which follow the label. If
none of the statements matches then the statement against the default is executed. The default statement
is optional in switch statement in case if any default statement is not given and if none of the condition
matches then no action takes place in this case the control transfers to the next statement of the if else
statement.
Switch (expression)
{
Case case-label-1;
Case case-label-2;
Case case-label-n;
………………
Case default
}
Sample Code
#include<stdio.h>
int main ()
{
/* local variable definition */
char grade ='B';
switch(grade)
{
case'A':
printf("Excellent!\n");
break;
case'B':
case'C':
printf("Well done\n");
break;
case'D':
printf("You passed\n");
break;
44
case'F':
printf("Better try again\n");
break;
default:
printf("Invalid grade\n");
}
printf("Your grade is %c\n", grade );
return0;
}
When the above code is compiled and executed, it produces the following result
Well done
Your grade is B
Sample Code
#include <stdio.h>
int main ()
{
int num1, num2, result ;
char operator ;
printf ("Enter two numbers") ;
scanf ("%d %d", &num1, &num2) ;
printf ("Enter an operator") ;
scanf ("%c", &operator) ;
switch (operator)
{
case '+':
result = num1 + num2 ;
break;
case '-':
result = num1 - num2 ;
break ;
case '*':
result = num1 * num2 ;
break ;
case '/':
if (num2 != 0)
result = num1 / num2 ;
else
{
printf ("warning : division by zero \n") ;
result = 0 ;
}
break ;
default:
printf ("\n unknown operator") ;
result = 0 ;
break ;
}
printf ("%d", result) ;
45
return 0;
}
In the above program the break statement is need after the case statement break out of the loop and
prevent the program from executing other cases.
The GOTO statement:
The goto statement is an unconditional branch. The result of the goto statement is a change in the flow of
control to the first statement after the label specified in the goto statement.
A label is an identifier followed by a colon. A label must appear in the same function as the goto statement
that refers to it. Using goto statement in C programming language is considered as poor programming
approach
Syntax
The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program above or
below to goto statement.
Goto Statement Example
The program below uses goto statements to loop ten times and print the counter value each time.
After initializing count to 1, the if condition tests count to determine whether it’s greater than 10 (the label
start: is skipped because labels do not perform any action). If so, control is transferred from the goto to the
first statement after the label end.
// Using the goto statement
#include<stdio.h>
int main( )
{
int a = 1; // initialize count
start: // label
if ( a>10 )
{
goto end;
} // end if
printf( "%d ", a );
++a;
goto start; // goto start on line 9
end: // label
putchar( '\n' );
} // end main
Output:
12345678910
C Ternary Operator (?:)
A conditional operator is a ternary operator, that is, it works on 3 operands.
Conditional Operator Syntax
conditionalExpression ? expression1 : expression2
The conditional operator works as follows:
The first expression conditionalExpression is evaluated first. This expression evaluates to 1 if it's true
and evaluates to 0 if it's false.
If conditionalExpression is true, expression1 is evaluated.
46
Unit-2
Decision making and Loops:-
In every programming language, thus also in the C programming language, there are
circumstances were you want to do the same thing many times. For instance you want to
print the same words ten times. You could type ten printf function, but it is easier to use a
loop. The only thing you have to do is to setup a loop that execute the same printf function
ten times.
There are three basic types of loops which are:
▪ “for loop”
▪ “while loop”
▪ “do while loop”
printf ("World\n");
}
return 0;
}
Note: A single instruction can be placed behind the “for loop” without the curl brackets.
Let’s look at the “for loop” from the example: We first start by setting the variable i to
0. This is where we start to count. Then we say that the for loop must run if the counter
i is smaller then ten. Last we say that every cycle i must be increased by one (i++).
In the example we used i++ which is the same as using i = i + 1. This is called
incrementing. The instruction i++ adds 1 to i. If you want to subtract 1 from i you can use
i--. It is also possible to use ++i or --i. The difference is is that with ++i (prefix
incrementing) the one is added before the “for loop” tests if i < 10. With i++ (postfix
incrementing) the one is added after the test i < 10. In case of a for loop this make no
difference, but in while loop test it makes a difference. But before we look at a postfix
and prefix increment while loop example, we first look at the while loop.
The while loop
The while loop can be used if you don’t know how many times a loop must run. Here is
an example:
#include<stdio.h>
int main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
while ( counter < howmuch)
{
counter++;
printf("%d\n", counter);
}
return 0;
}
Let’s take a look at the example: First you must always initialize the counter before the
while loop starts ( counter = 1). Then the while loop will run if the variable counter is
smaller then the variable “howmuch”. If the input is ten, then 1 through 10 will be printed
on the screen. A last thing you have to remember is to increment the counter inside the
loop (counter++). If you forget this the loop becomes infinitive.
48
As said before (after the for loop example) it makes a difference if prefix
incrementing (++i) or postfix incrementing (i++) is used with while loop. Take a look at
the following postfix and prefix increment while loop example:
#include<stdio.h>
int main()
{
int i;
i = 0;
while(i++ < 5)
{
printf("%d\n", i);
}
printf("\n");
i = 0;
while(++i < 5)
{
printf("%d\n", i);
}
return 0;
}
The output of the postfix and prefix increment example will look like this:
1
2
3
4
5
1
2
3
4
i++ will increment the value of i, but is using the pre-incremented value to test against
< 5. That’s why we get 5 numbers.
++i will increment the value of i, but is using the incremented value to test against < 5.
That’s why we get 4 numbers.
49
do
{
do something;
}
while (expression);
Do something first and then test if we have to continue. The result is that the loop
always runs once. (Because the expression test comes afterward). Take a look at an
example:
#include<stdio.h>
int main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
do
{
counter++;
printf("%d\n", counter);
}
while ( counter < howmuch);
return 0;
}
Output:
Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3
While vs do..while loop in C
#include <stdio.h>
int main()
{
int i=0;
while(i==1)
{
printf("while vs do-while");
}
printf("Out of loop");
}
Output:
Out of loop
Same example using do-while loop
#include <stdio.h>
int main()
{
int i=0;
do
{
printf("while vs do-while\n");
}while(i==1);
printf("Out of loop");
}
Output:
while vs do-while
Out of loop
51
• break statement
• continue statement
Break statement
When break statement is meet inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop. The break
statement terminates the loop (for, while and do...while loop) immediately when it is
meet. The break statement is used with decision making statement such as if...else.
Syntax of break statement
break;
i++;
if ( i == 10)
break;
}
return 0;
}
Example -2
#include<stdio.h>
int main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
return 0;
}
Continue statement
It causes the control to go directly to the test-condition and then continue the loop
process. On encountering continue, cursor leave the current cycle of loop, and starts with
the next cycle.
Continue Statement
The continue statement skips some statements inside the loop. The continue statement is
used with decision making statement such as if...else.
Syntax of continue Statement
continue;
#include <stdio.h>
53
int main()
{
int a[10] = {-1, 2, -3, 4, -5, 6, -7, 8, -9, 10};
int i, sum = 0;
for (i = 0; i < 10; i++)
{
if (a[i] < 0) /* skip negative elements */
continue;
sum += a[i]; /* sum positive elements */
}
printf("Sum of positive elements: %d\n", sum);
}
OUTPUT
Sum of positive elements: 30
#include<stdio.h>
int main()
{
int i;
i = 0;
while ( i < 20 )
{
i++;
continue;
printf("Nothing to see\n");
}
return 0;
}
Array:-
C Array is a collection of variables belongings to the same data type. You can store group
of data of same data type in an array.
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
54
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and
..., numbers[99] to represent individual variables. A specific element in an array is
accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows
−
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
55
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays
have 0 as the index of their first element which is also called the base index and the last
index of an array will be total size of the array minus 1. Shown below is the pictorial
representation of the array we discussed above −
#include <stdio.h>
int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result –
Element[0] = 100
Element[1] = 101
Element[2] = 102
56
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Arrays in Detail
Arrays are important to C and should need a lot more attention. The following
important concepts related to array should be clear to a C programmer
S.N. Concept & Description
1 Multi-dimensional arrays
C supports multidimensional arrays. The simplest form of the multidimensional
array is the two-dimensional array.
4 Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the
array name, without any index.
TYPES OF C ARRAYS:
There are 4 types of C arrays. They are,
Array
declaration Array initialization Accessing array
57
age[0];_/*0_is_accessed*/age[1];_/
int age[5]={0, 1, 2, 3, *1_is_accessed*/age[2];_/*2_is_acc
int age [5]; 4}; essed*/
char str[10]={‘H’,‘a’,‘i’}
; (or)char str[0] =
‘H’;char str[1] = ‘a’; str[0];_/*H is accessed*/str[1]; /*a
is accessed*/str[2]; /* i is
char str[10]; char str[2] = ‘i; accessed*/
value of arr[0] is 10
58
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
2. TWO DIMENSIONAL ARRAY IN C:
• Two dimensional array is nothing but array of array.
• syntax : data_type array_name[num_of_rows][num_of_column]
S. Accessing
no Array declaration Array initialization array
The following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array containing
the string is one more than the number of characters in the word "Hello."
Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try
to print the above mentioned string −
#include <stdio.h>
60
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings -
S.N. Function & Purpose
1 strcpy(s1, s2);
2 strcat(s1, s2);
3 strlen(s1);
4 strcmp(s1, s2);
5 strchr(s1, ch);
6 strstr(s1, s2);
#include <stdio.h>
61
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
When the above code is compiled and executed, it produces the following result
strcpy( str3, str1) : Hello
strcat( str1, str2): Hello World
strlen(str1) : 11
Arrays are closely related to pointers in C programming but the important difference
between them is that, a pointer variable takes different addresses as value whereas, in
case of array it is fixed.
#include <stdio.h>
int main()
{
char charArr[4];
int i;
for(i = 0; i < 4; ++i)
{
printf("Address of charArr[%d] = %u\n", i, &charArr[i]);
}
62
return 0;
}
Address of charArr[0] = 28ff44
Address of charArr[1] = 28ff45
Address of charArr[2] = 28ff46
Address of charArr[3] = 28ff47
Note: You may get different address of an array.
Notice, that there is an equal difference (difference of 1 byte) between any two
consecutive elements of array charArr.
But, since pointers just point at the location of another variable, it can store any address.
Relation between Arrays and Pointers
Consider an array:
int arr[4];
In C programming, name of the array always points to address of the first element of an
array.
In the above example, arr and &arr[0] points to the address of the first element.
&arr[0] is equivalent to arr
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,
In C, you can declare an array and can use pointer to alter the data of an array.
Array of pointers
Before we understand the concept of arrays of pointers, let us consider the following
example, which uses an array of 3 integers −
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result Value of
var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
There may be a situation when we want to maintain an array, which can store pointers to
an int or char or any other data type available. Following is the declaration of an array of
pointers to an integer −
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a
pointer to an int value. The following example uses three integers, which are stored in an
array of pointers, as follows −
#include <stdio.h>
int main () {
64
return 0;
}
When the above code is compiled and executed, it produces the following result
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
You can also use an array of pointers to character to store a list of strings as follows −
#include <stdio.h>
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i = 0;
return 0;
}
65
When the above code is compiled and executed, it produces the following result
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
Limitations of arrays
We have seen that we can use arrays whenever we have to store and manipulate
collections of elements. However, the use of arrays for this purpose presents several
limitations related to the way arrays are handled in Java:
• the dimension of an array is determined the moment the array is created, and
cannot be changed later on;
• the array occupies an amount of memory that is proportional to its size,
independently of the number of elements that are actually of interest;
• if we want to keep the elements of the collection ordered, and insert a new value in
its correct position, or remove it, then, for each such operation we may need to
move many elements (on the average, half of the elements of the array); this is very
inefficient.
Concept of Pointers
The Pointer in C, is a variable that stores address of another variable. A pointer can also
be used to refer to another pointer function. A pointer can be incremented/decremented,
i.e., to point to the next/ previous memory location. The purpose of pointer is to save
memory space and achieve faster execution time.
Pointer Variable
int *y = &v;
VARIABLE POINTER
A value stored in A variable that points to the
a named storage/memory address storage/memory address
of another variable
Declaring a Pointer
Like variables, pointers in C programming have to be declared before they can be used in
your program. Pointers can be named anything you want as long as they obey C's naming
rules. A pointer declaration has the following form.
66
data_type * pointer_variable_name;
Here,
• data_type is the pointer's base type of C's variable types and indicates the type of
the variable that the pointer points to.
The asterisk (*: the same asterisk used for multiplication) which is indirection
operator, declares a pointer.
After declaring a pointer, we initialize it like standard variables with a variable address. If
pointers in C programming are not uninitialized and used in the program, the results are
unpredictable and potentially disastrous.
To get the address of a variable, we use the ampersand (&)operator, placed before the
name of a variable whose address we need. Pointer initialization is done with the
following syntax.
Pointer Syntax
pointer = &variable;
#include <stdio.h>
int main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf("Address stored in a variable p is:%x\n",p); //accessing the address
printf("Value stored in a variable p is:%d\n",*p); //accessing the value
return 0;
67
Output:
Null Pointer
We can create a null pointer by assigning null value during the pointer declaration. This
method is useful when you do not have any address assigned to the pointer. A null pointer
always contains value 0.
#include <stdio.h>
int main()
{
int *p = NULL; //null pointer
printf(“The value inside variable p is:\n%x”,p);
return 0;
}
68
Output:
A pointer is said to be a wild pointer if it is not being initialized to anything. These types of
C pointers are not efficient because they may point to some unknown memory location
which may cause problems in our program and it may lead to crashing of the program.
One should always be careful while working with wild pointers.
#include <stdio.h>
int main()
{
int *p; //wild pointer
printf("\n%d",*p);
return 0;
}
Output
ptr = NULL;
}
2. Function Call
// The pointer pointing to local variable becomes
// dangling when local variable is not static.
#include<stdio.h>
int *fun()
{
// x is local variable and goes out of
// scope after an execution of fun() is
// over.
int x = 5;
return &x;
}
// Driver Code
int main()
{
int *p = fun();
fflush(stdin);
int *fun()
{
// x now has scope throughout the program
static int x = 5;
return &x;
}
int main()
70
{
int *p = fun();
fflush(stdin);
// Not a dangling pointer as it points
// to static variable.
printf("%d",*p);
}
Output:
5
Variable goes out of scope
void main()
{
int *ptr;
.....
.....
{
int ch;
ptr = &ch;
}
.....
// Here ptr is dangling pointer
}
Generic pointer
A void pointer is a special pointer that can point to object of any type. A void pointer is
typeless pointer also known as generic pointer. Void pointer is an approach
towards generic functions and generic programming in C.
Void pointer is a specific pointer type – void * – a pointer that points to some data location
in storage, which doesn’t have any specific type. Void refers to the type. Basically the type
of data that it points to is can be any. If we assign address of char data type to void pointer
it will become char Pointer, if int data type then int pointer and so on. Any pointer type is
convertible to a void pointer hence it can point to any value.
Important Points
1. void pointers cannot be dereferenced. It can however be done using typecasting the
void pointer
2. Pointer arithmetic is not possible on pointers of void due to lack of concrete value and
thus size.
Example:
#include<stdlib.h>
int main()
71
{
int x = 4;
float y = 5.5;
//A void pointer
void *ptr;
ptr = &x;
// (int*)ptr - does type casting of void
// *((int*)ptr) dereferences the typecasted
// void pointer variable.
printf("Integer variable is = %d", *( (int*) ptr) );
// void pointer is now float
ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr) );
return 0;
}
Output:
Integer variable is = 4
Float variable is= 5.500000
printf(
"Address of variable x = %p", &x);
return 0;
}
Output:
Address of variable x = 0x7fff3b690fd4
Accessing the Address of a Variable
We can access the value of another variable using the pointer variable
Steps:
Example:
Here, we have declared a normal integer variable num and pointer variable ptr, ptr is
being initialized with the address of num and finally getting the value of num using
pointer variable ptr.
#include <stdio.h>
int main(void)
{
//normal variable
int num = 100;
//pointer variable
int *ptr;
//pointer initialization
ptr = #
//pritning the value
printf("value of num = %d\n", *ptr);
return 0;
}
Output
Pointer declaration is similar to other type of variable except asterisk (*) character before
pointer variable name.
• ptr is the name of pointer variable (name of the memory blocks in which address of
another variable is going to be stored).
• The character asterisk (*) tells to the compiler that the identifier ptr should be
declare as pointer.
• The data type int tells to the compiler that pointer ptr will store memory address of
integer type variable.
Finally, ptr will be declared as integer pointer which will store address of integer type
variable.
Pointer initialization
Pointer ptr is declared, but it not pointing to anything; now pointer should be initialized
by the address of another integer variable.
int x;
int *ptr;
ptr=&x;
Here, x is an integer variable and pointer ptr is initiating with the address of x.
Accessing address and value of x using pointer variable ptr
We can get the value of ptr which is the address of x (an integer variable)
#include <stdio.h>
int main()
{
int x=20; //int variable
74
Pointer arithmetic
A pointer in c is an address, which is a numeric value. Therefore, you can perform
arithmetic operations on a pointer just as you can on a numeric value. There are four
arithmetic operators that can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which
points to the address 1000. Assuming 32-bit integers, let us perform the following
arithmetic operation on the pointer −
ptr++
After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without
impacting the actual value at the memory location. If ptr points to a character whose
address is 1000, then the above operation will point to the location 1001 because the next
character will be available at 1001.
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer
can be incremented, unlike the array name which cannot be incremented because it is a
constant pointer. The following program increments the variable pointer to access each
succeeding element of the array −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %x\n", i, ptr );
75
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2
point to variables that are related to each other, such as elements of the same array, then
p1 and p2 can be meaningfully compared.
The following program modifies the previous example − one by incrementing the variable
pointer so long as the address to which it points is either less than or equal to the address
of the last element of the array, which is &var[MAX - 1] −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have address of the first element in pointer */
ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] ) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* point to the next location */
ptr++;
i++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result
Address of var[0] = bfdbcb20
Value of var[0] = 10
Address of var[1] = bfdbcb24
Value of var[1] = 100
Address of var[2] = bfdbcb28
Value of var[2] = 200
77
Unit-3
Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of a
variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register
extern RAM Zero Global Till the end of the main program Maybe declared
anywhere in the program
static RAM Zero Local Till the end of the main program, Retains value
between multiple functions call
Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are defined.
The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
#include <stdio.h>
int main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
return 0;
}
Output:
garbage garbage garbage
Example 2
#include <stdio.h>
int main()
{
78
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}
Output:
11 20 20 20 11
Static
o The variables defined as static specifier can hold their value between the multiple function calls.
o Static local variables are visible only to the function or the block in which they are defined.
o A same static variable can be declared many times but can be assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example 1
#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main ()
{
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
}
Output:
0 0 0.000000 (null)
Example 2
#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
79
}
}
Output:
10 24
11 25
12 26
Register
o The variables defined as the register is allocated the memory into the CPU registers depending
upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the register
variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU register.
However, it is compiler?s choice whether or not; the variables can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a variable.
o Static variables can not be stored into the register since we can not use more than one storage
specifier for the same variable.
Example 1
#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
printf("%d",a);
}
Output:
0
Example 2
#include <stdio.h>
int main()
{
register int a = 0;
printf("%u",&a); // This will give a compile time error since we can not access the address of a register v
ariable.
}
Output:
main.c:5:5: error: address of register variable ?a? requested
printf("%u",&a);
^~~~~~
External
o The external storage class is used to tell the compiler that the variable defined as extern is
declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration and intended
to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
80
o We can only initialize the extern variable globally, i.e., we can not initialize the external variable
within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be initialized
somewhere in the program which may be extern or static. If it is not, then the compiler will show
an error.
Example 1
#include <stdio.h>
int main()
{
extern int a;
printf("%d",a);
}
Output
main.c:(.text+0x6): undefined reference to `a'
collect2: error: ld returned 1 exit status
Example 2
#include <stdio.h>
int a;
int main()
{
extern int a; // variable a is defined globally, the memory will not be allocated to a
printf("%d",a);
}
Output
0
Example 3
#include <stdio.h>
int a;
int main()
{
extern int a = 0; // this will show a compiler error since we can not use extern and initializer at same tim
e
printf("%d",a);
}
Output
compile time error
main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;
Example 4
#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized somewhere in the pogra
m or not.
printf("%d",a);
}
81
int a = 20;
Output
20
Example 5
extern int a;
int a = 10;
#include <stdio.h>
int main()
{
printf("%d",a);
}
int a = 20; // compiler will show an error at this line
Output
compile time error
Scope of a Identifier starts at the beginning of the file and ends at the end of the file. It
refers to only those Identifiers that are declared outside of all functions. The
Identifiers of File scope are visible all over the file Identifiers having file scope are
File Scope global
Scope of a Identifier begins at opening of the block / ‘{‘ and ends at the end of the
Block Scope block / ‘}’. Identifiers with block scope are local to their block
Function
Prototype Scope Identifiers declared in function prototype are visible within the prototype
Function scope begins at the opening of the function and ends with the closing of it.
Function scope is applicable to labels only. A label declared is used as a target to goto
Function scope statement and both goto and label statement must be in same function
Functions in C
A function is a block of code that performs a particular task.
There are many situations where we might need to write same line of code for more than once in a
program. This may lead to unnecessary repetition of code, bugs and even becomes boring for the
programmer. So, C language provides an approach in which you can declare and define a group of
statements once in the form of a function and it can be called and used whenever required.
These functions defined by the user are also know as User-defined Functions
C functions can be classified into two categories,
1. Library functions
2. User-defined functions
82
Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these functions.
These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the user at the
time of writing program. These functions are made for code reusability and for saving time and space.
Benefits of Using Functions
Parameter list
The parameter list declares the type and number of arguments that the function expects when it is called.
Also, the parameters in the parameter list receives the argument values when the function is called. They
are often referred as formal parameters.
Time for an Example
Let's write a simple program with a main() function, and a user defined function to multiply two numbers,
which will be called from the main() function.
#include<stdio.h>
int multiply(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Please enter 2 numbers you want to multiply...");
scanf("%d%d", &i, &j);
result = multiply(i, j); // function call
printf("The result of muliplication is: %d", result);
return 0;
}
When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function-ending
closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name, and if
the function returns a value, then you can store the returned value. For example −
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
We have kept max() along with main() and compiled the source code. While running the final executable,
it would produce the following result −
Max value is : 200
Header file and library
Header Files : The files that tell the compiler how to call some functionality (without knowing how the
functionality actually works) are called header files. They contain the function prototypes. They also
contain Data types and constants used with the libraries. We use #include to use these header files in
programs. These files end with .h extension.
Library : Library is the place where the actual functionality is implemented i.e. they contain function
body. Libraries have mainly two categories :
• Static
• Shared or Dynamic
Static : Static libraries contains object code linked with an end user application and then they become the
part of the executable. These libraries are specifically used at compile time which means the library
should be present in correct location when user wants to compile his/her C or C++ program. In windows
they end with .lib extension and with .a for MacOS.
Shared or Dynamic : These libraries are only required at run-time i.e, user can compile his/her code
without using these libraries. In short these libraries are linked against at compile time to resolve
undefined references and then its distributed to the application so that application can load it at run time.
85
For example, when we open our game folders we can find many .dll(dynamic link libraries) files. As these
libraries can be shared by multiple programs, they are also called as shared [Link] files end
with .dll or .lib extensions. In windows they end with .dll extension.
Let’s see the difference between these two in tabular form,so that it can be easily comparable:
HEADER FILES LIBRARY FILES
Header files are human [Link] they are in the Library files are non human [Link]
form of source code. they are in the form of machine code.
Header files in our program are included by using a Library files in our program are included in
command #include which is internally handle by pre- last stage by special software called as
processor. linker.
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon entry into
the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a function −
[Link]. Call Type & Description
1 Call by value
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no
effect on the argument.
2 Call by reference
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means the code within a function cannot
alter the arguments used to call the function.
By default, C programming uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function. Consider the function swap() definition as
follows.
/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following example −
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
It shows that there are no changes in the values, though they had been changed inside the function
Function call by reference
The call by reference method of passing arguments to a function copies the address of an argument into
the formal parameter. Inside the function, the address is used to access the actual argument used in the
call. It means the changes made to the parameter affect the passed argument.
To pass a value by reference, argument pointers are passed to the functions just like any other value. So
accordingly you need to declare the function parameters as pointer types as in the following
function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.
/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us now call the function swap() by passing values by reference as in the following example −
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );100
printf("Before swap, value of b : %d\n", b );200
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d\n", a );200
printf("After swap, value of b : %d\n", b );100
return 0;
}
Let us put the above code in a single C file, compile and execute it, to produce the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
88
#include <string.h>
int main()
{
char s1[20] = "Book";
char s2[20] = "Books";
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 – 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 back";
/* 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 back
C String function – strncpy
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);
90
return 0;
}
Output:
String s1 is: string 2: I’m
C String function – strcat
strcat( ) Function :
strcat( ) function in C language concatenates two given strings. It concatenates source string at the end
of destination string. Syntax for strcat( ) function is given below.
Syntax : char * strcat ( char * destination, const char * source );
Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.
• As you know, each string in C is ended up with null character (‘\0′).
• In strcat( ) operation, null character of destination string is overwritten by source string’s first character
and null character is added at the end of new destination string which is created after strcat( ) operation.
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
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = “ ftl” ;
char target[ ]= “ welcome to” ;
printf (“\n Source string = %s”, source ) ;
printf ( “\n Target string = %s”, target ) ;
strcat ( target, source ) ;
printf ( “\n Target string after strcat( ) = %s”, target ) ;
}
Output :
Source string = ftl
Target string = welcome to
Target string after strcat() = welcome to ftl
strrev() function :
strrev() function reverses a given string in C language.
Syntax : char *strrev(char *string);
strrev() function is non standard function which may not available in standard library in C.
91
Example :
char name[20]=”ftl”; then
strrev(name)= ltf
Program : In below program, string “Hello” is reversed using strrev( ) function and output is displayed
as “olleH”.
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = “Hello”;
printf(“String before strrev( ) : %s\n”, name);
printf(“String after strrev( ) : %s”, strrev(name));
return 0;
}
Output :
String before strrev( ) : Hello
String after strrev( ) : olleH
strchr() function :
strchr() function returns pointer to the first occurrence of the character in a given string.
Syntax : char *strchr(const char *str, int character);
Program : In this program, strchr( ) function is used to locate first occurrence of the character ‘i’ in the
string ”This is a string ”. Character ‘i’ is located at position 3 and pointer is returned at first occurrence of
the character ‘i’.
#include <stdio.h>
#include <string.h>
int main ()
{
char string[25] =”This is a string “;
char *p;
p = strchr (string,'i');
return 0;
}
Output :
Character i is found at position 3
First occurrence of character “i” in “This is a string” is “is is a string”
strstr() function :
strstr( ) function returns pointer to the first occurrence of the string in a given string.
Syntax : char *strstr(const char *str1, const char *str2);
Program : In this program, strstr( ) function is used to locate first occurrence of the string “test” in the
string ”This is a test string for testing”. Pointer is returned at first occurrence of the string “test”.
#include <stdio.h>
#include <string.h>
int main( )
92
{
char string[55] =”This is a test string for testing”;
char *p;
p = strstr (string, ”test”);
if(p)
{
printf(“string found\n” );
printf (“First occurrence of string \”test\” in \”%s\” is”\” \”%s\””,string, p);
}
else printf(“string not found\n” );
return 0;
}
Output :
String found
First occurrence of ”test” in “this is a test string for testing” is “testing string for testing”
Recursion:-
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.
void recursion()
{
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go into an
infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial
of a number, generating Fibonacci series, etc.
Number Factorial:-
The following example calculates the factorial of a given number using a recursive function –
#include <stdio.h>
int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
93
}
When the above code is compiled and executed, it produces the following result
Factorial of 15 is 2004310016
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −
#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++) {
printf("%d\t\n", fibonaci(i));
}
return 0;
}
When the above code is compiled and executed, it produces the following result
0 1 1 2 3 5 8 13 21 34
Return pointer from functions
C also allows to return a pointer from a function. To do so, you would have to declare a function returning
a pointer as in the following example −
int * myFunction() {
.
.
.
}
Second point to remember is that, it is not a good idea to return the address of a local variable outside the
function, so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return them using an
array name which represents a pointer, i.e., address of first array element.
#include <stdio.h>
#include <time.h>
/* function to generate and return random numbers. */
int * getRandom( )
{
static int r[10];
94
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
return r;
}
/* a pointer to an int */
int *p;
int i;
p = getRandom();
return 0;
}
When the above code is compiled together and executed, it produces the following result −
1523198053
1187214107
1108300978
430494959
1421301276
930971084
123250484
106932140
1604461820
149169022
*(p + [0]) : 1523198053
*(p + [1]) : 1187214107
*(p + [2]) : 1108300978
*(p + [3]) : 430494959
*(p + [4]) : 1421301276
*(p + [5]) : 930971084
*(p + [6]) : 123250484
*(p + [7]) : 106932140
*(p + [8]) : 1604461820
*(p + [9]) : 149169022
95
tempnum = *num1;
*num1 = *num2;
*num2 = tempnum;
}
int main( )
{
int v1 = 11, v2 = 77 ;
printf("Before swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);
96
printf("\nAfter swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);
return 0;
}
Output:
Before swapping:
Value of v1 is: 11
Value of v2 is: 77
After swapping:
Value of v1 is: 77
Value of v2 is: 11
Command Line Arguments:-
It is possible to pass some values from the command line to your C programs when they are executed.
These values are called command line arguments and many times they are important for your program
especially when you want to control your program from outside instead of hard coding those values inside
the code.
The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to the
program. Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly −
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following result.
$./[Link] testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following result.
$./[Link] testing1 testing2
Too many arguments supplied.
97
When the above code is compiled and executed without passing any argument, it produces the following
result.
$./[Link]
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first
command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc
will be one, and if you pass one argument then argcis set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space then you
can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above
example once again where we will print program name and we also pass a command line argument by
putting inside double quotes −
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but inside
double quotes, it produces the following result.
$./[Link] "testing1 testing2"
Progranm name ./[Link]
The argument supplied is testing1 testing2
Dynamic Memory Allocation:-
In C, the exact size of array is unknown until compile time, i.e., the time when a compiler compiles your
code into a computer understandable language. So, sometimes the size of the array can be insufficient or
more than required.
Dynamic memory allocation allows your program to obtain more memory space while running, or to
release it if it's not required.
In simple terms, Dynamic memory allocation allows you to manually handle memory space for your
program.
Although, C language inherently does not have any technique to allocate memory dynamically, there are
4 library functions under "stdlib.h" for dynamic memory allocation.
They are:
1. malloc()
98
2. calloc()
3. free()
4. realloc()
Let’s look at each of them in greater detail.
Before learning above functions, let's understand the difference between static memory allocation and
dynamic memory allocation.
static memory allocation dynamic memory allocation
memory can't be increased while executing memory can be increased while executing
program. program.
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
calloc() function in C
• The calloc() function allocates multiple block of requested memory.
• It initially initialize all bytes to zero.
• It returns NULL if memory is not sufficient.
• The syntax of calloc() function is given below:
ptr=(cast-type*)calloc(number, byte-size)
Let's see the example of calloc() function.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by
freeing it.
Syntax:
free(ptr);
100
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
Memory successfully allocated using calloc.
Calloc Memory successfully freed.
C realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a
previously allocated memory. In other words, if the memory previously allocated with the help of
malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-
allocation of memory maintains the already present value and new blocks will be initialized with
default garbage value.
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
If space is insufficient, allocation fails and returns a NULL pointer.
101
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.\n");
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
102
Unit-4
C Structures
Structure is a user-defined datatype in C language which allows us to combine data of
different types together. Structure helps to construct a complex data type which is more
meaningful. It is somewhat similar to an Array, but an array holds data of similar type
only. But structure on the other hand, can store data of any type, which is practical more
useful.
For example: If I have to write a program to store Student information, which will have
Student's name, age, branch, permanent address, father's name etc, which included string
values, integer values etc, how can I use arrays for this problem, I will require something
which can hold data of different types together.
In structure, data is stored in form of records.
Defining a structure
struct keyword is used to define a structure. struct defines a new data type which is a
collection of primary and derived datatypes.
Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
As you can see in the syntax above, we start with the struct keyword, then it's optional to
provide your structure a name, we suggest you to give it a name, then inside the curly
braces, we have to mention all the member variables, which are nothing but normal C
language variables of different types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables, again this is
optional.
Note: The closing curly brace in the structure type declaration must be followed by a
semicolon(;).
Example of Structure
struct Student
{
char name[25];
int age;
103
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists of 4
data fields, namely name, age, branch and gender. These fields are called structure
elements or members.
Each member can have different datatype, like in this case, name is an array of char type
and age is of int type etc. Student is the name of the structure and is called as the structure
tag.
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
int main()
{
struct Student s1;
[Link] = 18;
/*
using string function to add name
*/
strcpy([Link], "Viraaj");
/*
displaying the stored values
*/
printf("Name of Student 1: %s\n", [Link]);
printf("Age of Student 1: %d\n", [Link]);
return 0;
}
Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at compile
time.
struct Patient
{
float height;
int weight;
int age;
};
unsigned int d;
unsigned int m;
unsigned int y;
};
int main()
{
printf("Size of date is %lu
bytes\n", sizeof(structdate));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Output:
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
Output:
Size of date is 8 bytes
Date is 31/12/2014
107
However if the same code is written using signed int and the value of the fields goes
beyond the bits allocated to the variable and something interesting can happen. For
example consider the same code but with signed integers:
#include <stdio.h>
// Space optimized representation of the date
struct date {
// d has value between 1 and 31, so 5 bits
// are sufficient
int d : 5;
int y;
};
int main()
{
printf("Size of date is %lu bytes\n",
sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
Output:
Size of date is 8 bytes
Date is -1/-4/2014
The output comes out to be negative. What happened behind is that the value 31 was
stored in 5 bit signed integer which is equal to 11111. The MSB is a 1, so it’s a negative
number and you need to calculate the 2’s complement of the binary number to get its
actual value which is what is done internally. By calculating 2’s complement you will
arrive at the value 00001 which is equivalent to decimal number 1 and since it was a
negative number you get a -1. A similar thing happens to 12 in which case you get 4-bit
representation as 1100 which on calculating 2’s complement you get the value of -4.
Array of Structures:-
Structure is collection of different data type. An object of structure represents a single
record in memory, if we want more than one record of structure type, we have to create
an array of structure or object. As we know, an array is a collection of similar type,
therefore an array can be of structure type.
Syntax :-
108
struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
struct struct-name obj [ size ];
EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES IN C:
This program is used to store and access “id, name and percentage” for 3 students.
Structure array is used in this program to store and display records for many students.
You can store “n” number of students record by declaring structure variable as ‘struct
student record[n]“, where n can be 1000 or 5000 etc.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name, "Tia");
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf(" Records of STUDENT : %d \n", i+1);
109
scanf("%d",&Emp[i].Age);
printf("\n\tEnter Employee Salary : ");
scanf("%ld",&Emp[i].Salary);
}
printf("\nDetails of Employees");
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}
Output :
Enter details of 1 Employee
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000
Enter details of 2 Employee
Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000
Enter details of 3 Employee
Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
Passing struct to function:-
A structure can be passed to any function from main function or from any sub function.
Structure definition will be available within the function only.
It won’t be available to other functions unless it is passed to those functions by value or by
address (reference).
Else, we have to declare structure variable as global variable. That means, structure
variable should be declared outside the main function. So, this structure will be visible to
all the functions in a C program.
PASSING STRUCTURE TO FUNCTION IN C:
It can be done in below 2 ways.
Passing structure to a function by value
Passing structure to a function by address(reference)
In this program, the whole structure is passed to another function by value. It means the
whole structure is passed to another function with all members and their values. So, this
structure can be accessed from called function. This concept is very useful while writing
very big programs in C.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record);
int main()
{
struct student record;
[Link]=1;
strcpy([Link], "Raju");
[Link] = 86.5;
func(record);
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", [Link]);
printf(" Name is: %s \n", [Link]);
printf(" Percentage is: %f \n", [Link]);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void display(struct student stu);
112
int main()
{
struct student stud;
printf("Enter student's name: ");
scanf("%s", &[Link]);
printf("Enter roll number:");
scanf("%d", &[Link]);
display(stud); // passing structure variable stud as argument
return 0;
}
void display(struct student stu){
printf("Output\nName: %s",[Link]);
printf("\nRoll: %d",[Link]);
}
Output
Enter student's name: Kevin Amla
Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149
EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:
In this program, the whole structure is passed to another function by address. It means
only the address of the structure is passed to another function. The whole structure is not
passed to another function with all members and their values. So, this structure can be
accessed from called function by its address.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
int main()
{
struct student record;
[Link]=1;
113
strcpy([Link], "Raju");
[Link] = 86.5;
func(&record);
return 0;
}
void func(struct student *record)
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record-
>percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
#include <stdio.h>
struct distance
{
int feet;
float inch;
};
void add(struct distance d1,struct distance d2, struct distance *d3);
int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d", &[Link]);
printf("Enter inch: ");
scanf("%f", &[Link]);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d", &[Link]);
printf("Enter inch: ");
scanf("%f", &[Link]);
114
//passing structure variables dist1 and dist2 by value whereas passing structure
variable dist3 by reference
printf("\nSum of distances = %d\'-%.1f\"", [Link], [Link]);
return 0;
}
void add(struct distance d1,struct distance d2, struct distance *d3)
{
//Adding distances d1 and d2 and storing it in d3
d3->feet = [Link] + [Link];
d3->inch = [Link] + [Link];
Differences
};
union details {
struct student st;
};
union details set;
printf("Enter details:");
printf("\nEnter name : ");
scanf("%s", &[Link]);
printf("\nEnter roll no : ");
scanf("%d", &[Link]);
printf("\nEnter sex : ");
scanf("%c", &[Link]);
printf("\nEnter percentage :");
scanf("%f", &[Link]);
printf("\nThe student details are : \n");
printf("\name : %s", [Link]);
printf("\nRollno : %d", [Link]);
printf("\nSex : %c", [Link]);
printf("\nPercentage : %f", [Link]);
getch();
}
Output
Enter details:
Enter name : Pritesh
Enter rollno: 10
Enter sex: M
Enter percentage: 89
1
The student details are:
Name : Pritesh
Rollno : 10
Sex : M
Percentage : 89.000000
Self Referential Structures
Self Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.
118
In other words, structures pointing to the same type of structures are self-referential in
nature.
Example:
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure
‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.
Types of Self Referential Structures
• Self Referential Structure with Single Link
• Self Referential Structure with Multiple Links
Self Referential Structure with Single Link: These structures can have only one self-
pointer as their member. The following example will show us how to connect the objects
of a self-referential structure with the single link and access the corresponding data
119
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Initialization
[Link] = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
[Link] = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
[Link] = &ob2;
// Accessing data members of ob2 using
ob1
printf("%d", [Link]->data1);
printf("\n%d", [Link]->data2);
return 0;
}
Output:
30
40
Self Referential Structure with Multiple Links: Self referential structures with multiple
links can have more than one self-pointers. Many complicated data structures can be
120
easily constructed using these structures. Such structures can easily connect to more than
one nodes at a time. The following example shows one such structure with more than one
links.
The connections made in the above example can be understood using the following figure.
#include <stdio.h>
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};
int main()
{
struct node ob1; // Node1
// Initialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
[Link] = 10;
struct node ob2; // Node2
// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
[Link] = 20;
struct node ob3; // Node3
// Initialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
[Link] = 30;
// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;
// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;
// Accessing data of ob1, ob2 and ob3 by ob1
printf("%d\t", [Link]);
121
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob2
printf("%d\t", ob2.prev_link->data);
printf("%d\t", [Link]);
printf("%d\n", ob2.next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob3
printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", [Link]);
return 0;
}
Output:
10 20 30
10 20 30
10 20 30
In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three objects of the self
referential structure ‘node’. And they are connected using their links in such a way that
any of them can easily access each other’s data. This is the beauty of the self referential
structures. The connections can be manipulated according to the requirements of the
programmer.
Applications:
Self referential structures are very useful in creation of other complex data structures
like:
• Linked Lists
• Stacks
• Queues
• Trees
• Graphs etc
File management in C
In this tutorial you will learn about C Programming – File management in C, File
operation functions in C, Defining and opening a file, Closing a file, The getw and putw
functions, The fprintf & fscanf functions, Random access to files and fseek function.
C supports a number of functions that have the ability to perform basic file operations,
which include:
1. naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
122
Real life situations involve large volume of data and in such cases, the console oriented I/O
operations pose two major problems
It becomes cumbersome and time consuming to handle large volumes of data through
terminals.
The entire data is lost when either the program is terminated or computer is turned off
therefore it is necessary to have more flexible approach where data can be stored on the
disks and read whenever necessary, without destroying the data. This method employs
the concept of files to store data.
File operation functions in C:
Function Operation
Name
fopen() Creates a new file for use
Opens a new existing file for use
fclose Closes a file which has been opened for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads a integer from a file
putw() Writes an integer to the file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the begining of the file
Opening Files
You can use the fopen( ) function to create a new file or to open an existing file. This call
will initialize an object of the type FILE, which contains all the information necessary to
control the stream. The prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and access mode can
have one of the following values −
Mode Description
W Opens a text file for writing. If it does not exist, then a new file is
created. Here your program will start writing content from the
beginning of the file.
A Opens a text file for writing in appending mode. If it does not exist,
then a new file is created. Here your program will start appending
content in the existing file content.
123
w+ Opens a text file for both reading and writing. It first truncates the file
to zero length if it exists, otherwise creates a file if it does not exist.
a+ Opens a text file for both reading and writing. It creates the file if it
does not exist. The reading will start from the beginning but writing
can only be appended.
If you are going to handle binary files, then you will use following access modes instead of
the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file.
This function actually flushes any data still pending in the buffer to the file, closes the file,
and releases any memory used for the file. The EOF is a constant defined in the header
file stdio.h.
Reading from a file –
The file read operations can be performed using functions fscanf or fgets. Both the
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. So, it depends on you if you want to read the file line by line or
character by character.
And the code snippet for reading a file is as:
FILE * filePointer;
filePointer = fopen(“[Link]”, “r”);
fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);
Writing a file –:
The file write operations can be perfomed by the functions fprintf and fputs with
similarities to read operations. The snippet for writing to a file is as :
FILE *filePointer ;
filePointer = fopen(“[Link]”, “w”);
fprintf(filePointer, "%s %s %s %d", "We", "are", "
124
# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[50];
// opening an existing file
printf( "Opening the file test.c in write mode" ) ;
fp = fopen("test.c", "w") ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard” \
“ to write in the file test.c" ) ;
// getting input from user
while ( strlen ( gets( data ) ) > 0 )
{
// writing in the file
fputs(data, fp) ;
fputs("\n", fp) ;
}
// closing the file
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}
OUTPUT:
Opening the file test.c in write mode
Enter some text from keyboard to write in the file test.c
Hai, How are you?
Closing the file test.c
125
Predefined Streams :
Stands
Standard Input Standard Output
For
Data (Often
data (Often Text) going out from a
Data Flow Text) going into
program
a program
}
Different methods of Error handling in C
Value of errno: 2
Note: Here the errno is set to 2 which means – No such file or directory. On online IDE
it may give errorno 13, which says permission denied.
1. perror() and strerror(): The errno value got above indicate the types of error
encountered.
If it is required to show the error description, then there are two functions that can be
used to display a text message that is associated with errorno. The functions are:
• perror: It displays the string you pass to it, followed by a colon, a space, and then
the textual representation of the current errno value.
Syntax:
void perror (const char *str)
• str: is a string containing a custom message to be printed before the error message
itself.
• strerror(): returns a pointer to the textual representation of the current errno
value.
Syntax:
char *strerror (int errnum)
errnum: is the error number (errno).
// C implementation to see how perror() and
strerror()
// functions are used to print the error messages.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
{
FILE *fp;
// If a file is opened which does not exist,
// then it will be an error and corresponding
// errno value will be set
fp = fopen(" [Link] ", "r");
Output:
On Personal desktop:
Value of errno: 2
The error message is : No such file or directory
Message from perror: No such file or directory
On online IDE:
Value of errno: 13
The error message is : Permission denied
Note: The function perror() displays a string passed to it, followed by a colon and the
textual message of the current errno value.
2. Exit Status: The C standard specifies two constants: EXIT_SUCCESS and EXIT_FAILURE,
that may be passed to exit() to indicate successful or unsuccessful termination,
respectively. These are macros defined in stdlib.h.
// C implementation which shows the
// use of EXIT_SUCCESS and EXIT_FAILURE.
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
FILE * fp;
fp = fopen ("[Link]", "rb");
if (fp == NULL)
{
printf("Value of errno: %d\n", errno);
printf("Error opening the file: %s\n",
strerror(errno));
perror("Error printed by perror");
exit(EXIT_FAILURE);
printf("I will not be printed\n");
}
else
{
fclose (fp);
exit(EXIT_SUCCESS);
printf("I will not be printed\n");
}
return 0;
130
}
Output:
Value of errno: 2
Error opening the file: No such file or directory
Error printed by perror: No such file or directory
3. Divide by Zero Errors: A common pitfall made by C programmers is not checking if a
divisor is zero before a division command. Division by zero leads to undefined
behavior, there is no C language construct that can do anything about it. Your best bet
is to not divide by zero in the first place, by checking the denominator.
// C program to check and rectify
// divide by zero condition
#include<stdio.h>
#include <stdlib.h>
void function(int);
int main()
{
int x = 0;
function(x);
return 0;
}
void function(int x)
{
float fx;
if (x==0)
{
printf("Division by Zero is not allowed");
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}
else
{
fx = 10 / x;
printf("f(x) is: %.5f", fx);
}
}
Output:
Division by Zero is not allowed
#include <stdio.h>
#include <errno.h>
#include <string.h>
131
Declaration
Parameters
• stream − This is the pointer to a FILE object that identifies the stream.
• offset − This is the number of bytes to offset from whence.
• whence − This is the position from where offset is added. It is specified by one of the
following constants −
1 SEEK_SET
Beginning of file
133
2 SEEK_CUR
Current position of the file pointer
3 SEEK_END
End of file
Return Value
Example
int main () {
FILE *fp;
fp = fopen("[Link]","w+");
fputs("This is [Link]", fp);
return(0);
}
Let us compile and run the above program that will create a file [Link] with the following
content. Initially program creates the file and writes This is [Link] but later we had
reset the write pointer at 7th position from the beginning and used puts() statement which
over-write the file with the following content This is C Programming Language
Now let's see the content of the above file using the following program −
#include <stdio.h>
int main () {
FILE *fp;
int c;
134
fp = fopen("[Link]","r");
while(1) {
c = fgetc(fp);
if( feof(fp) ) {
break;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Let us compile and run the above program to produce the following result −
This is C Programming Language
How to use ftell() function in C:
In C language, ftell() returns the current file position of the specified stream with respect to
the starting of the file. This function is used to get the total size of file after moving the file
pointer at the end of the file. It returns the current position in long type and file can have
more than 32767 bytes of data.
Here is the syntax of ftell() in C language,
#include <stdio.h>
#include<conio.h>
void main () {
135
FILE *f;
int len;
f = fopen("[Link]", "r");
if(f == NULL) {
perror(“Error opening file”);
return(-1);
}
fseek(f, 0, SEEK_END);
len = ftell(f);
fclose(f);
printf("Size of file: %d bytes", len);
getch();
}
Output
Size of file: 78 bytes
When you access files and devices using the following groups of functions:
The following describes the differences between high-level and low-level I/O functions.
• When using the I/O functions high-level I/O is slower as compared to the low-level
I/O.
136
Low-level I/O
• When using I/O functions, low-level I/O is faster as compared to the high-level I/O.
File Descriptors
When you perform any read or write operations you need to open a file. You can create a
new file to write to it, or you can use an existing file by discarding its previous contents.
You need to specific permissions to be able to perform read or write operations.
When you write to a file, the system checks for the existing permissions and if you have
permission then the system returns a non-negative integer called a “file descriptor”. In
low-level I/O functions a file descriptor is used to identity a file for all subsequent read or
write operations.
The low-level I/O system in C provides functions that can be used to access files and
devices.
1. Open()
2. Close()
3. Read()
4. Write()
137