C TOKENS:
In a C program the smalles individual units are known as C tokens. They
serve as the basic building blocks for program statements. C programs are
written using these tokens and the syntax of the language.
Word:
A word is a collection of characters which has some meaning. The following
are the rules to frame a word.
A word can be formed with the help of 37 characters only (Alphabets,
Digits and Underscore).
The length of the word should not exceed 8 characters.
A word must start with an alphabet only.
A word must not start with a digit but it can end with a digit.
Underscore (_) is used to separate the words (eg: emp_sal).
Words are broadly classified into keywords and user-defined words.
Keywords: All keywords have fixed meaning and these meaning cannot be
changed. There are 32 keywords are present in C language. All keywords
must be written in lowercase.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
User-defined words: Words which are defined by the user for his own
specific purpose and consist of a sequence of letters and digits, with a letter
as the first character. Both uppercase and lowercase letters are permitted.
Example: emp_sal
Identifier:
An identifier is a name given to the elements of a C program such as names
of the variables, constants, functions, arrays, structures, unions, files etc.,
Variable:
A variable is a data name that may be used to store a data value. It reserves
some space in the memory. It can change its value during the execution of a
C program.
Example: average
Constant:
A constant is a data name that may be used to store a data value. It
reserves some space in the memory. It can not change its value during the
execution of a C program.
Consants are broadly classified into numeric constants and character
constants.
Integer Constants: An integer constant refers to a sequence of digits with
or without sign without a fractional part. There are three types of integers,
namely, decimal integer, octal integer and hexadecimal integer.
Decimal integers consist a set of digits, 0 through 9, preceeded by an
optional – or + sign.
Example: 123 -321
An octal integer constant consists any combination of digits from the set 0
through 7, with a leading 0.
Example: 037 0435
A hexadecimal integer is a sequence of digis preceeded by 0x or 0X.
Example: 0X2 0x9F
Real Constans: Real constant refers to a sequence of digits with or without
sign with a fractional part or exponent.
Example: 0.0083 -0.75 0.65e4 -1.2E3
Single Character Constants: A single character constant contains a single
character enclosed within a pair of single quotes.
Example: ‘5’ ‘x’ ‘*’
String Constant: A string constant is a sequence of characters enclosed in
double quotes.
Example: “Hello” “Well Done”
/* Program to print all the characters of C character Set */
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
printf("ASCII ==> Character\n");
for(i = -128; i <= 127; i++)
printf("%d ==> %c\n", i, i);
getch();
return 0;
}
DATA TYPES:
Data types in the c programming language are used to specify what kind of
value can be stored in a variable. The memory size and type of the value of a
variable are determined by the variable data type. Data used in c program is
classified into different types based on its properties.
Primary data types (Basic data types OR Predefined data types)
User-defined data types
Derived data types
Empty data set (void data type)
Primary Data Types:
The primary data types in the C programming language are the basic data
types. All the primary data types are already defined in the system. Primary
data types are also called as Built-In data types. The following are the
primary data types in c programming language...
Character data type
Integer data type
Floating Point data type
Double data type
Character data types: The character data type is a set of characters
enclosed in single quotations. The following table provides complete details
about the character data type.
Type Size (Bytes) Range Specifier
char (signed char) 1 -128 to +127 %c
unsigned char 1 0 to 255 %c
Integer Data types: The integer data type is a set of whole numbers. Every
integer value does not have the decimal value. We use the keyword "int" to
represent integer data type in c. The integer data type is used with different
type modifiers like short, long, signed and unsigned. The following table
provides complete details about the integer data type.
Type Size (Bytes) Range Specifier
short int (signed 1 -128 to +127 %d
short int)
unsigned short int 1 0 to 255 %d
int (signed int) 2 -32,768 to + 32,767 %d
unsigned int 2 0 to 65535 %d
long int (signed 4 -2,147,483,648 to %u
long int) 2,147,483,647
unsigned long int 4 0 to 4,294,967,295 %u
Floating Point data types: Floating-point data types are a set of numbers
with the decimal value. Every floating-point value must contain the decimal
value. The floating-point data type has two variants such as float and
double. We use the keyword "float" to represent floating-point data type and
"double" to represent double data type in c.
Both float and double are similar but they differ in the number of decimal
places. The float value contains 6 decimal places whereas double value
contains 14decimal places. The following table provides complete details
about floating-point data types.
Type Size (Bytes) Range Specifier
float 4 3.4E-38 to 3.4E+38 %d
double 8 1.7E-308 to 1.7E+308 %ld
long double 10 3.4E-4932 to 1.1E+4932 %ld
User-defined data types:
User-defined data types of the C language consist of typedef and
enumerated (enum).
typedef: In C programming language, typedef is a keyword used to create
alias name for the existing datatypes. Using typedef keyword we can create a
temporary name to the system defined datatypes like int, float, char and
double. We use that temporary name to create a variable.
Syntax: typedef <existing-datatype> <alias-name>
Example: typedef int Number
In the above example, Number is defined as alias name for integer datatype.
So, we can use Number to declare integer variables.
/* Program to illustrate typedef in C */
#include<stdio.h>
#include<conio.h>
typedef int Number;
void main( )
{
Number a,b,c; // Here a,b,&c are integer type of variables.
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &a,&b) ;
c = a + b;
printf("Sum = %d", c) ;
}
Enumerated (enum): In C programming language, an enumeration is used
to create user-defined datatypes. Using enumeration, integral constants are
assigned with names and we use these names in the program. Using names
in programming makes it more readable and easy to maintain.
Enumeration is the process of creating user defined datatype by assigning
names to integral constants. We use the keyword enum to create
enumerated datatype.
Syntax: enum identifier {name1, name2, name3, ... }
Example: enum day {mon, tue, wed, thu, fri, sat};
In the above syntax, integral constant '0' is assigned to name1, integral
constant '1' is assigned to name2 and so on.
/* Program to demonstrate enum in C */
#include<stdio.h>
#include<conio.h>
enum day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,
Sunday} ;
void main()
{
enum day today;
today = tuesday ;
printf("\ntoday = %d ", today) ;
}
In the above example program a user defined datatype "day is created seven
values, monday as integral constant '0', tuesday as integral constant '1',
wednesday as integral constant '2', thursday as integral constant '3', friday
as integral constant '4', saturday as integral constant '5' and sunday as
integral constant '6'. Here, when we display tuesday it displays the
respective integral constant '1'.
Derived data types:
The derived data types of C language are Arrays, Structures, Unions etc.,
Empty (void) data set:
The void data type means nothing or no value. Generally, the void is used to
specify a function which does not return any value. We also use the void
data type to specify empty parameters of a function.
INPUT / OUTPUT FUNCTIONS IN C:
Input means which the program reads. Output means which the program
writes.
The input/output functions of C language are broadly classified into 3 types
such as…
Console i/o functions: Console i/o functions are used to transfer the
data between the program and programmer.
Disk i/o functions: Disk i/o functions are used to transfer the data
between the program and storage device.
Port i/o functions: Port i/o functions are used to transfer the data
between the program and i/o port.
The console i/o functions are further divided into unformatted console i/o
functions and formatted console i/o functions.
Unformatted Console I/O functions:
The unformatted console I/O functions deals with character type data only.
They are getchar(), putchar(), getch(), getche(), putch(), gets(), puts().
getchar() function: The getchar() function is used to read a character from
the keyboard and return it to the program. This function is used to read a
single character. To read multiple characters we need to write multiple times
or use a looping statement. Consider the following example program...
Syntax: char_var = getchar();
Example: ch = getchar();
/* Program to illustrate getchar() function */
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("\nEnter any character : ");
ch = getchar();
printf("\nYou have entered : %c\n",ch);
}
Output:
Ener any character : M
You have entered: M
putchar() function: The putchar() function is used to display a single
character on the output screen. The putchar() functions prints the character
which is passed as a parameter to it and returns the same character as a
return value. This function is used to print only a single character. To print
multiple characters we need to write multiple times or use a looping
statement.
Syntax: putchar(char_var);
Example: puchar(ch);
/* Program to illustrate putchar() function */
#include<stdio.h>
#include<conio.h>
void main()
{
char ch = 'A';
putchar(ch);
}
Output:
getch() function: The getch() function is similar to getchar function. The
getch() function is used to read a character from the keyboard and return it
to the program. This function is used to read a single character. To read
multiple characters we need to write multiple times or use a looping
statement.
Syntax: char_var = getch();
Example: ch = getch();
/* Program to illustrate getch() function */
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("\nEnter any character : ");
ch = getch();
printf("\nYou have entered : %c",ch);
}
Output:
Enter any charater :
You have entered : M
gets() function: The gets() function is used to read a line of string and
stores it into a character array. The gets() function reads a line of string or
sequence of characters till a newline symbol enters.
Syntax: gets(str_var);
Example: gets(str);
/* Program to demonstrate gets() function */
#include<stdio.h>
#include<conio.h>
void main()
{
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
printf("%s",name);
}
Output:
Enter your favourite website: economictimes
economictimes
puts() function: The puts() function is used to display a string on the
output screen. The puts() functions prints a string or sequence of characters
till the newline.
Syntax: puts(str_var);
Example: puts(str);
/* Program to demonstrate puts() function */
#include<stdio.h>
#include<conio.h>
void main()
{
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
puts(name);
}
Output:
Enter your favourite website: economictimes
economictimes
Formatted Console I/O functions:
The formateed console I/O functions are used to read / write multiple data
values of different data. They are scanf() and printf().
scanf() function: The scanf() function is used to read multiple data values
of different data types from the keyboard. The scanf() function is built-in
function defined in a header file called "stdio.h". When we want to use
scanf() function in our program, we need to include the respective header file
(stdio.h) using #include statement.
Syntax: scanf("format strings",&variableNames);
Example: scanf("%d",&i);
/* Program to demonstrate scanf() function */
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
printf("\nEnter any integer value: ");
scanf("%d",&i);
printf("\nYou have entered %d number",i);
}
Output:
Enter any integer value: 123
You have entered 123 number
In the above example program, we used the scanf() function to read an
integer value from the keyboard and store it into variable 'i'.
The scanf function also used to read multiple data values of different or the
same data types. Consider the following program...
Example: scanf("%d%f",&i, &x);
/* Program to demonstrate scanf() function with multiple values */
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
float x;
printf("\nEnter one integer followed by one float value : ");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);
}
Output:
Enter one integer followed by one float value : 123 12.34
integer = 123, float = 12.340000
In the above example program, we used the scanf() function to read one
integer value and one float value from the keyboard. Here 'i' is an integer
variable so we have used format string %d, and 'x' is a float variable so we
have used format string %f.
The scanf() function returns an integer value equal to the total number of
input values read using scanf function.
Example: i = scanf("%d%d%f",&a, &b, &x);
/* Program to illustrate scanf() function to count no. of values read */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,a,b;
float x;
printf("\nEnter two integers and one float : ");
i = scanf("%d%d%f",&a, &b, &x);
printf("\nTotal inputs read : %d",i);
}
Output:
Enter two integers and one float : 12 23 34.56
Total inputs read : 3
printf() function: The printf() function is used to print string or data values
or a combination of string and data values on the output screen (User
screen). The printf() function is built-in function defined in a header file
called "stdio.h". When we want to use printf() function in our program we
need to include the respective header file (stdio.h) using
the #include statement.
Syntax: printf("message to be display!!!");
Example: printf("Hello! Welcome to the land of C");
/* Program to illustrate printf() function */
#include<stdio.h>
#include<conio.h>
void main()
{
printf("Hello! Welcome to the land of C");
}
Output:
Hello! Welcome to the land of C
In the above example program, we used the printf() function to print a string
on to the output screen.
The printf() function is also used to display data values. When we want to
display data values we use format string of the data value to be displayed.
Syntax: printf("format string",variableName);
Example: printf("%d %f",i, x);
/* Program to display data values using printf() */
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 10;
float x = 5.5;
printf("%d %f",i, x);
}
Output:
10 5.500000
In the above example program, we used the printf() function to print data
values of variables i and x on to the output screen. Here i is a an integer
variable so we have used format string %d and x is a float variable so we
have used format string %f.
The printf() function can also be used to display string along with data
values.
Syntax: printf("String format string",variableName);
Example: printf("Integer value = %d, float value = %f",i, x);
/* Program to display string along with data values using printf() */
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 10;
float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);
}
Output:
Integer value = 10, float value = 5.500000
In the above program, we are displaying string along with data values.
Every function in the C programming language must have a return value.
The printf() function also have an integer as a return value.
The printf() function returns an integer value equivalent to the total number
of characters it has printed.
Example: i = printf("WelcomeToTheLandofC");
/* Program to count no. characters printed using printf() */
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
i = printf("WelcomeToTheLandofC");
printf(" is %d number of characters.",i);
}
Output:
WelcomeToTheLandofC is 19 number of characters.
In the above program, first printf() function printing "
WelcomeToTheLandofC " which is of 19 characters. So it returns integer
value 15 to the variable "i". The value of "i" is printed in the second printf()
function.
Generally, when we write multiple printf() statements the result is displayed
in a single line because the printf() function displays the output in a single
line. Consider the following example program...
/* Program to illustrate formatted printf() function */
#include<stdio.h>
#include<conio.h>
void main()
{
printf("Welcome to ");
printf("The Land of C ");
printf("the perfect subject for learning programming ");
}
Output:
Welcome to The Land of C the perfect subject for learning programming
In the above program, there are 3 printf() statements written in different
lines but the output is displayed in single line only.
To display the output in different lines or as we wish, we use some special
characters called escape sequences.
Escape sequences are special characters with special functionality used in
printf() function to format the output according to the user requirement. In
the C programming language, we have the following escape sequences...
Escape Sequences / Backslash Character Constants: C supports some
special backslash character constants that are used in output functions.
Constant Meaning
‘\a’ audible alert (bell)
‘\h’ back space
‘\f’ form feed
‘\n’ new line
‘\r’ Carriage return
‘\t’ horizontal tab
‘\v’ vertical tab
‘\’’ single quote
‘\”’ double quote
‘\?’ question mark
‘\\’ backslash
‘\0’ null
/* Program to illustrate escape sequence */
#include<stdio.h>
#include<conio.h>
void main()
{
printf("Welcome to \n");
printf("The Land of C \n");
printf("the perfect subject for learning programming ");
}
Output:
Welcome to The
Land of C
the perfect subject for learning programming
OPERATORS IN C:
An operator is a symbol used to perform arithmetic and logical operations in
a program. That means an operator is a special symbol that tells the
compiler to perform mathematical or logical operations. C programming
language supports a rich set of operators that are classified as follows.
Arithmetic Operators
Relational Operators
Logical Operators
Increment & Decrement Operators
Assignment Operators
Conditional Operator
Bitwise Operators
Special Operators
Arithmetic Operators (+, -, *, /, %):
The arithmetic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication, division
and percentage modulo. The following table provides information about
arithmetic operators.
Operator Meaning Example
+ Addition 5+2=7
- Subtraction 5–2=3
* Multiplication 5 * 2 = 10
/ Integer Division (Quotient) 5/2=2
% Modulo Division (Remainder) 5%2=1
The addition operator can be used with numerical data types and character
data type. When it is used with numerical values, it performs mathematical
addition and when it is used with character data type values, it performs
concatination (appending).
The remainder of the division operator is used with integer data type only.
Relational Operators (<, >, <=, >=, ==, !=):
The relational operators are the symbols that are used to compare two
values. That means the relational operators are used to check the
relationship between two values. Every relational operator has two results
TRUE or FALSE. In simple words, the relational operators are used to define
conditions in a program. The following table provides information about
relational operators.
Operator Meaning Example
< Returns TRUE if the first value is smaller than 5 < 2 is
second value otherwise returns FALSE False
<= Returns TRUE if the first value is smaller than or 5 <= 2 is
equal to second value otherwise returns FALSE False
> Returns TRUE if the first value is larger than 5 > 2 is True
second value otherwise returns FALSE
>= Returns TRUE if the first value is larger than or 5 >= 2 is
equal to second value otherwise returns FALSE True
== Returns TRUE if both values are equal otherwise 5 == 2 is
returns FALSE False
!= Returns TRUE if both values are not equal 5 != 2 is
otherwise returns FALSE True
Logical Operators (&&, ||, !):
The logical operators are the symbols that are used to combine multiple
conditions into one condition. The following table provides information
about logical operators.
Operator Meaning Example
&& Logical AND - Returns TRUE if all conditions are 5 < 2 && 5 >
TRUE otherwise returns FALSE 7 is False
|| Logical OR - Returns FALSE if all conditions are 5 < 2 || 5 > 7
FALSE otherwise returns TRUE is True
! Logical NOT - Returns TRUE if condition is (!5 < 2 && 5 >
FLASE and returns FALSE if it is TRUE 7) is True
Logical AND - Returns TRUE only if all conditions are TRUE, if any of
the conditions is FALSE then complete condition becomes FALSE.
Logical OR - Returns FALSE only if all conditions are FALSE, if any of
the conditions is TRUE then complete condition becomes TRUE.
Increment & Decrement Operators (++ & --)
The increment and decrement operators are called unary operators because
both need only one operand. The increment operator adds one to the
existing value of the operand and the decrement operator subtracts one
from the existing value of the operand. The following table provides
information about increment and decrement operators.
Operator Meaning Example
++ Increment - Adds one to existing value int a = 5;
a++; ⇒ a = 6
-- Decrement - Subtracts one from int a = 5;
existing value a--; ⇒ a = 4
The increment and decrement operators are used infront of the operand
(++a) or after the operand (a++). If it is used infront of the operand, we call it
as pre-increment or pre-decrement and if it is used after the operand, we
call it as post-increment or post-decrement.
Pre-Increment or Pre-Decrement: In the case of pre-increment, the value
of the variable is increased by one before the expression evaluation. In the
case of pre-decrement, the value of the variable is decreased by one before
the expression evaluation. That means, when we use pre-increment or pre-
decrement, first the value of the variable is incremented or decremented by
one, then the modified value is used in the expression evaluation.
/* Program to demonstrate Pre-Increment operator */
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j = %d",i,j);
}
Output:
i = 6, j = 7
Post-Increment or Post-Decrement: In the case of post-increment, the
value of the variable is increased by one after the expression evaluation. In
the case of post-decrement, the value of the variable is decreased by one
after the expression evaluation. That means, when we use post-increment or
post-decrement, first the expression is evaluated with existing value, then
the value of the variable is incremented or decremented by one.
/* Program to demonstrate Post-Increment Operator */
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 5,j;
j = i++; // Post-Increment
printf("i = %d, j = %d",i,j);
}
Output:
i = 6, j = 5
Assignment Operators (=, +=, -=, *=, /=, %=):
The assignment operators are used to assign right-hand side value (Rvalue)
to the left-hand side variable (Lvalue). The assignment operator is used in
different variants along with arithmetic operators.
The following table describes all the assignment operators in the C
programming language.
Operator Meaning Example
= Assign the right-hand side value to left-hand side A = 15
variable
+= Add both left and right-hand side values and store A += 10
the result into left-hand side variable ⇒A=
A+10
-= Subtract right-hand side value from left-hand side A -= B
variable value and store the result ⇒ A = A-B
into left-hand side variable
*= Multiply right-hand side value with left-hand side A *= B
variable value and store the result ⇒A=
into left-hand side variable A*B
/= Divide left-hand side variable value with right-hand A /= B
side variable value and store the result ⇒A=
into the left-hand side variable A/B
%= Divide left-hand side variable value with right-hand A %= B
side variable value and store the remainder ⇒A=
into the left-hand side variable A%B
Conditional Operator (?:):
The conditional operator is also called a ternary operator because it requires
three operands. This operator is used for decision making. In this operator,
first we verify a condition, then we perform one operation out of the two
operations based on the condition result. If the condition is TRUE the first
option is performed, if the condition is FALSE the second option is
performed. The conditional operator is used with the following syntax.
Condition ? TRUE Part : FALSE Part;
Syntax: (exp1) ? (exp2) : (exp3);
Example: A = (10<15)?100:200; ⇒ A value is 100
Bitwise Operators (&, |, ^, ~, >>, <<):
The bitwise operators are used to perform bit-level operations in the c
programming language. When we use the bitwise operators, the operations
are performed based on the binary values. The following table describes all
the bitwise operators in the C programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operator Meaning Example
& the result of Bitwise AND is 1 if all the A&B
bits are 1 otherwise it is 0 ⇒ 16 (10000)
| the result of Bitwise OR is 0 if all the A|B
bits are 0 otherwise it is 1 ⇒ 29 (11101)
^ the result of Bitwise XOR is 0 if all the A^B
bits are same otherwise it is 1 ⇒ 13 (01101)
~ the result of Bitwise once complement ~A
is negation of the bit (Flipping) ⇒ 6 (00110)
<< the Bitwise left shift operator shifts all A << 2
the bits to the left by the specified ⇒ 100 (1100100)
number of positions
>> the Bitwise right shift operator shifts A >> 2
all the bits to the right by the specified ⇒ 6 (00110)
number of positions
Special Operators (sizeof, pointer, comma, dot, etc.):
The following are the special operators in c programming language.
sizeof operator: This operator is used to find the size of the memory (in
bytes) allocated for a variable. This operator is used with the following
syntax.
Syntax: sizeof(variableName);
Example: sizeof(A); ⇒ the result is 2 if A is an integer
Pointer operator (*): This operator is used to define pointer variables in c
programming language.
Comma operator (,): This operator is used to separate variables while they
are declaring, separate the expressions in function calls, etc.
Dot operator (.): This operator is used to access members of structure or
union.
EXPRESSIONS:
Expression: In any programming language, if we want to perform any
calculation or to frame any condition etc., we use a set of symbols to
perform the task. These set of symbols makes an expression.
In the C programming language, an expression is defined as follows.
An expression is a collection of operators and operands that represents a
specific value.
In the above definition, an operator is a symbol that performs tasks like
arithmetic operations, logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here
operand can be a direct value or variable or address of memory location.
Expression Types in C: In the C programming language, expressions are
divided into THREE types. They are as follows...
Infix Expression
Postfix Expression
Prefix Expression
The above classification is based on the operator position in the expression.
Infix Expression: The expression in which the operator is used between
operands is called infix expression.
Syntax: Operand1 Operator Operand2
Example: (a + b)
Postfix Expression: The expression in which the operator is used after
operands is called postfix expression.
Syntax: Operand1 Operand2 Operator
Example: ab+
Prefix Expression: The expression in which the operator is used before
operands is called a prefix expression.
Syntax: Operator Operand1 Operand2
Example: +ab
OPERATOR PRECEDENCE AND ASSOCIATIVITY:
Operator Precedence:
Operator precedence is used to determine the order of operators evaluated
in an expression. In c programming language every operator has precedence
(priority). When there is more than one operator in an expression the
operator with higher precedence is evaluated first and the operator with the
least precedence is evaluated last.
Operator Associativity:
Operator associativity is used to determine the order of operators with equal
precedence evaluated in an expression. In the c programming language,
when an expression contains multiple operators with equal precedence, we
use associativity to determine the order of evaluation of those operators.
In c programming language the operator precedence and associativity are as
shown in the following table.
Precedence Operator Operator Meaning Associativity
1 () function call Left to Right
[] array reference
-> structure member
. access
structure member
access
2 ! negation Right to Left
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
-- decrement operator
& address of operator
* pointer
sizeof returns size of a
(type) variable
type conversion
3 * multiplication Left to Right
/ division
% remainder
4 + addition Left to Right
- subtraction
5 << left shift Left to Right
>> right shift
6 < less than Left to Right
<= less than or equal to
> greater than
>= greater than or equal
to
7 == equal to Left to Right
!= not equal to
8 & bitwise AND Left to Right
9 ^ bitwise EXCLUSIVE Left to Right
OR
10 | bitwise OR Left to Right
11 && logical AND Left to Right
12 || logical OR Left to Right
13 ?: conditional operator Left to Right
14 = assignment Right to Left
*= assign multiplication
/= assign division
%= assign remainder
+= assign addition
-= assign subtraction
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift
15 , separator Left to Right
In the above table, the operator precedence decreases from top to bottom
and increases from bottom to top.
Expression Evaluation:
In the C programming language, an expression is evaluated based on the
operator precedence and associativity. When there are multiple operators in
an expression, they are evaluated according to their precedence and
associativity. The operator with higher precedence is evaluated first and the
operator with the least precedence is evaluated last.
An expression is evaluated based on the precedence and associativity of the
operators in that expression.
To understand expression evaluation in c, let us consider the following
simple example expression...
Example: 10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these
three operators, both multiplication and division have the same higher
precedence and addition has lower precedence. So, according to the operator
precedence both multiplication and division are evaluated first and then the
addition is evaluated. As multiplication and division have the same
precedence they are evaluated based on the associativity. Here, the
associativity of multiplication and division is left to right. So, multiplication
is performed first, then division and finally addition. So, the above
expression is evaluated in the order of * / and +. It is evaluated as follows...
4 * 3 => 12
12 / 2 => 6
10 + 6 => 16
The expression is evaluated to 16.
Type Conversion and Type Casting in C:
In a programming language, the expression contains data values of the
same datatype or different data types. When the expression contains similar
datatype values then it is evaluated without any problem. But if the
expression contains two or more different datatype values then they must be
converted to the single datatype of destination datatype.
Here, the destination is the location where the final result of that expression
is stored. For example, the multiplication of an integer data value with the
float data value and storing the result into a float variable. In this case, the
integer value must be converted to float value so that the final result is a
float datatype value.
In a c programming language, the data conversion is performed in two
different methods such as Type Conversion and Type Casting
Type Conversion: The type conversion is the process of converting a data
value from one data type to another data type automatically by the compiler.
Sometimes type conversion is also called implicit type conversion. The
implicit type conversion is automatically performed by the compiler.
For example, in c programming language, when we assign an integer value
to a float variable the integer value automatically gets converted to float
value by adding decimal value 0. And when a float value is assigned to an
integer variable the float value automatically gets converted to an integer
value by removing the decimal value. To understand more about type
conversion observe the following...
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
i = x ; => x value 15.5 is converted as 15 and assigned to variable i
x = i ; => Here i value 10 is converted as 10.000000 and assigned to variable
x
i = ch ; => Here the ASCII value of A (65) is assigned to i
/* Program to demonstrate type conversion */
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;
i=x;
printf("i value is %d\n",i);
x=i;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);
}
Output:
i value is 90
x value is 90.000000
i value is 65
In the above program, we assign i = x, i.e., float variable value is assigned to
the integer variable. Here, the compiler automatically converts the float
value (90.99) into integer value (90) by removing the decimal part of the float
value (90.99) and then it is assigned to variable i. Similarly, when we
assign x = i, the integer value (90) gets converted to float value (90.000000)
by adding zero as the decimal part.
Typecasting:
Typecasting is also called an explicit type conversion. Compiler converts
data from one data type to another data type implicitly. When compiler
converts implicitly, there may be a data loss. In such a case, we convert the
data from one data type to another data type using explicit type conversion.
To perform this we use the unary cast operator.
To convert data from one type to another type we specify the target data type
in parenthesis as a prefix to the data value that has to be converted. The
general syntax of typecasting is as follows.
Syntax: (TargetDatatype) DataValue
Example: int totalMarks = 450, maxMarks = 600 ;
float average ;
average = (float) totalMarks / maxMarks * 100 ;
In the above example code, both totalMarks and maxMarks are integer data
values. When we perform totalMarks / maxMarks the result is a float value,
but the destination (average) datatype is a float. So we use type casting to
convert totalMarks and maxMarks into float data type.
/* Program to demonstrate Type Casting */
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c ;
float avg ;
printf("Enter any three integer values : ");
scanf(“%d%%d”,&a,&b,&c);
avg = (a + b + c) / 3 ;
printf(“avg before casting = %f",avg);
avg = (float)(a + b + c) / 3 ;
printf("avg after casting = " << avg << endl;
return 0;
}
Output:
Enter any three integer values : 10 20 30
avg before casting = 20.000000
avg after casting = 20.000000
Declaration of Variable:
Declaration of a variable tells the compiler to allocate the required amount of
memory with the specified variable name and allows only specified datatype
values into that memory location. In C programming language, the
declaration can be performed either before the function as global variables
or inside any block or function. But it must be at the beginning of block or
function.
Syntax: datatype variableName;
Example: int number;
The above declaration tells to the compiler that allocates 2 bytes of memory
with the name number and allows only integer values into that memory
location.
Creating constants in C:
In a c programming language, constants can be created using two
concepts...
Using the 'const' keyword
Using '#define' preprocessor
Using the 'const' keyword: We create a constant of any datatype using
'const' keyword. To create a constant, we prefix the variable declaration with
'const' keyword.
Syntax: const datatype constantName;
(OR)
const datatype constantName = value ;
Example: const int x = 10 ;
Here, 'x' is a integer constant with fixed value 10.
/* Program to illustrate const keyword */
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 9 ;
const int x = 10 ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
}
The above program gives an error because we are trying to change the
constant variable value (x = 100).
Using '#define' preprocessor: We can also create constants using '#define'
preprocessor directive. When we create constant using this preprocessor
directive it must be defined at the beginning of the program (because all the
preprocessor directives must be written before the global declaration).
Syntax: #define CONSTANTNAME value
Example: #define PI 3.14
Here, PI is a constant with value 3.14
/* Program to illustrate #define function */
#include<stdio.h>
#include<conio.h>
#define PI 3.14
void main()
{
int r, area ;
printf("Please enter the radius of circle : ") ;
scanf("%d", &r) ;
area = PI * (r * r) ;
printf("Area of the circle = %d", area) ;
}
CONTROL STRUCTURES:
Control structures are tests which controls the flow of execution of a
program. There are 4 types of control structures. They are…
Sequence Structures
Decision Structures
Selection Structures
Iterative Structures
Sequence Structures:
In this type of control structures all the statements of a program are
executed in sequence (one-by-one).
Decision Structures:
In this type of control structures some of the statements are executed and
some of the statements are skipped.
'if' Statement in C: ‘if’ is a conditional executable statement, which allows
the user to pass through a condition. It has four forms…
Simple if statement
if-else statement
Nested if statement
if-else-if statement (if-else ladder)
Simple if: In case of simple if, a condition is tested, if it is true only, the
statement part followed by ‘if’ will be executed.
Example: bonus = 0;
if(salary <=5000)
bonus = 500;
printf(“\n Bonus = %d”, bonus);
/* Program to Test whether given number is divisible by 5.
#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5\n") ;
printf("statement does not belong to if!!!") ;
}
Output 1:
Enter any integer number: 25
Given number is divisible by 5
statement does not belong to if!!!"
Output 2:
Enter any integer number: 33
statement does not belong to if!!!"
if…else: The if-else statement is used to verify the given condition and
executes only one out of the two blocks of statements based on the condition
result. The if-else statement evaluates the specified condition.
If it is TRUE, it executes a block of statements (True block). If the condition
is FALSE, it executes another block of statements (False block). The general
syntax and execution flow of the if-else statement is as follows.
The if-else statement is used when we have two options and only one option
has to be executed based on a condition result (TRUE or FALSE).
Example: if(salary <= 5000)
bonus = 500;
else
bonus = 1000;
printf(“\nBonus = %d”, bonus);
/* Program to Test whether given number is even or odd. */
#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ;
}
Output 1:
Enter any integer number: 10
Given number is EVEN
Output 2:
Enter any integer number: 15
Given number is ODD
Nested if: Writing a if statement inside another if statement is called nested
if statement. The general syntax of the nested if statement is as follows...
The nested if statement can be defined using any combination of simple if &
if-else statements.
/* Program to Test whether given number is even or odd if it is below
100. */
#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
Output 1:
Enter any integer number: 55
Given number is below 100
And it is ODD
Output 2:
Enter any integer number: 66
Given number is below 100
And it is EVEN
Output 3:
Enter any integer number: 125
Given number is not below 100
else…if ladder: Writing a if statement inside else of an if statement is called
if-else-if statement. The general syntax of the if-else-if statement is as
follows...
The if-else-if statement can be defined using any combination of simple if &
if-else statements.
/* Program to Find the largest of three numbers. */
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c ;
clrscr() ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
}
Output:
Enter any three integer numbers: 5 10 15
15 is the largest number
Selection Structures:
In case of selection structures, based on the value of an expression a
specific block of statements will be executed.
switch: Switch is a conditional branching statement, which transfers the
control to the specific block based on the value of an expression.
In the switch statement, we provide a value that is to be compared with a
value associated with each option. Whenever the given value matches the
value associated with an option, the execution starts from that option. In the
switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
The switch statement contains one or more cases and each case has a value
associated with it. At first switch statement compares the first case value
with the switchValue, if it gets matched the execution starts from the first
case. If it doesn't match the switch statement compares the second case
value with the switchValue and if it is matched the execution starts from the
second case.
This process continues until it finds a match. If no case value matches with
the switchValue specified in the switch statement, then a special case
called default is executed.
When a case value matches with the switchValue, the execution starts from
that particular case. This execution flow continues with the next case
statements also. To avoid this, we use the "break" statement at the end of
each case. That means the break statement is used to terminate the switch
statement. However, it is optional.
/* Program to Display pressed digit in words */
#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any digit: ") ;
scanf("%d", &n) ;
switch( n )
{
case 0: printf("ZERO") ; break ;
case 1: printf("ONE") ; break ;
case 2: printf("TWO") ; break ;
case 3: printf("THREE") ; break ;
case 4: printf("FOUR") ; break ;
case 5: printf("FIVE") ; break ;
case 6: printf("SIX") ; break ;
case 7: printf("SEVEN") ; break ;
case 8: printf("EIGHT") ; break ;
case 9: printf("NINE") ; break ;
default: printf("Not a Digit") ; break;
}
getch() ;
}
Output 1:
Enter any digit: 5
Five
Output 2:
Enter any digit: 25
Not a Digit
Iterative Structures:
In case of iterative structures some of the statements of a program are
repeated for several number of times. The three iterative structures are…
while loop
do…while loop
for loop
'while' loop: It is a conditional repetitive control structure. It is an enry
controlled structure. The statement part of the structure will be repeated as
long as the condition remains true. The statement part of the structure will
not be executed at least once if the condition is not satisfied.
Example: i = 1;
while(i<=10)
{
printf(“\n%d”,i);
i = i + 1;
}
/* Program to display even numbers upto 10 */
#include<stdio.h>
#include<conio.h>
void main()
{
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
getch() ;
}
Output:
Even numbers upto 10
0 2 4 6 8 10
'do-while' loop: It is a conditional repetitive control structure. It is an exit
controlled structure. The statement part of the structure will be repeated as
long as the condition remains true. The statement part of the structure will
be executed at once though the condition is not satisfied.
Example: i = 1;
do
{
printf(“\n%d”,i);
i = i + 1;
}while(i<=10);
/* Program to display even numbers upto 10 */
#include<stdio.h>
#include<conio.h>
void main()
{
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;
getch() ;
}
Output:
Even numbers upto 10
0 2 4 6 8 10
'for' loop: It is a conditional repetitive control structure. It is an enry
controlled structure. The statement part of the structure will be repeated as
long as the condition remains true. The statement part of the structure will
not be executed at least once if the condition is not satisfied.
It is similar to while loop but it includes all the three (initialization, test
expression, increment/decrement) into a single statement.
/* Program to display even numbers upto 10 */
#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)
printf("%d\t", n) ;
}
getch() ;
}
Output:
Even numbers upto 10
0 2 4 6 8 10
break, continue and goto in C:
In c, there are control statements that do not need any condition to control
the program execution flow. These control statements are called
as unconditional control statements. C programming language provides the
following unconditional control statements...
break
continue
goto
The above three statements do not need any condition to control the
program execution flow.
break statement: In C, the break statement is used to perform the
following two things...
break statement is used to terminate the switch case statement
break statement is also used to terminate looping statements like
while, do-while and for.
When a break statement is encountered inside the switch case statement,
the execution control moves out of the switch statement directly. For
example, consider the following program.
/* Program to perform all arithmetic operations using switch
statement */
#include<stdio.h>
#include<conio.h>
void main()
{
int n1, n2 ;
char operator;
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &number1, &number2) ;
printf("Please enter any arithmetic operator: ");
operator = getchar();
switch(operator)
{
case '+' : printf("Addition = %d", n1+n2) ; break;
case '-' : printf("Subtraction = %d", n1-n2) ; break;
case '*' : printf("Multiplication = %d", n1*n2) ; break;
case '/': printf("Division = %d", n1/n2) ; break;
case '%': printf("Remainder = %d", n1%n2) ; break;
default: printf("\nWrong selection!!!") ; break;
}
getch() ;
}
Output:
Enter any two integer numbers: 10 20
Please enter any arithmetic operator: *
Multiplication = 200
When the break statement is encountered inside the looping statement, the
execution control moves out of the looping statements. The break statement
execution is as shown in the following figure.
For example, consider the following example program...
/* Program for to demonstrate break statement */
#include<stdio.h>
#include<conio.h>
void main()
{
char ch ;
clrscr() ;
do
{
printf("Enter Y / N : ") ;
scanf("%c", &ch) ;
if(ch == 'Y')
{
printf("Okay!!! Repeat again !!!\n") ;
}
else
{
printf("Okay !!! Breaking the loop !!!") ;
break ;
}
} while( 1 ) ;
getch() ;
}
Output:
Do you want to repeat – Enter Y / N : Y
Okay!!! Repeat again!!!
Do you want to repeat – Enter Y / N : N
Okay !!! Breaking the loop !!!
continue statement: The continue statement is used to move the program
execution control to the beginning of the looping statement. When
the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly
jumps to the beginning of the loop. The continue statement can be used
with looping statements like while, do-while and for.
When we use continue statement with while and do-while statements the
execution control directly jumps to the condition. When we
use continue statement with for statement the execution control directly
jumps to the modification portion (increment/decrement/any modification)
of the for loop. The continue statement execution is as shown in the
following figure.
/* Program to illustrate continue statement */
#include<stdio.h>
#include<conio.h>
void main()
{
int number ;
clrscr() ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{
printf("Entered number is EVEN!!! Try another number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD number!!! Bye!!!") ;
exit(0) ;
}
}
getch() ;
}
Output:
Enter any integer number: 10
Entered number is EVEN!!! Try another number!!!
Enter any integer number: 15
You have entered ODD number!!! Bye!!!
goto statement: The goto statement is used to jump from one line to
another line in the program. Using goto statement we can jump from top to
bottom or bottom to top. To jump from one line to another line, the goto
statement requires a label. Label is a name given to the instruction or line in
the program. When we use a goto statement in the program, the execution
control directly jumps to the line with the specified label.
/* Program to demonstrate goto statement */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}
Output:
We are at first printf statement!!!
We are at last printf statement!!!
FUNCTIONS IN C:
When we write a program to solve a larger problem, we divide that larger
problem into smaller subproblems and are solved individually to make the
program easier. In C, this concept is implemented using functions.
Functions are used to divide a larger program into smaller subprograms
such that the program becomes easy to understand and easy to implement.
A function is defined as follows...
Function is a subpart of a program used to perform a specific task and is
executed individually. Every C program must contain at least one function
called main(). However, a program may also contain other functions.
Every function in C has the following...
Function Declaration (Function Prototype)
Function Definition
Function Call
Function Declaration: The function declaration tells the compiler about
function name, the data type of the return value and parameters. The
function declaration is also called a function prototype. The function
declaration is performed before the main function or inside the main
function or any other function.
Syntax: returnType functionName(parametersList);
In the above syntax, returnType specifies the data type of the value which is
sent as a return value from the function definition. The functionName is a
user-defined name used to identify the function uniquely in the program.
The parametersList is the data values that are sent to the function
definition.
Function Definition: The function definition provides the actual code of
that function. The function definition is also known as the body of the
function. The actual task of the function is implemented in the function
definition. That means the actual instructions to be performed by a function
are written in function definition. The actual instructions of a function are
written inside the braces "{ }". The function definition is performed before the
main function or after the main function.
Syntax: returnType functionName(parametersList)
{
Actual code...
}
Function Call: The function call tells the compiler when to execute the
function definition. When a function call is executed, the execution control
jumps to the function definition where the actual code gets executed and
returns to the same functions call once the execution completes. The
function call is performed inside the main function or any other function or
inside the function itself.
Syntax: functionName(parameters);
Advantages Of Functions: Using funcions we can implement modular
programming.
Functions make the program more readable and understandable.
Using functions the program implementation becomes easy.
Once a function is created it can be used many times (code re-
usability).
Using functions larger programs can be divided into smaller modules.
Types of Functions in C: In C Programming Language, based on providing
the function definition, functions are divided into two types. Those are as
follows...
System Defined Functions
User Defined Functions
System Defined Functions: The C Programming Language provides pre-
defined functions to make programming easy. These pre-defined functions
are known as syatem defined functions. The system defined function is
defined as follows...
The function whose definition is defined by the system is called as system
defined function. The system defined functions are also called as Library
Functions or Standard Functions or Pre-Defined Functions. The
implementation of system defined functions is already defined by the
system.
In C, all the system defined functions are defined inside the header
files like stdio.h, conio.h, math.h, string.h etc., For example, the
funtions printf() and scanf() are defined in the header file called stdio.h.
Whenever we use system defined functions in the program, we must include
the respective header file using #include statement. For example, if we use a
system defined function sqrt() in the program, we must include the header
file called math.h because the function sqrt() is defined in math.h.
/* Program to demonstrate functions */
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2, result ;
int addition(int,int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("SUM = %d", result);
getch() ;
}
int addition(int a, int b) // function definition
{
return a+b ;
}
In the above example program, the function declaration statement "int
addition(int,int)" tells the compiler that there is a function with
name addition which takes two integer values as parameters and returns an
integer value. The function call statement takes the execution control to
the additon() definition along with values of num1 and num2. Then function
definition executes the code written inside it and comes back to the function
call along with return value.
In the concept of functions, the function call is known as "Calling
Function" and the function definition is known as "Called Function".
When we make a function call, the execution control jumps from calling
function to called function. After executing the called function, the execution
control comes back to calling function from called function. When the
control jumps from calling function to called function it may carry one or
more data values called "Paramenters" and while coming back it may carry a
single value called "return value". That means the data values transferred
from calling function to called function are called as Parameters and the
data value transferred from called funcion to calling function is
called Return value.
Categories of Functions:
Based on the data flow between the calling function and called function, the
functions are classified as follows...
Function without Parameters and without Return value
Function with Parameters and without Return value
Function without Parameters and with Return value
Function with Parameters and with Return value
Function without Parameters and without Return value: In this type of
functions there is no data transfer between calling function and called
function. Simply the execution control jumps from calling-function to called
function and executes called function, and finally comes back to the calling
function. For example, consider the following program...
/* Program to demonstrate Function without Parameters and without
Return value */
#include<stdio.h>
#include<conio.h>
void main()
{
void addition() ; // function declaration
clrscr() ;
addition() ; // function call
getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}
Function with Parameters and without Return value: In this type of
functions there is data transfer from calling-function to called function
(parameters) but there is no data transfer from called function to calling-
function (return value). The execution control jumps from calling-function to
called function along with the parameters and executes called function, and
finally comes back to the calling function. For example, consider the
following program...
/* Program to demonstrate Function with Parameters and without
Return value */
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
Function without Parameters and with Return value: In this type of
functions there is no data transfer from calling-function to called-function
(parameters) but there is data transfer from called function to calling-
function (return value). The execution control jumps from calling-function to
called function and executes called function, and finally comes back to the
calling function along with a return value. For example, consider the
following program...
/* Program to demonstrate Function without Parameters and with
Return value */
#include<stdio.h>
#include<conio.h>
void main()
{
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
Function with Parameters and with Return value: In this type of
functions there is data transfer from calling-function to called-function
(parameters) and also from called function to calling-function (return value).
The execution control jumps from calling-function to called function along
with parameters and executes called function, and finally comes back to the
calling function along with a return value. For example, consider the
following program...
/* Program to demonstrate Function with Parameters and with Return
value */
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
Parameter Passing in C:
When a function gets executed in the program, the execution control is
transferred from calling-function to called function and executes function
definition, and finally comes back to the calling function. When the
execution control is transferred from calling-function to called-function it
may carry one or number of data values. These data values are called
as parameters.
Parameters are the data values that are passed from calling function to
called function. In C, there are two types of parameters and they are as
follows...
Actual Parameters
Formal Parameters
The actual parameters are the parameters that are speficified in calling
function. The formal parameters are the parameters that are declared at
called function. When a function gets executed, the copy of actual parameter
values are copied into formal parameters.
In C Programming Language, there are two methods to pass parameters
from calling function to called function and they are as follows...
Call by Value
Call by Reference
Call by Value: In call by value parameter passing method, the copy of
actual parameter values are copied to formal parameters and these formal
parameters are used in called function. The changes made on the formal
parameters does not effect the values of actual parameters. That means,
after the execution control comes back to the calling function, the actual
parameter values remains same. For example consider the following
program...
/* Program to demonstrate Call-by-Value */
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);
getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 10, num2 = 20
In the above example program, the variables num1 and num2 are called
actual parameters and the variables a and b are called formal parameters.
The value of num1 is copied into a and the value of num2 is copied into b.
The changes made on variables a and b does not effect the values
of num1 and num2.
Call by Reference: In Call by Reference parameter passing method, the
memory location address of the actual parameters is copied to formal
parameters. This address is used to access the memory locations of the
actual parameters in called function. In this method of parameter passing,
the formal parameters must be pointer variables.
That means in call by reference parameter passing method, the address of
the actual parameters is passed to the called function and is recieved by the
formal parameters (pointers). Whenever we use these formal parameters in
called function, they directly access the memory locations of actual
parameters. So the changes made on the formal parameters effects the
values of actual parameters. For example consider the following program...
/* Program to demonstrate call-by-reference */
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10
In the above example program, the addresses of
variables num1 and num2 are copied to pointer variables a and b. The
changes made on the pointer variables a and b in called function effects the
values of actual parameters num1 and num2 in calling function.
Inter Function Communication in C
When a function gets executed in the program, the execution control is
transferred from calling a function to called function and executes function
definition, and finally comes back to the calling function. In this process,
both calling and called functions have to communicate with each other to
exchange information. The process of exchanging information between
calling and called functions is called inter-function communication.
In C, the inter function communication is classified as follows...
Downward Communication
Upward Communication
Bi-directional Communication
Downward Communication: In this type of inter function communication,
the data is transferred from calling function to called function but not from
called function to calling function. The functions with parameters and
without return value are considered under downward communication. In the
case of downward communication, the execution control jumps from calling
function to called function along with parameters and executes the function
definition,and finally comes back to the calling function without any return
value. For example consider the following program...
/* Program to demonstrate Downward Communication */
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
addition(num1, num2) ; // calling function
getch() ;
}
void addition(int a, int b) // called function
{
printf("SUM = %d", a+b) ;
}
Output:
Before swap: num1 = 10, num2 = 20
SUM = 30
Upward Communication: In this type of inter-function communication, the
data is transferred from called function to calling-function but not from
calling-function to called-function. The functions without parameters and
with return value are considered under upward communication. In the case
of upward communication, the execution control jumps from calling-
function to called-function without parameters and executes the function
definition, and finally comes back to the calling function along with a return
value. For example, consider the following program...
/* Program to demonstrate Upward Communication */
#include<stdio.h>
#include<conio.h>
void main()
{
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // calling function
printf("SUM = %d", result) ;
getch() ;
}
int addition() // called function
{
int num1, num2 ;
num1 = 10;
num2 = 20;
return (num1+num2) ;
}
Output:
SUM = 30
Bi - Directional Communication: In this type of inter-function
communication, the data is transferred from calling-function to called
function and also from called function to calling-function. The functions
with parameters and with return value are considered under bi-directional
communication. In the case of bi-directional communication, the execution
control jumps from calling-function to called function along with parameters
and executes the function definition and finally comes back to the calling
function along with a return value. For example, consider the following
program...
/* Program to demonstrate Bi - Directional Communication */
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
result = addition(num1, num2) ; // calling function
printf("SUM = %d", result) ;
getch() ;
}
int addition(int a, int b) // called function
{
return (a+b) ;
}
Output:
SUM = 30
Standard Functions in C:
The standard functions are built-in functions. In C programming language,
the standard functions are declared in header files and defined in .dll files.
In simple words, the standard functions can be defined as "the ready made
functions defined by the system to make coding more easy". The standard
functions are also called as library functions or pre-defined functions.
In C when we use standard functions, we must include the respective
header file using #include statement. For example, the function printf() is
defined in header file stdio.h (Standard Input Output header file). When we
use printf() in our program, we must include stdio.h header file
using #include<stdio.h> statement. C Programming Language provides the
following header files with standard functions.
Header Example
File Purpose Functions
stdio.h Provides functions to perform standard I/O printf(), scanf()
operations
conio.h Provides functions to perform console I/O clrscr(), getch()
operations
math.h Provides functions to perform mathematical sqrt(), pow()
operations
string.h Provides functions to handle string data values strlen(), strcpy()
stdlib.h Provides functions to perform general calloc(), malloc()
functions/td>
time.h Provides functions to perform operations on time time(), localtime()
and date
ctype.h Provides functions to perform - testing and isalpha(), islower()
mapping of character data values
setjmp.h Provides functions that are used in function calls setjump(),
longjump()
signal.h Provides functions to handle signals during signal(), raise()
program execution
assert.h Provides Macro that is used to verify assumptions assert()
made by the program
locale.h Defines the location specific settings such as date setlocale()
formats and currency symbols
stdarg.h Used to get the arguments in a function if the va_start(),
arguments are not specified by the function va_end(), va_arg()
errno.h Provides macros to handle the system calls Error, errno
graphics.h Provides functions to draw graphics. circle(), rectangle()
float.h Provides constants related to floating point data
values
stddef.h Defines various variable types
limits.h Defines the maximum and minimum values of
various variable types like char, int and long
Scope of Variable in C:
When we declare a variable in a program, it can not be accessed against the
scope rules. Variables can be accessed based on their scope. The scope of a
variable decides the portion of a program in which the variable can be
accessed. The scope of the variable is defined as follows...
Scope of a variable is the portion of the program where a defined variable
can be accessed.
The variable scope defines the visibility of variable in the program. Scope of
a variable depends on the position of variable declaration.
In C programming language, a variable can be declared in three different
positions and they are as follows...
Before the function definition (Global Declaration)
Inside the function or block (Local Declaration)
In the function definition parameters (Formal Parameters)
Before the function definition (Global Declaration): Declaring a variable
before the function definition (outside the function definition) is called global
declaration. The variable declared using global declaration is called global
variable. Tha global variable can be accessed by all the functions that are
defined after the global declaration. That means the global variable can be
accessed any where in the program after its declaration. The global variable
scope is said to be file scope.
/* Program to demonstrate Before the function definition (Global
Declaration) */
#include<stdio.h>
#include<conio.h>
int num1, num2 ;
void main()
{
void addition() ;
void subtraction() ;
void multiplication() ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
subtraction() ;
multiplication() ;
getch() ;
}
void addition()
{
int result ;
result = num1 + num2 ;
printf("\naddition = %d", result) ;
}
void subtraction()
{
int result ;
result = num1 - num2 ;
printf("\nsubtraction = %d", result) ;
}
void multiplication()
{
int result ;
result = num1 * num2 ;
printf("\nmultiplication = %d", result) ;
}
Output:
num1 = 10, num2 = 20
addition = 30
subtraction = -10
multiplication = 200
In the above example program, the variables num1 and num2 are declared
as global variables. They are declared before the main() function. So, they
can be accessed by function main() and other functions that are defined
after main(). In the above example, the functions main(), addition(),
subtraction() and multiplication() can access the variables num1 and num2.
Inside the function or block (Local Declaration): Declaring a variable
inside the function or block is called local declaration. The variable declared
using local declaration is called local variable. The local variable can be
accessed only by the function or block in which it is declared. That means
the local variable can be accessed only inside the function or block in which
it is declared.
/* Program to demonstrate Inside the function or block (Local
Declaration) */
#include<stdio.h>
#include<conio.h>
void main()
{
void addition() ;
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
getch() ;
}
void addition()
{
int sumResult ;
sumResult = num1 + num2 ;
printf("\naddition = %d", sumResult) ;
}
Output:
num1 = 10, num2 = 20
addition = 0
The above example program shows an error because, the variables num1
and num2 are declared inside the function main(). So, they can be used only
inside main() function and not in addition() function.
In the function definition parameters (Formal Parameters): The
variables declared in function definition as parameters have a local variable
scope. These variables behave like local variables in the function. They can
be accessed inside the function but not outside the function.
/* Program to demonstrate In the function definition parameters
(Formal Parameters) */
#include<stdio.h>
#include<conio.h>
void main()
{
void addition(int, int) ;
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
addition(num1, num2) ;
getch() ;
}
void addition(int a, int b)
{
int sumResult ;
sumResult = a + b ;
printf("\naddition = %d", sumResult) ;
}
Output:
addition = 30
In the above example program, the variables a and b are declared in
function definition as parameters. So, they can be used only inside the
addition() function.
C Storage Classes:
In C programming language, storage classes are used to define things
like storage location (whether RAM or REGISTER), scope, lifetime and
the default value of a variable.
In the C programming language, the memory of variables is allocated either
in computer memory (RAM) or CPU Registers. The allocation of memory
depends on storage classes.
In C programming language, there are FOUR storage classes and they are as
follows...
auto storage class
extern storage class
static storage class
register storage class
auto storage class: The default storage class of all local variables (variables
declared inside block or function) is auto storage class. Variable of auto
storage class has the following properties...
Property Description
Keyword auto
Storage Computer Memory (RAM)
Default Value Garbage Value
Scope Local to the block in which the variable is defined
Life time Till the control remains within the block in which variable
is defined
/* Program to demonstrate auto storage class */
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
auto char c;
float f;
printf("i = %d\tc = %c\tf = %f",i,c,f);
return 0;
}
/* Program to demonstrate auto storage class */
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10;
{
int a=20;
printf("%d",a);
}
printf(" %d",a);
return 0;
}
/* Program to demonstrate auto storage class */
#include<stdio.h>
#include<conio.h>
int main()
{
{
int a=20;
printf("%d",a);
}
printf(" %d",a); //a is not visible here
return 0;
}
External storage class: The default storage class of all global varibles
(variables declared outside function) is external storage class. Variable of
external storage class has the following properties...
Property Description
Keyword extern
Storage Computer Memory (RAM)
Default Value Zero
Scope Global to the program (i.e., Throughout the program)
Life time As long as the program’s execution does not comes to end
/* Program to demonstrate extern storage class */
#include<stdio.h>
#include<conio.h>
int i; //By default it is extern variable
int main()
{
printf("%d",i);
return 0;
}
/* Program to demonstrate auto storage class */
#include<stdio.h>
#include<conio.h>
extern int i; //extern variable
int main()
{
printf("%d",i);
return 0;
}
Static storage class: The static storage class is used to create variables
that hold value beyond its scope until the end of the program. The static
variable allows to initialize only once and can be modified any number of
times. Variable of static storage class has the following properties...
Property Description
Keyword static
Storage Computer Memory (RAM)
Default Value Zero
Scope Local to the block in which the variable is defined
Life time The value of the persists between different function calls
(i.e., Initialization is done only once)
/* Program to demonstrate static storage class */
#include<stdio.h>
#include<conio.h>
static int a;
int main()
{
printf("%d",a);
return 0;
}
/* Program to demonstrate static storage class */
#include<stdio.h>
#include<conio.h>
static int i=10;
int main()
{
i=25; //Assignment statement
printf("%d",i);
return 0;
}
Register storage class: The register storage class is used to specify the
memory of the variable that has to be allocated in CPU Registers. The
memory of the register variable is allocated in CPU Register but not in
Computer memory (RAM). The register variables enable faster accessibility
compared to other storage class variables. As the number of registers inside
the CPU is very less we can use very less number of register variables.
Variable of register storage class has the following properties...
Property Description
Keyword register
Storage CPU Register
Default Value Garbage Value
Scope Local to the block in which the variable is defined
Life time Till the control remains within the block in which variable
is defined
/* Program to demonstrate register storage class */
#include<stdio.h>
#include<conio.h>
int main()
{
register int a,b;
scanf("%d%d",&a,&b);
printf("%d %d",a,b);
}
The following table provides detailed properties of all storage classes...
Storage Memory Default
Keyword Scope Life Time
Class Location Value
Till the
control
Local to the
remains
Computer block in
Garbage within the
Automatic auto Memory which the
Value block in
(RAM) variable
which
has defined
variable is
defined
Global to
As long as
the
the
Computer program
program’s
External extern Memory Zero (i.e.,
execution
(RAM) Throughout
does not
the
come to end
program)
The value of
the persists
Local to the between
Computer block in different
Static static Memory Zero which the function
(RAM) variable calls (i.e.,
has defined Initialization
is done only
once)
Till the
control
Local to the
remains
block in
CPU Garbage within the
Register register which the
Register Value block in
variable
which
has defined
variable is
defined
Recursive Functions in C:
In C programming language, function calls can be made from the main()
function, other functions or from the same function itself. The recursive
function is defined as follows...
A function called by itself is called recursive function.
The recursive functions should be used very carefully because, when a
function called by itself it enters into the infinite loop. And when a function
enters into the infinite loop, the function execution never gets completed. We
should define the condition to exit from the function call so that the
recursive function gets terminated.
When a function is called by itself, the first call remains under execution till
the last call gets invoked. Every time when a function call is invoked, the
function returns the execution control to the previous function call.
/* Program to demonstrate Recursive Function */
#include<stdio.h>
#include<conio.h>
int factorial( int ) ;
int main()
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ;
printf("\nFactorial of %d is %d\n", n, fact) ;
return 0;
}
int factorial( int n )
{
int temp ;
if( n == 0)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}
Output:
Enter any positive integer: 5
Factorial of 5 is 120
In the above example program, the factorial() function call is initiated from
main() function with the value 3. Inside the factorial() function, the function
calls factorial(2), factorial(1) and factorial(0) are called recursively. In this
program execution process, the function call factorial(3) remains under
execution till the execution of function calls factorial(2), factorial(1) and
factorial(0) gets completed. Similarly the function call factorial(2) remains
under execution till the execution of function calls factorial(1) and
factorial(0) gets completed. In the same way the function call factorial(1)
remains under execution till the execution of function call factorial(0) gets
completed. The complete execution process of the above program is shown
in the following figure...
Type Qualifiers in C:
In C programming language, type qualifiers are the keywords used to modify
the properties of variables. Using type qualifiers, we can change the
properties of variables. The c programming language provides two type
qualifiers and they are as follows...
const
volatile
const type qualifier in C: The const type qualifier is used to create
constant variables. When a variable is created with const keyword, the value
of that variable can't be changed once it is defined. That means once a value
is assigned to a constant variable, that value is fixed and cannot be changed
throughout the program.
The keyword const is used at the time of variable declaration. We use the
following syntax to create constant variable using const keyword.
const datatype variableName ;
When a variable is created with const keyword it becomes a constant
variable. The value of the constant variable can't be changed once it is
defined. The following program generates error message because we try to
change the value of constant variable x.
/* Program to demonstrate const type qualifier in C */
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 9 ;
const int x = 10 ;
clrscr() ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
}
volatile type qualifier in C: The volatile type qualifier is used to create
variables whose values can't be changed in the program explicitly but can be
changed by any external device or hardware.
For example, the variable which is used to store system clock is defined as a
volatile variable. The value of this variable is not changed explicitly in the
program but is changed by the clock routine of the operating system.
Preprocessor Commands in C :
In C programming language, preprocessor directive is a step performed
before the actual source code compilation. It is not part of the compilation.
Preprocessor directives in C programming language are used to define and
replace tokens in the text and also used to insert the contents of other files
into the source file.
When we try to compile a program, preprocessor commands are executed
first and then the program gets compiled.
Every preprocessor command begins with # symbol. We can also create
preprocessor commands with parameters.
Following are the preprocessor commands in C programming language...
#define: #define is used to create symbolic constants (known as macros) in
C programming language. This preprocessor command can also be used
with parameterized macros.
/* Program to demonstrate #define */
#include<stdio.h>
#include<conio.h>
#define PI 3.14
#define SQR(x) x*x //Parameterized Macro
void main()
{
double radius, area ;
clrscr() ;
printf("Enter the radius: ");
scanf("%ld",&radius);
area = PI * SQR(radius) ;
printf("area = %ld",area);
getch();
}
Output:
Ener the radius: 2
Area = 12.560000
#undef: #undef is used to destroy a macro that was already created using
#define.
#ifdef: #ifdef returns TRUE if the macro is defined and returns FALSE if the
macro is not defined.
#ifndef: #ifndef returns TRUE if the specified macro is not defined
otherwise returns FALSE.
#if: #if uses the value of specified macro for conditional compilation.
#else: #else is an alternative for #if.
#elif: #elif is a #else followed by #if in one statement.
#endif: #endif is used terminate preprocessor conditional macro.
#include: #include is used to insert specific header file into C program.
#error: #error is used to print error message on stderr.
#pragma: #pragma is used to issue a special command to the compiler.
In C programming language, there are some pre-defined macros and they
are as follows...
__ DATE __ : The current date as characters in "MMM DD YYYY" format.
__ TIME __ : The current time as characters in "HH : MM : SS" format.
__ FILE __ : This contains the current file name.
__ LINE __ : This contains the current line number.
__ STDC __ : Defines 1 when compiler compiles with ANSI Standards.
ARRAYS:
When we work with a large number of data values we need that any number
of different variables. As the number of variables increases, the complexity
of the program also increases and so the programmers get confused with the
variable names. There may be situations where we need to work with a large
number of similar data values. To make this work easier, C programming
language provides a concept called "Array".
An array is a special type of variable used to store multiple values of same
data type at a time.
An array can also be defined as follows...
An array is a collection of similar data items stored in continuous memory
locations with single name.
Declaration of an Array:
In C programming language, when we want to create an array we must
know the datatype of values to be stored in that array and also the number
of values to be stored in that array.
We use the following general syntax to create an array...
Syntax: datatype arrayName [ size ] ;
Syntax for creating an array with size and initial values
Syntax: datatype arrayName [ size ] = {value1, value2, ...} ;
Syntax for creating an array without size and with initial values
Syntax: datatype arrayName [ ] = {value1, value2, ...} ;
In the above syntax, the datatype specifies the type of values we store in
that array and size specifies the maximum number of values that can be
stored in that array.
Example: int a [3] ;
Here, the compiler allocates 6 bytes of contiguous memory locations with a
single name 'a' and tells the compiler to store three different integer values
(each in 2 bytes of memory) into that 6 bytes of memory. For the above
declaration, the memory is organized as follows...
In the above memory allocation, all the three memory locations have a
common name 'a'. So accessing individual memory location is not possible
directly. Hence compiler not only allocates the memory but also assigns a
numerical reference value to every individual memory location of an array.
This reference number is called "Index" or "subscript" or "indices". Index
values for the above example are as follows...
Accessing Individual Elements of an Array
The individual elements of an array are identified using the combination of
'arrayName' and 'indexValue'. We use the following general syntax to access
individual elements of an array...
Syntax: arrayName [ indexValue ] ;
For the above example the individual elements can be denoted as follows...
For example, if we want to assign a value to the second memory location of
above array 'a', we use the following statement...
Example: a [1] = 100 ;
The result of the above assignment statement is as follows...
Types of Arrays in C:
In c programming language, arrays are classified into two types. They are as
follows...
Single Dimensional Array / One Dimensional Array
Multi Dimensional Array
Single Dimensional Array / One Dimensional Array:
In c programming language, single dimensional arrays are used to store list
of values of same datatype. In other words, single dimensional arrays are
used to store a row of values. In single dimensional array, data is stored in
linear form. Single dimensional arrays are also called as one-dimensional
arrays, Linear Arrays or simply 1-D Arrays.
Declaration of Single Dimensional Array: We use the following general
syntax for declaring a single dimensional array...
Syntax: datatype arrayName [ size ] ;
Example: int rollNumbers [60] ;
The above declaration of single dimensional array reserves 60 continuous
memory locations of 2 bytes each with the name rollNumbers and tells the
compiler to allow only integer values into those memory locations.
Initialization of Single Dimensional Array: We use the following general
syntax for declaring and initializing a single dimensional array with size and
initial values.
Syntax: datatype arrayName [ size ] = {value1, value2, ...} ;
Example: int marks [6] = { 89, 90, 76, 78, 98, 86 } ;
The above declaration of single dimensional array reserves 6 contiguous
memory locations of 2 bytes each with the name marks and initializes with
value 89 in first memory location, 90 in second memory location, 76 in third
memory location, 78 in fourth memory location, 98 in fifth memory location
and 86 in sixth memory location.
We can also use the following general syntax to intialize a single dimensional
array without specifying size and with initial values...
Syntax: datatype arrayName [ ] = {value1, value2, ...} ;
The array must be initialized if it is created without specifying any size. In
this case, the size of the array is decided based on the number of values
initialized.
Example: int marks [] = { 89, 90, 76, 78, 98, 86 } ;
char studentName [] = "economictimes" ;
In the above example declaration, size of the array 'marks' is 6 and the size
of the array 'studentName' is 16. This is because in case of character array,
compiler stores one exttra character called \0 (NULL) at the end.
Accessing Elements of Single Dimensional Array: In c programming
language, to access the elements of single dimensional array we use array
name followed by index value of the element that to be accessed. Here the
index value must be enclosed in square braces. Index value of an element in
an array is the reference number given to each element at the time of
memory allocation. The index value of single dimensional array starts with
zero (0) for first element and incremented by one for each element. The index
value in an array is also called as subscript or indices.
We use the following general syntax to access individual elements of single
dimensional array...
Syntax: arrayName [ indexValue ];
Example: marks [2] = 99 ;
In the above statement, the third element of 'marks' array is assinged with
value '99'.
Multi Dimensional Array:
An array of arrays is called as multi dimensional array. In simple words, an
array created with more than one dimension (size) is called as multi
dimensional array. Multi dimensional array can be of two dimensional
array or three dimensional array or four dimensional array or more...
Most popular and commonly used multi dimensional array is two
dimensional array. The 2-D arrays are used to store data in the form of
table. We also use 2-D arrays to create mathematical matrices.
Declaration of Two Dimensional Array: We use the following general
syntax for declaring a two dimensional array...
Syntax: datatype arrayName [ rowSize ] [ columnSize ] ;
Example: int matrix_A [2][3] ;
The above declaration of two dimensional array reserves 6 continuous
memory locations of 2 bytes each in the form of 2 rows and 3 columns.
Initialization of Two Dimensional Array: We use the following general
syntax for declaring and initializing a two dimensional array with specific
number of rows and coloumns with initial values.
Syntax: datatype arrayName [rows][colmns] = {{r1c1value,
r1c2value, ...},{r2c1, r2c2,...}...} ;
Example: int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
The above declaration of two-dimensional array reserves 6 contiguous
memory locations of 2 bytes each in the form of 2 rows and 3 columns. And
the first row is initialized with values 1, 2 & 3 and second row is initialized
with values 4, 5 & 6.
We can also initialize as follows...
Example: int matrix_A [2][3] = { {1, 2, 3},
{4, 5, 6} };
Accessing Individual Elements of Two Dimensional Array: In a c
programming language, to access elements of a two-dimensional array we
use array name followed by row index value and column index value of the
element that to be accessed. Here the row and column index values must be
enclosed in separate square braces. In case of the two-dimensional array the
compiler assigns separate index values for rows and columns.
We use the following general syntax to access the individual elements of a
two-dimensional array...
Syntax: arrayName [ rowIndex ] [ columnIndex ]
Example: matrix_A [0][1] = 10 ;
In the above statement, the element with row index 0 and column index 1
of matrix_A array is assinged with value 10.
Applications of Arrays in C:
In c programming language, arrays are used in wide range of applications.
Few of them are as follows...
● Arrays are used to Store List of values:
In c programming language, single dimensional arrays are used to store list
of values of same datatype. In other words, single dimensional arrays are
used to store a row of values. In single dimensional array data is stored in
linear form.
● Arrays are used to Perform Matrix Operations:
We use two dimensional arrays to create matrix. We can perform various
operations on matrices using two dimensional arrays.
● Arrays are used to implement Search Algorithms:
We use single dimensional arrays to implement search algorihtms like ...
Linear Search, Binary Search
● Arrays are used to implement Sorting Algorithms:
We use single dimensional arrays to implement sorting algorihtms like ...
Insertion Sort, Bubble Sort, Selection Sort, Quick Sort, Merge Sort, etc.,
● Arrays are used to implement Datastructures:
We use single dimensional arrays to implement datastructures like...
Stack Using Arrays, Queue Using Arrays
● Arrays are also used to implement CPU Scheduling Algorithms:
SEARCHING & SORTING:
Linear Search:
Linear search is a very simple search algorithm. In this type of search, a
sequential search is made over all items one by one. Every item is checked
and if a match is found then that particular item is returned, otherwise the
search continues till the end of the data collection.
/* Program to implement linear search */
#include <stdio.h>
void lsearch(int [], int, int);
void main()
{
int a[10],n,i,x;
printf("\nEnter array size");
scanf("%d",&n);
printf("\nEnter %d elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter element to search");
scanf("%d",&x);
lsearch(a,n,x);
}
void lsearch(int a[],int n, int x)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
printf("\n%d is found at location %d", x, i+1);
exit();
}
}
printf("\n%d is not found",x);
}
Output:
Enter array size 5
Enter 5 elements 12 23 34 45 56
Enter element to search 45
45 is found at location 4
Binary Search:
Binary search is a fast search algorithm with run-time complexity of Ο(log
n). This search algorithm works on the principle of divide and conquer. For
this algorithm to work properly, the data collection should be in the sorted
form.
Binary search looks for a particular item by comparing the middle most item
of the collection. If a match occurs, then the index of item is returned. If the
middle item is greater than the item, then the item is searched in the sub-
array to the left of the middle item. Otherwise, the item is searched for in the
sub-array to the right of the middle item. This process continues on the sub-
array as well until the size of the sub-array reduces to zero.
For a binary search to work, it is mandatory for the target array to be sorted.
We shall learn the process of binary search with a pictorial example. The
following is our sorted array and let us assume that we need to search the
location of value 31 using binary search.
First, we shall determine half of the array by using this formula −
mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the
array.
Now we compare the value stored at location 4, with the value being
searched, i.e. 31. We find that the value at location 4 is 27, which is not a
match. As the value is greater than 27 and we have a sorted array, so we
also know that the target value must be in the upper portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our
target value 31.
The value stored at location 7 is not a match, rather it is more than what we
are looking for. So, the value must be in the lower part from this location.
Hence, we calculate the mid again. This time it is 5.
We compare the value stored at location 5 with our target value. We find
that it is a match.
We conclude that the target value 31 is stored at location 5.
Binary search halves the searchable items and thus reduces the count of
comparisons to be made to very less numbers.
/* Program to implement Binary Search */
#include <stdio.h>
void bsearch(int [], int, int);
void main()
{
int a[10],n,i,x;
printf("\nEnter array size");
scanf("%d",&n);
printf("\nEnter %d elements in order",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter element to search");
scanf("%d",&x);
bsearch(a,n,x);
}
void bsearch(int a[],int n, int x)
{
int l,u,m;
l=0;
u=n-1;
m=(l+u)/2;
while(l<u && a[m]!=x)
{
if(x>a[m])
l=m+1;
if(x<a[m])
u=m-1;
m=(l+u)/2;
}
if(a[m] == x)
printf("\n%d is found at location %d",x,m+1);
else
printf("\n%d is not found",x);
}
Output:
Enter array size 5
Enter 5 elements 12 23 34 45 56
Enter element to search 45
45 is found at location 4
Selection Sort:
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-
place comparison-based algorithm in which the list is divided into two parts,
the sorted part at the left end and the unsorted part at the right end.
Initially, the sorted part is empty and the unsorted part is the entire list.
The smallest element is selected from the unsorted array and swapped with
the leftmost element, and that element becomes a part of the sorted array.
This process continues moving unsorted array boundary by one element to
the right.
This algorithm is not suitable for large data sets as its average and worst
case complexities are of Ο(n2), where n is the number of items.
Consider the following depicted array as an example.
For the first position in the sorted list, the whole list is scanned sequentially.
The first position where 14 is stored presently, we search the whole list and
find that 10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the
minimum value in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of
the list in a linear manner.
We find that 14 is the second lowest value in the list and it should appear at
the second place. We swap these values.
After two iterations, two least values are positioned at the beginning in a
sorted manner.
The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process –
/* Program to Implement Selection Sort */
#include <stdio.h>
void ssort(int [], int);
void main()
{
int a[10],n,i;
printf("\nEnter Array Size");
scanf("%d",&n);
printf("\nEnter %d Elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
ssort(a,n);
printf("\nSorted Elements");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
void ssort(int a[], int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
return;
}
Output:
Enter Array Size 5
Enter 5 Elements 11 99 22 88 33
Sorted Elements 11 22 33 88 99
Bubble Sort:
Bubble sort is a simple sorting algorithm. This sorting algorithm is
comparison-based algorithm in which each pair of adjacent elements is
compared and the elements are swapped if they are not in order. This
algorithm is not suitable for large data sets as its average and worst case
complexity are of Ο(n2) where n is the number of items.
We take an unsorted array for our example. Bubble sort takes Ο(n2) time so
we're keeping it short and precise.
Bubble sort starts with very first two elements, comparing them to check
which one is greater.
In this case, value 33 is greater than 14, so it is already in sorted locations.
Next, we compare 33 with 27.
We find that 27 is smaller than 33 and these two values must be swapped.
The new array should look like this –
Next we compare 33 and 35. We find that both are in already sorted
positions.
Then we move to the next two values, 35 and 10.
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the array.
After one iteration, the array should look like this –
To be precise, we are now showing how an array should look like after each
iteration. After the second iteration, it should look like this –
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is
completely sorted.
/* Program to Implement Bubble Sort */
#include <stdio.h>
void bsort(int [], int);
void main()
{
int a[10],n,i;
printf("\nEnter Array Size");
scanf("%d",&n);
printf("\nEnter %d Elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
bsort(a,n);
printf("\nSorted Elements");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
void bsort(int a[], int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
return;
}
Output:
Enter Array Size 5
Enter 5 Elements 11 99 22 88 33
Sorted Elements 11 22 33 88 99
Insertion Sort:
This is an in-place comparison-based sorting algorithm. Here, a sub-list is
maintained which is always sorted. For example, the lower part of an array
is maintained to be sorted. An element which is to be 'insert'ed in this sorted
sub-list, has to find its appropriate place and then it has to be inserted
there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and
inserted into the sorted sub-list (in the same array). This algorithm is not
suitable for large data sets as its average and worst case complexity are of
Ο(n2), where n is the number of items.
We take an unsorted array for our example.
Insertion sort compares the first two elements.
It finds that both 14 and 33 are already in ascending order. For now, 14 is
in sorted sub-list.
Insertion sort moves ahead and compares 33 with 27.
And finds that 33 is not in the correct position.
It swaps 33 with 27. It also checks with all the elements of sorted sub-list.
Here we see that the sorted sub-list has only one element 14, and 27 is
greater than 14. Hence, the sorted sub-list remains sorted after swapping.
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with
10.
These values are not in a sorted order.
So we swap them.
However, swapping makes 27 and 10 unsorted.
Hence, we swap them too.
Again we find 14 and 10 in an unsorted order.
We swap them again. By the end of third iteration, we have a sorted sub-list
of 4 items.
This process goes on until all the unsorted values are covered in a sorted
sub-list.
/* Program to Implement Insertion Sort */
#include <stdio.h>
void isort(int [], int);
void main()
{
int a[10],n,i;
printf("\nEnter Array Size");
scanf("%d",&n);
printf("\nEnter %d Elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
isort(a,n);
printf("\nSorted Elements");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
void isort(int a[], int n)
{
int i,j,key;
for(i=1;i<n;i++)
{
key=a[i];
j=i-1;
while(j>=0 && a[j]>key)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=key;
}
}
Output:
Enter Array Size 5
Enter 5 Elements 11 99 22 88 33
Sorted Elements 11 22 33 88 99
STRINGS IN C:
String is a set of characters that are enclosed in double quotes. In the C
programming language, strings are created using one dimension array of
character datatype. Every string in C programming language is enclosed
within double quotes and it is terminated with NULL (\0) character.
Whenever c compiler encounters a string value it automatically appends a
NULL character (\0) at the end. The formal definition of string is as follows...
String is a set of characters enclosed in double quotation marks. In C
programming, the string is a character array of single dimension.
In C programming language, there are two methods to create strings and
they are as follows...
Using one dimensional array of character datatype ( static memory
allocation )
Using a pointer array of character datatype ( dynamic memory
allocation )
Creating string in C programming language:
In C, strings are created as a one-dimensional array of character datatype.
We can use both static and dynamic memory allocation. When we create a
string, the size of the array must be one more than the actual number of
characters to be stored. That extra memory block is used to store string
termination character NULL (\0). The following declaration stores a string of
size 5 characters.
Example: char str[6] ;
The following declaration creates a string variable of a specific size at the
time of program execution.
Example: char *str = (char *) malloc(15) ;
Assigning string value in C programming language:
String value is assigned using the following two methods...
At the time of declaration (initialization)
After declaraation
/* Examples of assigning string value */
#include <stdio.h>
int main()
{
char str1[6] = "Hello";
char str2[] = "Hello!";
char name1[] = {'s','m','a','r','t'};
char name2[6] = {'s','m','a','r','t'};
char title[20];
*title = "economictimes";
return 0;
}
Reading string value from user in C programming language:
We can read a string value from the user during the program execution. We
use the following two methods...
Using scanf() method - reads single word
Using gets() method - reads a line of text
Using scanf() method we can read only one word of string. We use %s to
represent string in scanf() and printf() methods.
/* Examples of reading string value using scanf() method */
#include<stdio.h>
#include<conio.h>
int main()
{
char name[50];
printf("Please enter your name : ");
scanf("%s", name);
printf("Hello! %s , welcome to btech smart class !!", name);
return 0;
}
When we want to read multiple words or a line of text, we use a pre-defined
method gets(). The gets() method terminates the reading of text
with Enter character.
/* Examples of reading string value using gets() method */
#include<stdio.h>
#include<conio.h>
int main()
{
char name[50];
printf("Please enter your name : ");
gets(name);
printf("Hello! %s , welcome to btech smart class !!", name);
return 0;
}
C Programming language provides a set of pre-definied functions
called String Handling Functions to work with string values. All the string
handling functions are defined in a header file called string.h.
String Handling Functions in C:
C programming language provides a set of pre-defined functions
called string handling functions to work with string values. The string
handling functions are defined in a header file called string.h. Whenever we
want to use any string handling function we must include the header file
called string.h.
The following table provides most commonly used string handling function
and their use...
Function Syntax (or) Example Description
strcpy() strcpy(string1, string2) Copies string2 value into string1
strncpy() strncpy(string1, string2, Copies first 5 characters string2 into string1
5)
strlen() strlen(string1) returns total number of characters in string1
strcat() strcat(string1,string2) Appends string2 to string1
strncat() strncpy(string1, string2, Appends first 4 characters of string2 to
4) string1
strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the
same;
less than 0 if string1<string2; greater than 0
if string1>string2
strncmp() strncmp(string1, string2, Compares first 4 characters of both string1
4) and string2
strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2 by
ignoring case (upper or lower)
stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by
ignoring case (similar to strcmpi())
strlwr() strlwr(string1) Converts all the characters of string1 to
lower case.
strupr() strupr(string1) Converts all the characters of string1 to
upper case.
strdup() string1 = strdup(string2) Duplicated value of string2 is assigned to
string1
strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of
character 'b' in string1
strrchr() 'strrchr(string1, 'b') Returns a pointer to the last occurrence of
character 'b' in string1
Function Syntax (or) Example Description
strstr() strstr(string1, string2) Returns a pointer to the first occurrence of
string2 in string1
strset() strset(string1, 'B') Sets all the characters of string1 to given
character 'B'.
strnset() strnset(string1, 'B', 5) Sets first 5 characters of string1 to given
character 'B'.
strrev() strrev(string1) It reverses the value of string1
STRUCTURES IN C:
In C programming language, a structure is a collection of elements of the
different data type. The structure is used to create user-defined data type in
the C programming language. As the structure used to create a user-defined
data type, the structure is also said to be “user-defined data type in C”.
In other words, a structure is a collection of non-homogeneous elements.
Using structure we can define new data types called user-defined data types
that holds multiple values of the different data type. The formal definition of
structure is as follows...
Structure is a colloction of different type of elements under a single name
that acts as user defined data type in C.
Generally, structures are used to define a record in the c programming
language. Structures allow us to combine elements of a different data type
into a group. The elements that are defined in a structure are called
members of structure.
To create structure in c, we use the keyword called "struct". We use the
following syntax to create structures in c programming language.
Syntax: struct <structure_name>
{
data_type member1;
data_type member2, member3;
.
.
};
Following is the example of creating a structure called Student which is
used to hold student record.
Example: struct Student
{
char stud_name[30];
int roll_number;
float percentage;
};
Every structure must terminated with semicolon symbol (;). "struct" is a
keyword, it must be used in lowercase letters only.
Creating and Using structure variables: In a c programming language,
there are two ways to create structure variables. We can create structure
variable while defining the structure and we can also create after
terminating structure using struct keyword.
To access members of a structure using structure variable, we use dot (.)
operator. Consider the following example code...
/* Program to demonstrate Structures */
struct Student
{
char stud_name[30];
int roll_number;
float percentage;
} stud_1 ; // while defining structure
void main()
{
struct Student stud_2; // using struct keyword
printf("Enter details of stud_1 : \n");
printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
printf("Percentage : ");
scanf("%f", &stud_1.percentage);
printf("***** Student 1 Details *****\n);
printf("Name of the Student : %s\n", stud_1.stud_name);
printf("Roll Number of the Student : %i\n", stud_1.roll_number);
printf("Percentage of the Student : %f\n", stud_1.percentage);
}
In the above example program, the stucture variable "stud_1 is created while
defining the structure and the variable "stud_2 is careted using struct
keyword. Whenever we access the members of a structure we use the dot (.)
operator.
Memory allocation of Structure: When the structures are used in the c
programming language, the memory does not allocate on defining a
structure. The memory is allocated when we create the variable of a
particular structure. As long as the variable of a structure is created no
memory is allocated. The size of memory allocated is equal to the sum of
memory required by individual members of that structure. In the above
example program, the variables stud_1 and stud_2 are allocated with 36
bytes of memory each.
All the members of a structure can be used simultaneously. Until variable
of a structure is created no memory is allocated. The memory required by
a structure variable is sum of the memory required by individual members
of that structure.
UNIONS IN C:
In C programming language, the union is a collection of elements of the
different data type. The union is used to create user-defined data type in the
C programming language. As the union used to create a user-defined data
type, the union is also said to be “user-defined data type in C”.
In other words, the union is a collection of non-homogeneous elements.
Using union we can define new data types called user-defined data types
that holds multiple values of the different data type. The formal definition of
a union is as follows...
Union is a colloction of different type of elements under a single name that
acts as user defined data type in C.
Generally, unions are used to define a record in the c programming
language. Unions allow us to combine elements of a different data type into
a group. The elements that are defined in a union are called members of
union.
To create union in c, we use the keyword called "union". We use the
following syntax to create unions in c programming language.
union <structure_name>
{
data_type member1;
data_type member2, member3;
.
.
};
Following is the example of creating a union called Student which is used to
hold student record.
Example: union Student
{
char stud_name[30];
int roll_number;
float percentage;
};
Every union must terminated with semicolon symbol (;). "union" is a
keyword, it must be used in lowercase letters only.
Creating and Using union variables: In a c programming language, there
are two ways to create union variables. We can create union variable while
the union is defined and we can also create after terminating union using
union keyword.
To access members of a union using union variable, we use dot (.) operator.
Consider the following example code...
/* Program to demonstrate Unions */
union Student
{
char stud_name[30];
int roll_number;
float percentage;
} stud_1 ; // while defining union
void main()
{
union Student stud_2; // using union keyword
printf("Enter details of stud_1 : \n");
printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
printf("Percentage : ");
scanf("%f", &stud_1.percentage);
printf("***** Student 1 Details *****\n);
printf("Name of the Student : %s\n", stud_1.stud_name);
printf("Roll Number of the Student : %i\n", stud_1.roll_number);
printf("Percentage of the Student : %f\n", stud_1.percentage);
}
In the above example program, the union variable "stud_1 is created while
defining the union and the variable "stud_2 is careted using union keyword.
Whenever we access the members of a union we use the dot (.) operator.
Memory allocation of Union: When the unions are used in the c
programming language, the memory does not allocate on defining union.
The memory is allocated when we create the variable of a particular union.
As long as the variable of a union is created no memory is allocated. The size
of memory allocated is equal to the maximum memory required by an
individual member among all members of that union. In the above example
program, the variables stud_1 and stud_2 are allocated with 30 bytes of
memory each.
Bit Fields in C:
When we use structures in the c programming language, the memory
required by structure variable is the sum of memory required by all
individual members of that structure. To save memory or to restrict memory
of members of structure we use bitfield concept. Using bitfield we can
specify the memory to be allocated for individual members of a structure. To
understand the bitfields, let us consider the following example code...
Example: struct Date
{
unsigned int day;
unsigned int month;
unsigned int year;
};
Here, the variable of Date structure allocates 6 bytes of memory.
In the above example structure the members day and month both does not
requires 2 bytes of memory for each. Becuase member day stores values
from 1 to 31 only which requires 5 bits of memory, and the
member month stores values from 1 to 12 only which required 4 bits of
memory. So, to save the memory we use the bitfields.
Consider the following structure with bitfields...
Example: struct Date
{
unsigned int day : 5;
unsigned int month : 4;
unsigned int year;
};
Here, the variable of Date structure allocates 4 bytes of memory.
POINTERS IN C:
In the c programming language, we use normal variables to store user data
values. When we declare a variable, the compiler allocates required memory
with the specified name. In the c programming language, every variable has
a name, datatype, value, storage class, and address. We use a special type of
variable called a pointer to store the address of another variable with the
same datatype. A pointer is defined as follows...
Pointer is a special type of variable used to store the memory location
address of a variable.
In the c programming language, we can create pointer variables of any
datatype. Every pointer stores the address the variable with same datatype
only. That means integer pointer is used store the address of integer variable
only.
Accessing the Address of Variables:
In c programming language, we use the reference operator "&" to access the
address of variable.
For example, to access the address of a variable "marks" we use "&marks".
We use the following printf statement to display memory location address of
variable "marks"...
Example: printf("Address : %u", &marks) ;
In the above example statement %u is used to display address
of marks variable. Address of any memory location is unsigned integer
value.
Declaring Pointers (Creating Pointers):
In c programming language, declaration of pointer variable is similar to the
creation of normal variable but the name is prefixed with * symbol. We use
the following syntax to declare a pointer variable...
Syntax: datatype *pointerName ;
A variable declaration prefixed with * symbol becomes a pointer variable.
Example: int *ptr ;
In the above example declaration, the variable "ptr" is a pointer variable that
can be used to store any integer variable address.
Assigning Address to Pointer:
To assign address to a pointer variable we use assignment operator with the
following syntax...
Syntax: pointerVariableName = & variableName ;
For example, consier the following variables declaration...
Example: int a, *ptr ;
In the above declaration, variable "a" is a normal integer variable and
variable "ptr" is an integer pointer variable. If we want to assign the address
of variable "a" to pointer variable "ptr" we use the following statement...
Example: ptr = &a ;
In the above statement, the address of variable "a" is assigned to pointer
variable "prt". Here we say that pointer variable ptr is pointing to variable a.
Accessing Variable Value Using Pointer:
Pointer variables are used to store the address of other variables. We can
use this address to access the value of the variable through its pointer. We
use the symbol "*" infront of pointer variable name to access the value of
variable to which the pointer is pointing. We use the following general
syntax...
Syntax: *pointerVariableName
/* Program to demonstrate Pointers */
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, *ptr ;
clrscr();
ptr = &a ;
printf("Address of variable a = %u\n", ptr) ;
printf("Value of variable a = %d\n", *ptr) ;
printf("Address of variable ptr = %u\n", &ptr) ;
}
Output:
` Address of variable a = 54321
Value of variable a = 10
Address of variable ptr = 35421
In the above example program, variable a is a normal variable and
variable ptr is a pointer variable. Address of variable a is stored in pointer
variable ptr. Here ptr is used to access the address of variable a and *ptr is
used to access the value of variable a.
Memory Allocation of Pointer Variables:
Every pointer variable is used to store the address of another variable. In
computer memory address of any memory location is an unsigned
integer value. In c programming language, unsigned integer requires 2
bytes of memory. So, irrespective of pointer datatype every pointer variable
is allocated with 2 bytes of memory.
Pointers Arithmetic Operations in C:
Pointer variables are used to store the address of variables. Address of any
variable is an unsigned integer value i.e., it is a numerical value. So we can
perform arithmetic operations on pointer values. But when we perform
arithmetic operations on pointer variable, the result depends on the amount
of memory required by the variable to which the pointer is pointing.
In the c programming language, we can perform the following arithmetic
operations on pointers...
Addition
Subtraction
Increment
Decrement
Comparison
Addition Operation on Pointer:
In the c programming language, the addition operation on pointer variables
is calculated using the following formula...
AddressAtPointer + ( NumberToBeAdd * BytesOfMemoryRequiredByDatatype
)
/* Program to demonstrate Pointers */
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
intPtr = intPtr + 3 ; // intPtr = 1000 + ( 3 * 2 )
floatPtr = floatPtr + 2 ; // floatPtr = 2000 + ( 2 * 4 )
doublePtr = doublePtr + 5 ; // doublePtr = 3000 + ( 5 * 8 )
printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;
getch() ;
}
Output:
intPtr value : 6356748
floatPtr value : 6356740
doublePtr value : 6356760
Subtraction Operation on Pointer:
In the c programming language, the subtraction operation on pointer
variables is calculated using the following formula...
AddressAtPointer - ( NumberToBeAdd * BytesOfMemoryRequiredByDatatype
)
/* Program to demonstrate Pointer */
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
intPtr = intPtr - 3 ; // intPtr = 1000 - ( 3 * 2 )
floatPtr = floatPtr - 2 ; // floatPtr = 2000 - ( 2 * 4 )
doublePtr = doublePtr - 5 ; // doublePtr = 3000 - ( 5 * 6 )
printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;
getch() ;
}
Output:
intPtr value : 6356724
floatPtr value :
doublePtr value :
Increment & Decrement Operation on Pointer:
The increment operation on pointer variable is calculated as follows...
AddressAtPointer + NumberOfBytesRequiresByDatatype
/* Program to demonstrate Pointers */
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
intPtr++ ; // intPtr = 1000 + 2
floatPtr++ ; // floatPtr = 2000 + 4
doublePtr++ ; // doublePtr = 3000 + 6
printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;
getch() ;
}
Output:
intPtr value :
floatPtr value :
doublePtr value :
The decrement operation on pointer variable is calculated as follows...
AddressAtPointer - NumberOfBytesRequiresByDatatype
/* Program to demonstrate Pointers */
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
intPtr-- ; // intPtr = 1000 - 2
floatPtr-- ; // floatPtr = 2000 - 4
doublePtr-- ; // doublePtr = 3000 - 6
printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;
getch() ;
}
Output:
intPtr value :
floatPtr value :
doublePtr value :
Comparison of Pointers:
The comparison operation is perform between the pointers of same datatype
only. In c programming language, we can use all comparison operators
(relational operators) with pointers.
We can't perform multiplication and division operations on pointers.
Pointers to Pointers in C:
In the c programming language, we have pointers to store the address of
variables of any datatype. A pointer variable can store the address of a
normal variable. C programming language also provides a pointer variable to
store the address of another pointer variable. This type of pointer variable is
called a pointer to pointer variable. Sometimes we also call it a double
pointer. We use the following syntax for creating pointer to pointer…
Syntax: datatype **pointerName ;
Example: int **ptr ;
Here, ptr is an integer pointer variable that stores the address of another
integer pointer variable but does not stores the normal integer variable
address.
Points To Be Remembered
To store the address of normal variable we use single pointer variable
To store the address of single pointer variable we use double pointer
variable
To store the address of double pointer variable we use triple pointer
variable
Similarly the same for remaining pointer variables also…
/* Program to demonstrate Pointers */
#include<stdio.h>
#include<conio.h>
int main()
{
int a ;
int *ptr1 ;
int **ptr2 ;
int ***ptr3 ;
ptr1 = &a ;
ptr2 = &ptr1 ;
ptr3 = &ptr2 ;
printf("\nAddress of normal variable 'a' = %u\n", ptr1) ;
printf("Address of pointer variable '*ptr1' = %u\n", ptr2) ;
printf("Address of pointer-to-pointer '**ptr2' = %u\n", ptr3) ;
return 0;
}
Output:
Address of normal variable 'a' =
Address of pointer variable '*ptr1' =
Address of pointer-to-pointer '**ptr2' =
Pointers to void in C
In the c programming language, pointer to void is the concept of defining a
pointer variable that is independent of data type. In C programming
language, a void pointer is a pointer variable used to store the address of a
variable of any datatype. That means single void pointer can be used to store
the address of integer variable, float variable, character variable, double
variable or any structure variable. We use the keyword "void" to create void
pointer. We use the following syntax for creating a pointer to void…
Syntax: void *pointerName ;
Example: void *ptr ;
Here, "ptr" is a void pointer variable which is used to store the address of
any datatype variable.
Points To Be Remembered
void pointer stores the address of any datatype variable.
/* Program to demonstrate Pointers */
#include<stdio.h>
#include<conio.h>
int main()
{
int a ;
float b ;
char c ;
void *ptr ;
clrscr() ;
ptr = &a ;
printf(“Address of integer variable ‘a’ = %u\n”, ptr) ;
ptr = &b ;
printf(“Address of float variable ‘b' = %u\n”, ptr) ;
ptr = &c ;
printf(“Address of character variable ‘c’ = %u\n”, ptr) ;
return 0;
}
Output:
Address of integer variable ‘a’ =
Address of float variable ‘b' =
Address of character variable ‘c’ =
Pointers to Arrays in C:
In the c programming language, when we declare an array the compiler
allocate the required amount of memory and also creates a constant pointer
with array name and stores the base address of that pointer in it. The
address of the first element of an array is called as base address of that
array.
The array name itself acts as a pointer to the first element of that array.
Consider the following example of array declaration...
Example: int marks[6] ;
For the above declaration, the compiler allocates 12 bytes of memory and
the address of first memory location (i.e., marks[0]) is stored in a constant
pointer called marks. That means in the above example, marks is a pointer
to marks[0].
/* Program to demonstrate Pointers */
#include<stdio.h>
#include<conio.h>
int main()
{
int marks[6] = {89, 45, 58, 72, 90, 93} ;
int *ptr ;
clrscr() ;
ptr = marks ;
printf(“Base Address of 'marks' array = %u\n”, ptr) ;
return 0;
}
Output:
Base Address of 'marks' array =
Points To Be Remembered
An array name is a constant pointer.
We can use the array name to access the address and value of all the
elements of that array.
Since array name is a constant pointer we can't modify its value.
Consider the following example statements...
Example: ptr = marks + 2 ;
Here, the pointer variable "ptr" is assigned with address of
"marks[2]" element.
Example: printf("Address of 'marks[4]' = %u", marks+4) ;
The above printf statement displays the address of element "marks[4]".
Example: printf("Value of 'marks[0]' = %d", *marks) ;
printf("Value of 'marks[3]' = %d", *(marks+3)) ;
In the above two statements, first printf statement prints the value 89 (i.e.,
value of marks[0]) and the second printf statement prints the value 72 (i.e.,
value of marks[3]).
Example: marks++ ;
The above statement generates compilation error because the array name
acts as a constant pointer. So we can't change its value.
In the above example program, the array name marks can be used as
follows...
marks is same as &marks[0]
marks + 1 is same as &marks[1]
marks + 2 is same as &marks[2]
marks + 3 is same as &marks[3]
marks + 4 is same as &marks[4]
marks + 5 is same as &marks[5]
*marks is same as marks[0]
*(marks + 1) is same as marks[1]
*(marks + 2) is same as marks[2]
*(marks + 3) is same as marks[3]
*(marks + 4) is same as marks[4]
*(marks + 5) is same as marks[5]
Pointers to Multi Dimensional Array:
In case of multi dimensional array also the array name acts as a constant
pointer to the base address of that array. For example, we declare an array
as follows...
Example: int marks[3][3] ;
In the above example declaration, the array name marks acts as constant
pointer to the base address (address of marks[0][0]) of that array.
In the above example of two dimensional array, the element marks[1][2] is
accessed as *(*(marks + 1) + 2).
Pointers for Functions in C:
In the c programming language, there are two ways to pass parameters to
functions. They are as follows...
Call by Value
Call By Reference
We use pointer variables as formal parameters in call by
reference parameter passing method.
In case of call by reference parameter passing method, the address of actual
parameters is passed as arguments from the calling function to the called
function. To recieve this address, we use pointer variables as formal
parameters.
Consider the following program for swapping two variable values...
/* Swapping of two variable values using Call by Reference */
#include<stdio.h>
#include<conio.h>
void swap(int *, int *) ;
void main()
{
int a = 10, b = 20 ;
clrscr() ;
printf(“Before swap : a = %d and b = %d\n", a, b) ;
swap(&a, &b) ;
printf(“After swap : a = %d and b = %d\n", a, b) ;
getch() ;
}
void swap(int *x, int *y)
{
int temp ;
temp = *x ;
*x = *y ;
*y = temp ;
}
Output:
Before swap : a = 10 and b = 20
After swap : a = 20 and b = 10
In the above example program, we are passing the addresses of
variables a and b and these are recieved by the pointer variables x and y. In
the called function swap we use the pointer variables x and y to swap the
values of variables a and b.
DYNAMIC MEMORY ALLOCATION IN C:
In C programming language, when we declare variables memory is allocated
in space called stack. The memory allocated in the stack is fixed at the time
of compilation and remains until the end of the program execution. When
we create an array, we must specify the size at the time of the declaration
itself and it can not be changed during the program execution. This is a
major problem when we do not know the number of values to be stored in
an array. To solve this we use the concept of Dynamic Memory Allocation.
The dynamic memory allocation allocates memory from heap storage.
Dynamic memory allocation is defined as follow...
Allocation of memory during the program execution is called dynamic
memory allocation.
OR
Dynamic memory allocation is the process of allocating the memory
manually at the time of program execution.
We use pre-defined or standard library functions to allocate memory
dynamically. There are FOUR standard library functions that are defined in
the header file known as "stdlib.h". They are as follows...
malloc()
calloc()
realloc()
free()
malloc(): malloc() is the standard library function used to allocate a
memory block of specified number of bytes and returns void pointer. The
void pointer can be casted to any datatype. If malloc() function unable to
allocate memory due to any reason it returns NULL pointer.
Syntax: void* malloc(size_in_bytes)
/* Program to demonstrate malloc(). */
#include<stdio.h>
#include<conio.h>
int main ()
{
char *title;
title = (char *) malloc(15);
strcpy(title, "c programming");
printf("String = %s, Address = %u\n", title, title);
return(0);
}
calloc(): calloc() is the standard library function used to allocate multiple
memory blocks of the specified number of bytes and initializes them to
ZERO. calloc() function returns void pointer. If calloc() function unable to
allocate memory due to any reason it returns a NULL pointer. Generally,
calloc() is used to allocate memory for array and structure. calloc() function
takes two arguments and they are 1. The number of blocks to be allocated,
2. Size of each block in bytes
Syntax: void* calloc(number_of_blocks, size_of_each_block_in_bytes)
/* Program to demonstrate calloc(). */
#include<stdio.h>
#include<conio.h>
int main ()
{
int i, n;
int *ptr;
printf("Number of blocks to be created:");
scanf("%d",&n);
ptr = (int*)calloc(n, sizeof(int));
printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ )
{
scanf("%d",&ptr[i]);
}
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ )
{
printf("%d ",ptr[i]);
}
return(0);
}
realloc(): realloc() is the standard library function used to modify the size of
memory blocks that were previously allocated using malloc() or calloc().
realloc() function returns void pointer. If realloc() function unable to allocate
memory due to any reason it returns NULL pointer.
Syntax: void* realloc(*pointer, new_size_of_each_block_in_bytes)
/* Program to demonstrate realloc(). */
#include<stdio.h>
#include<conio.h>
int main ()
{
char *title;
title = (char *) malloc(15);
strcpy(title, "c programming");
printf("Before modification : String = %s, Address = %u\n", title, title);
title = (char*) realloc(title, 30);
strcpy(title,"C Programming Language");
printf("After modification : String = %s, Address = %u\n", title, title);
return(0);
}
free(): free() is the standard library function used to deallocate memory
block that was previously allocated using malloc() or calloc(). free() function
returns void pointer. When free() function is used with memory allocated
that was created using calloc(), all the blocks are get deallocated.
Syntax: void free(*pointer)
/* Program to demonstrate free(). */
#include<stdio.h>
#include<conio.h>
int main ()
{
char *title;
title = (char *) malloc(15);
strcpy(title, "c programming");
printf("Before modification : String = %s, Address = %u\n", title, title);
title = (char*) realloc(title, 30);
strcpy(title,"C Programming Language");
printf("After modification : String = %s, Address = %u\n", title, title);
free(title);
return(0);
}
FILES IN C:
Generally, a file is used to store user data in a computer. In other words,
computer stores the data using files. we can define a file as follows...
File is a collection of data that stored on secondary memory like hardisk of a
computer.
C programming language supports two types of files such as Text Files (or)
ASCII Files and Binary Files.
Text File (or) ASCII File - The file that contains ASCII codes of data like
digits, alphabets and symbols is called text file (or) ASCII file.
Binary File - The file that contains data in the form of bytes (0's and 1's) is
called as binary file. Generally, the binary files are compiled version of text
files.
File Operations in C: The following are the operations performed on files in
c programming langauge...
Creating (or) Opening a file
Reading data from a file
Writing data into a file
Closing a file
All the above operations are performed using file handling functions
available in C.
Creating (or) Opening a file: To create a new file or open an existing file,
we need to create a file pointer of FILE type. Following is the sample code for
creating file pointer.
Syntax: FILE *f_ptr ;
We use the pre-defined method fopen() to create a new file or to open an
existing file. There are different modes in which a file can be opened.
Consider the following code...
Syntax: File *f_ptr ;
*f_ptr = fopen("abc.txt", "w") ;
The above example code creates a new file called abc.txt if it does not exists
otherwise it is opened in writing mode.
In C programming language, there different modes are available to open a
file and they are shown in the following table.
Sl. No. Mode Description
1 r Opens a text file in reading mode.
2 w Opens a text file in wirting mode.
3 a Opens a text file in append mode.
4 r+ Opens a text file in both reading and writing mode.
5 w+ Opens a text file in both reading and writing mode. It
set the cursor position to the begining of the file if it
exists.
6 a+ Opens a text file in both reading and writing mode. The
reading operation is performed from begining and
writing operation is performed at the end of the file.
Note - The above modes are used with text files only. If we want to work with
binary files we use
rb, wb, ab, rb+, wb+ and ab+.
Reading from a file: The reading from a file operation is performed using
the following pre-defined file handling methods.
getc()
getw()
fscanf()
fgets()
fread()
getc( *file_pointer ) - This function is used to read a character from
specified file which is opened in reading mode. It reads from the current
position of the cursor. After reading the character the cursor will be at next
character.
Syntax: getc( *file_pointer );
Example: ch = getc(fp);
/* Program to illustrate getc() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("MySample.txt","r");
printf("Reading character from the file: %c\n",getc(fp));
ch = getc(fp);
printf("ch = %c", ch);
fclose(fp);
getch();
return 0;
}
Output
Reading character from the file:
Ch = e
getw( *file_pointer ) - This function is used to read an integer value form
the specified file which is opened in reading mode. If the data in file is set of
characters then it reads ASCII values of those characters.
Syntax: getw( *file_pointer );
Example: i = getw(fp);
/* Program to illustrate getw() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int i,j;
clrscr();
fp = fopen("MySample.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);
fp = fopen("MySample.txt","r");
i = getw(fp); // reads 65 - ASCII value of A
j = getw(fp); // reads 97 - ASCII value of a
printf("SUM of the integer values stored in file = %d", i+j); // 65 + 97 =
162
fclose(fp);
getch();
return 0;
}
Output :
SUM of the integer values stored in file = 162
fscanf( *file_pointer, typeSpecifier, &variableName ) - This function is
used to read multiple datatype values from specified file which is opened in
reading mode.
Syntax: fscanf( *file_pointer, typeSpecifier, &variableName);
Example: fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
/* Program to illustrate fscanf() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
char str1[10], str2[10], str3[10];
int year;
FILE * fp;
clrscr();
fp = fopen ("file.txt", "w+");
fputs("We are in 2020", fp);
rewind(fp); // moves the cursor to begining of the file
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("Read String1 - %s\n", str1 );
printf("Read String2 - %s\n", str2 );
printf("Read String3 - %s\n", str3 );
printf("Read Integer - %d", year );
fclose(fp);
getch();
return 0;
}
Output:
Read String1 – We
Read String2 – are
Read String3 – in
Read Integer - 2020
fgets( variableName, numberOfCharacters, *file_pointer ) - This method
is used for reading a set of characters from a file which is opened in reading
mode starting from the current cursor position. The fgets() function reading
terminates with reading NULL character.
Syntax: fgets( variableName, numberOfCharacters, *file_pointer );
Example: fgets(str,6,fp);
/* Program to illustrate fgets() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char *str;
clrscr();
fp = fopen ("file.txt", "r");
fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
getch();
return 0;
}
Output:
Str = Welcom
fread( source, sizeofReadingElement, numberOfCharacters, FILE
*pointer ) - This function is used to read specific number of sequence of
characters from the specified file which is opened in reading mode.
Syntax: fread( source, sizeofReadingElement, numberOfCharacters,
FILE *pointer );
Example: fread(str,sizeof(char),5,fp);
/* Program to illustrate fgets() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char *str;
clrscr();
fp = fopen ("file.txt", "r");
fread(str,sizeof(char),5,fp);
str[strlen(str)+1] = 0;
printf("str = %s", str);
fclose(fp);
getch();
return 0;
}
Output:
Str = Welcome
Writing into a file:
The writing into a file operation is performed using the following pre-defined
file handling methods.
putc()
putw()
fprintf()
fputs()
fwrite()
putc( char, *file_pointer ) - This function is used to write/insert a
character to the specified file when the file is opened in writing mode.
Syntax: putc( char, *file_pointer );
Example: putc(ch,fp);
/* Program to illustrate putc() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("C:/TC/EXAMPLES/MySample.txt","w");
putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);
getch();
return 0;
}
Output:
AB
putw( int, *file_pointer ) - This function is used to writes/inserts an integer
value to the specified file when the file is opened in writing mode.
Syntax: putw( int, *file_pointer );
Example: putw(i,fp);
/* Program to illustrate putw() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int i;
clrscr();
fp = fopen("MySample.txt","w");
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
getch();
return 0;
}
Output:
Bd
fprintf( *file_pointer, "text" ) - This function is used to writes/inserts
multiple lines of text with mixed data types (char, int, float, double) into
specified file which is opened in writing mode.
Syntax: fprintf( *file_pointer, "text" );
Example: fprintf(fp,text);
/* Program to illustrate "fprintf()" in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char *text = "\nthis is example text");
int i = 10;
clrscr();
fp = fopen("MySample.txt","w");
fprintf(fp,"This is line1\nThis is line2\n%d", i);
fprintf(fp,text);
fclose(fp);
getch();
return 0;
}
Output:
This is line1
This is line2
10
this is example text
fputs( "string", *file_pointer ) - TThis method is used to insert string data
into specified file which is opened in writing mode.
Syntax: fputs( "string", *file_pointer );
Example: fputs("Hi!\nHow are you?",fp);
/* Program to illustrate fputs() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char *text = "\nthis is example text";
clrscr();
fp = fopen("MySample.txt","w");
fputs("Hi!\nHow are you?",fp);
fclose(fp);
getch();
return 0;
}
Output:
Hi
How are you?"
fwrite( “StringData”, sizeof(char), numberOfCharacters, FILE *pointer )
- This function is used to insert specified number of characters into a binary
file which is opened in writing mode.
Syntax: fwrite( “StringData”, sizeof(char), numberOfCharacters,
FILE *pointer );
Example: fwrite(text,sizeof(char),5,fp);
/* Program to illustrate fwrite() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char *text = "Welcome to C Language";
clrscr();
fp = fopen("MySample.txt","wb");
fwrite(text,sizeof(char),5,fp);
fclose(fp);
getch();
return 0;
}
Output:
Welco
Closing a file:
Closing a file is performed using a pre-defined method fclose().
Syntax: fclose( *f_ptr );
The method fclose() returns '0'on success of file close otherwise it returns
EOF (End Of File).
Cursor Positioning Functions in Files:
C programming language provides various pre-defined methods to set the
cursor position in files. The following are the methods available in c, to
position cursor in a file.
ftell()
rewind()
fseek()
ftell( *file_pointer ) - This function returns the current position of the
cursor in the file.
Syntax: ftell( *file_pointer );
Example: position = ftell(fp);
/* Program to illustrate ftell() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output:
Cursor position = 0
Cursor position = 5
rewind( *file_pointer ) - This function is used reset the cursor position to
the beginning of the file.
Syntax: rewind( *file_pointer );
Example: rewind(fp);
/* Program to illustrate rewind() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
rewind(fp);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output:
Cursor position = 0
Cursor position = 5
Cursor position = 0
fseek( *file_pointer, numberOfCharacters, fromPosition ) - This function
is used to set the cursor position to the specific position. Using this function
we can set the cursor position from three different position they are as
follows.
from beginning of the file (indicated with 0)
from current cursor position (indicated with 1)
from ending of the file (indicated with 2)
Syntax: fseek( *file_pointer, numberOfCharacters, fromPosition );
Example: position = ftell(fp);
/* Program to illustrate fseek() in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
fseek(fp, -5, 2);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output:
Cursor position = 0
Cursor position = 5
Cursor position = 16
Error Handling in C:
C programming language does not support error handling that are occured
at program execution time. However, C provides a header file called error.h.
The header file error.h contains few methods and variables that are used to
locate error occured during the program execution. Generally, c
programming function returns NULL or -1 in case of any error occured, and
there is a global variable called errno which stores the error code or error
number. The following table lists few errno values and thier meaning.
Error Number Meaning
1 Specified operation not permitted
2 No such file or directory.
3 No such process.
4 Interrupted system call.
5 IO Error
6 No such device or address
7 Argument list too long
8 Exec format error
9 Bad file number
10 No child processes
11 Try again
12 Out of memory
13 Permission denied
C programming language provides the following two methods to represent
errors occured during program execution.
perror( )
strerror( )
perror( ) - The perror() function returns a string passed to it along with the
textual representation of current errno value.
strerror( ) - The strerror() function returns a pointer to the string
representation of the current errno value. This method is defined in the
header file string.h Consider the following example program...
/* Program to illustrate error handling in C */
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *f_ptr;
f_ptr = fopen("abc.txt", "r");
if(f_ptr == NULL)
{
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");
}
Else
{
printf("File is opened in reading mode!");
fclose(f_ptr);
}
return 0;
}
Output:
Value of errno: 2
COMMAND LINE ARGUMENTS IN C:
In C programming language, command line arguments are the data values
that are passed from command line to our program. Using command line
arguments we can control the program execution from the outside of the
program. Generally, all the command line arguments are handled by the
main() method. Generally, the command line arguments can be understood
as follows...
Command line arguments are the parameters passing to main() method
from the command line.
When command line arguments are passed main() method receives them
with the help of two formal parameters and they are,
int argc
char *argv[ ]
int argc - It is an integer argument used to store the count of command line
arguments are passed from the command line.
char *argv[ ] - It is a character pointer array used to store the actual values
of command line arguments are passed from the command line.
Points to be Remembered
The command line arguments are seperated with SPACE.
Always the first command line argument is file path.
Only string values can be passed as command line arguments.
All the command line arguments are stored in a character pointer
array called argv[ ].
Total count of command line arguments including file path argument
is stored in a integer parameter called argc.
Consider the following example program...
/* Program to illustrate command line arguments in C */
#include<stdio.h>
#include<conio.h>
int main(int argc, char *argv[])
{
int i;
clrscr() ;
if(argc == 1)
{
printf("Please provide command line arguments!!!");
return 0;
}
Else
{
printf("Total number of arguments are - %d and they are\n\n", argc);
for(i=0; i<argc ; i++)
{
printf("%d -- %s \n", i+1, argv[i]);
}
return 0;
}
}
When execute the above program by passing "Hello welcome to clanguage"
as command line arguments it produce the following output.
Output:
Total number of arguments are
1 – C:\Users\User\Desktop
2 – hello
3 – welcome
4 – to
5 – clanguage
In the above example program we are passing 4 string arguments (Hello,
welcome, to and www.btechsmartclass.com) but the default first argument is
a file path. So, the total count of command line arguments is 5.
Whenever we want to pass numerical values as command line arguments,
they are passed as string values only and we need to convert them into
numerical values in the program. Consider the following program that
calculates the sum of all command line arguments and displays the result.
/* Program to display sum of all command line arguments in C */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int i, n, sum = 0;
clrscr() ;
if(argc == 1)
{
printf("Please provide command line arguments!!!");
return 0;
}
Else
{
printf("Total number of arguments are - %d and sum of those is ",
argc);
for(i=0; i<argc ; i++)
{
n = atoi(argv[i]);
sum += n;
}
printf("%d\n", sum);
return 0;
}
}
When execute the above program by passing "10 20 30 40 50" as command
line arguments it produce the following output.
Output:
Total number of arguments are 6 and the sum of those is 150
In the above example program we are passing 5 string arguments (10, 20,
30 40 and 50). They are converted into integer values by using atoi() method
which is available in stdlib.h header file.