C Programming Notes ?
C Programming Notes ?
DINESHKUMAR THANGAVEL
PARUL UNIVERSITY
C PROGRAMMING
strings
functions
file handling
that are being used in many languages like C++
Java
C#
etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
C is a procedural language. In C, variables and function prototypes must be declared before being
used.
1
C PROGRAMMING
A High-Level language is not specific to one machine, i.e., machine independent. It is easy to
understand.
History of C:
Brief History of C Programming Language:
C provides strong abstraction in case of its libraries and built-in features that make it machine-
independent. It is capable enough to develop system applications such as the kernel, driver, etc.
Structured Language
2
C PROGRAMMING
C Language supports structured programming which includes the use of functions. Functions
reduce the code complexity and are totally reusable.
Extensible: C Language is a High-level language and is also open for upgrades. Hence,
the programming language is considered to be extensible like any other high-level
languages.
Recursion
Pointers
C enables users to directly interact with memory using the pointers. We use pointers in memory,
structure, functions, arrays, stack and many more.
Faster: C Language comes with a minimal number of libraries and built-in functions which
makes the compile and execution-times to be less and the system faces low overhead.
Memory Management: C provides the best in class memory management. It can both
allocate and deallocate memory dynamically. the malloc(), calloc(), realloc() functions are
used to allocate memory dynamically and free() function is used to deallocate the used
memory at any instance of time.
Structure of C programming:
3
C PROGRAMMING
4
C PROGRAMMING
Pre-processor directives in C:
The pre-processor will process directives that are inserted into the C source code. These
directives allow additional actions to be taken on the C source code before it is compiled into
object code. Directives are not part of the C language itself.
5
C PROGRAMMING
Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We can define
the token as the smallest individual element in C. For `example, we cannot create a sentence
without using words; similarly, we cannot create a program in C without using tokens in C.
Therefore, we can say that tokens in C is the building block or the basic component for creating
a program in C language.
Classification of tokens in C
o Keywords in C
o Identifiers in C
o Strings in C
o Operators in C
o Constant in C
o Special Characters in C
Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are
only 32 reserved words (keywords) in the C language.
6
C PROGRAMMING
C Identifiers
C identifiers represent the name in the C program, for example, variables, functions,
arrays, structures, unions, labels, etc. An identifier can be composed of letters such
as uppercase, lowercase letters, underscore, digits, but the starting letter should be
either an alphabet or an underscore. If the identifier is not used in the external
linkage, then it is called as an internal identifier. If the identifier is used in the
external linkage, then it is called as an external identifier.
Example of valid identifiers: total, sum, average, a12, a_12, ab, place, college etc..
7
C PROGRAMMING
Types of identifiers
o Internal identifier
o External identifier
Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal identifier. The
internal identifiers can be local variables.
External Identifier
If the identifier is used in the external linkage, then it is known as an external identifier. The
external identifiers can be function names, global variables.
Keyword Identifier
Its meaning is pre-defined in the c Its meaning is not defined in the c compiler.
compiler.
It does not contain the underscore It can contain the underscore character.
character.
1. int main()
2. {
3. int a=10;
4. int A=20;
5. printf("Value of a is : %d",a);
6. printf("\nValue of A is :%d",A);
7. return 0;
8. }
8
C PROGRAMMING
C Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Misc Operator
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Show Examples
9
C PROGRAMMING
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then −
Show Examples
== Checks if the values of two operands are equal or not. If yes, then (A == B)
the condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not. If the values (A != B)
are not equal, then the condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right (A > B)
operand. If yes, then the condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right (A < B)
operand. If yes, then the condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the (A >= B)
value of right operand. If yes, then the condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value (A <= B)
of right operand. If yes, then the condition becomes true. is true.
10
C PROGRAMMING
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
Show Examples
&& Called Logical AND operator. If both the operands are non-zero, then the (A && B)
condition becomes true. is false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the (A || B) is
condition becomes true. true.
! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it false. B) is
true.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is
as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
11
C PROGRAMMING
& Binary AND Operator copies a bit to the result if it exists in (A & B)
both operands. = 12,
i.e.,
0000
1100
~ (~A ) =
Binary One's Complement Operator is unary and has the ~(60),
effect of 'flipping' bits. i.e,. -
0111101
<< Binary Left Shift Operator. The left operands value is A << 2 =
moved left by the number of bits specified by the right 240 i.e.,
operand. 1111
0000
12
C PROGRAMMING
>> Binary Right Shift Operator. The left operands value is A >> 2 =
moved right by the number of bits specified by the right 15 i.e.,
operand. 0000
1111
Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples
= Simple assignment operator. Assigns values from right side operands to C=A+B
left side operand will assign
the value
of A + B
to C
+= Add AND assignment operator. It adds the right operand to the left C += A is
operand and assign the result to the left operand. equivalent
to C = C +
A
*= Multiply AND assignment operator. It multiplies the right operand with the C *= A is
left operand and assigns the result to the left operand. equivalent
to C = C *
A
/= Divide AND assignment operator. It divides the left operand with the right C /= A is
operand and assigns the result to the left operand. equivalent
to C = C /
A
13
C PROGRAMMING
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
14
C PROGRAMMING
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
15
C PROGRAMMING
Example:
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
16
C PROGRAMMING
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to left.
1. int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).
ASCII value in C
What is ASCII code?
The full form of ASCII is the American Standard Code for information interchange. It is a
character encoding scheme used for electronics communication. Each character or a special
character is represented by some ASCII code, and each ascii code occupies 7 bits in memory.
In C programming language, a character variable does not contain a character value itself rather
the ascii value of the character variable. The ascii value represents the character variable in
numbers, and each character variable is assigned with some number range from 0 to 127. For
example, the ascii value of 'A' is 65.
In the above example, we assign 'A' to the character variable whose ascii value is 65, so 65 will be
stored in the character variable rather than 'A'.
We will create a program which will display the ascii value of the character variable.
1. #include <stdio.h>
2. int main()
18
C PROGRAMMING
3. {
4. char ch; // variable declaration
5. printf("Enter a character");
6. scanf("%c",&ch); // user input
7. printf("\n The ascii value of the ch variable is : %d", ch);
8. return 0;
9. }
Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't represent itself when
used inside string literal or character.
It is composed of two or more characters starting with backslash \. For example: \n represents new
line.
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
19
C PROGRAMMING
\? Question Mark
\0 Null
Example:
#include<stdio.h>
int main(){
int number=50;
printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
return 0;
}
C Format Specifier
The Format specifier is a string used in the formatted input and output functions. The format string
determines the format of the input and output. The format string always starts with a '%' character.
Format Description
specifier
%d or %i It is used to print the signed integer value where signed integer means that the variable
can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer means that the
variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value always starts with
a 0 value.
20
C PROGRAMMING
%x It is used to print the hexadecimal unsigned integer where the hexadecimal integer
value always starts with a 0x value. In this, alphabetical characters are printed in small
letters such as a, b, c, etc.
%X It is used to print the hexadecimal unsigned integer, but %X prints the alphabetical
characters in uppercase such as A, B, C, etc.
%f It is used for printing the decimal floating-point values. By default, it prints the 6 values
after '.'.
%g It is used to print the decimal floating-point values, and it uses the fixed precision, i.e.,
the value after the decimal in input would be exactly the same as the value in the
output.
Type Casting in C
Typecasting allows us to convert one data type into other. In C language, we use cast operator for
typecasting which is denoted by (type).
Syntax:
1. (type)value;
Note: It is always recommended to convert the lower value to higher for avoiding data loss.
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
21
C PROGRAMMING
Static in C
Static is a keyword used in C programming language. It can be used with both variables and
functions, i.e., we can declare a static variable and static function as well. An ordinary variable is
limited to the scope in which it is defined, while the scope of the static variable is throughout the
program.
o Staticglobalvariable
When a global variable is declared with a static keyword, then it is known as a static global
variable. It is declared at the top of the program, and its visibility is throughout the
program.
o Static function
When a function is declared with a static keyword known as a static function. Its lifetime is
throughout the program.
o Static local variable
When a local variable is declared with a static keyword, then it is known as a static local
variable. The memory of a static local variable is valid throughout the program, but the
scope of visibility of a variable is the same as the automatic local variables. However, when
the function modifies the static local variable during the first function call, then this
modified value will be available for the next function call also.
22
C PROGRAMMING
Basic Datatypes
Basic Datatypes are considered as the most fundamental and primary datatypes that C has to
offer. The Datatypes that come under Basic Datatypes are as follows.
23
C PROGRAMMING
Derived Datatypes
A derived type is formed by using one or more basic types in combination. They are the object
types whose functionalities are predefined in the C libraries.
Function types
Pointer types
Array types
Structure types
Union types
Enumeration Datatypes
Void Datatypes
The void data type is an empty data type that is used as a return type for the functions that
return no value in C.
example:
void function(int n)
int function(void)
Variables in C
Variable is defined as the reserved memory space which stores a value of a definite datatype. The
value of the Variable is not constant, instead, it allows changes. There are mainly five types of
variables supported in C.
local variable
global variable
static variable
automatic variable
external variable
24
C PROGRAMMING
Local Variables
Any variable that is declared at the inside a code block or a function and has the scope confined to
that particular block of code or function is called to be a local variable.
//Example
1Void Edu()
2{
3 int Local_variable=10;
4}
Global Variables
Any variable that is declared at the outside a code block or a function and has the scope across
the entire program and allows any function to change it’s value is known as Global Variable.
//Example
1int Global_variable=10;
2void Edu()
3{
4 int Local_variable=20;
5}
Static Variables
Any variable that is declared using the keyword static is known as a Static Variable. Static
Variables retain the declared value throughout the entire execution of the program and will not be
changed between multiple function calls.
//Example
void Edu()
{
int Local_variable =10;//
static int Static_variable =10;
Local_variable=Local_variable+1;
Static_variable =Static_variable+1;
printf("%d,%d",x,y);
}
25
C PROGRAMMING
Automatic Variables
Automatic Variables can be declared by using the keyword auto. By default, all the variables
declared in C language are Automatic Variables.
//Example
void main()
{
int Local_variable=10; //(automatic default)
auto int auto=20; //(automatic variable)
};
External Variables
External Variables are declared by using the extern keyword. We can share a variable in
multiple C source files by using an external variable.
//Example
extern external=10;
1
printf() function
The printf() function is used for output. It prints the given statement to the console.
printf("format string",argument_list);
scanf() function
The scanf() function is used for input. It reads the input data from the console.
scanf("format string",argument_list);
26
C PROGRAMMING
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
return 0;
}
Output
enter a number:5
cube of number is:125
The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.
First C Program
In this C Programming Tutorial, we will understand the basic structure of a C Program. Any
basic C program consists of the following sections
27
C PROGRAMMING
Preprocessor Directives
Preprocessor Directives are declared at the beginning of every C Program with a special
character #. They are defined as predefined functions or Macro programs that are invoked
and compiled by the C Compiler during the compilation process.
Functions
Functions in C Program are defined as the subdivided program of the main program.
Functions provide code reusability and decrease code complexity.
Variables
Variable is defined as a name declared to a store the values in a C Program. Every variable used
in C has a specific data type that determines the size and layout of the variable’s memory.
Statements & Expressions:Statements are nothing but the instructions we provide to the
computer to compile and the expressions, on the other hand, are considered to be the
mathematical or the logical statements which yield into a resultant value.
Comments
Comments are the messages written by the developer in the code for easy understanding of the
logic of the code used while programming. The comments will not be compiled by the compiler. the
comments are written within // or /* */.
1#include<stdio.h>
2//main fn
3int main(){
4/* printing hello world*/
28
C PROGRAMMING
5 printf("Hello World");
return 0;
}
//Output
Hello World
if
//Example
1#include<stdio.h>
2int main()
3{
4 int number=0;
5 printf("Enter a number:");
6 scanf("%d",&number);
7 if(number%2==0){
8 printf("your number is %d and it is an
9even number",number);
10 }
11 return 0;
29
C PROGRAMMING
//Output
Enter a number:4
your number is 4 and it is an even number
else-if
Else If Conditional Statement in C language is used to execute
one statement out of the two. The Conditional Statement
executes the code segment provided is true and valid. Below is
the flowchart for the else-if condition.
//Example
#include<stdio.h>
int main()
1{
2 int number=0;
3 printf("enter a number:");
4 scanf("%d",&number);
5 if(number%2==0)
6 {
7 printf("your number is %d and it is an even
8number",number);
9 }
10 else
11 {
12 printf("your number is %d and it is an odd
13number",number);
14 }
15 return 0;
16}
30
C PROGRAMMING
//Output
Enter a number:5
your number is 5 and it is an odd number
else-if ladder
1#include<stdio.h>
2int main()
3{
4 int number=0;
5 printf("enter a number:");
6 scanf("%d",&number);
7 if(number==10)
8 {
9 printf("your inputted number is equals to 10");
10 }
31
C PROGRAMMING
11 else if(number==50)
12 {
13 printf("your inputted number is equal to 50");
14 }
15 else if(number==100)
16 {
17 printf("your inputted number is equal to 100");
18 }
19 else
20 {
21 printf("your inputted number is not equal to 10, 50 or 100");
22 }
23 return 0;
24}
//Output
enter a number:5
your inputted number is not equal to 10, 50 or 100
Nested if
//Example
1#include<stdio.h>
2int main()
3{
4 int v1, v2;
5 printf("Enter the value of First variable :");
6 scanf("%d",&v1);
7 printf("Enter the value of Second variable :");
32
C PROGRAMMING
8 scanf("%d",&v2);
9 if (v1 != v2)
10 {
11 printf("First variable is not equal to Second variablen");
12 if (v1<v2)
13 {
14 printf("First variable is not equal to Second
15variablen");
16 }
17 else
18 {
19 printf("Second variable is greater than First
20variablen");
21 }
22 }
23 else
24 {
25 printf("First variable is equal to Second variablen");
26 }
return 0;
}
//Output:
Looping Statements:
Loops in C are defined as a programming statement that is designed to execute a particular code
segment for a specific number of times or until a particular condition provided is satisfied. There
are mainly three-loop statements available in C.
How it Works:
33
C PROGRAMMING
As per the above diagram, if the Test Condition is true, then the loop is
executed, and if it is false then the execution breaks out of the loop. After the
loop is successfully executed the execution again starts from the Loop entry
and again checks for the Test condition, and this keeps on repeating.
Types of Loop
1. while loop
2. for loop
3. do while loop
34
C PROGRAMMING
while loop
while loop can be addressed as an entry control loop. It is completed in 3
steps.
Syntax :
variable initialization;
while(condition)
statements;
#include<stdio.h>
35
C PROGRAMMING
void main( )
int x;
x = 1;
printf("%d\t", x);
x++;
1 2 3 4 5 6 7 8 9 10
do while loop
36
C PROGRAMMING
do
.....
.....
while(condition)
#include<stdio.h>
void main()
int a, i;
a = 5;
i = 1;
do
37
C PROGRAMMING
printf("%d\t", a*i);
i++;
1. While the loop is an entry control loop The do-while loop is an exit control loop
because firstly, the condition is because in this, first of all, the body of
checked, then the loop's body is the loop is executed then the condition
executed. is checked true or false.
2. The statement of while loop may not The statement of the do-while loop
be executed at all. must be executed at least once.
3. The while loop terminates when the As long as the condition is true, the
condition becomes false. compiler keeps executing the loop in
the do-while loop.
4. In a while loop, the test condition In a do-while loop, the variable of test
variable must be initialized first to condition Initialized in the loop also.
check the test condition in the loop.
5. In a while loop, at the end of the In this, at the end of the condition, there
condition, there is no semicolon. is a semicolon.
Syntax: Syntax:
while (condition) while (condition);
38
C PROGRAMMING
6. While loop is not used for creating It is mostly used for creating menu-
menu-driven programs. driven programs because at least one
time; the loop is executed whether the
condition is true or false.
39
C PROGRAMMING
for loop
for loop is used to execute a set of statements repeatedly until a
particular condition is satisfied. We can say it is an open ended loop..
General format is,
statement-block;
In for loop we have exactly two semicolons, one after initialization and second
after the condition. In this loop we can have more than one initialization or
increment/decrement, separated using comma operator. But it can have only
one condition.
40
C PROGRAMMING
#include<stdio.h>
void main( )
int x;
41
C PROGRAMMING
printf("%d\t", x);
1 2 3 4 5 6 7 8 9 10
statement ;
#include<stdio.h>
42
C PROGRAMMING
void main( )
int i, j;
printf("\n");
printf("%d", j);
Copy
21
321
4321
54321
43
C PROGRAMMING
1) break statement
When break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following
the loop.
2) continue statement
It causes the control to go directly to the test-condition and then continue the
loop process. On encountering continue, cursor leave the current cycle of loop,
and starts with the next cycle.
44
C PROGRAMMING
Example:
#include<stdio.h>
int main()
{
int i;
45
C PROGRAMMING
46
C PROGRAMMING
Arrays
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. The array is the simplest data structure where each data element can be randomly
accessed by using its index number.
One-Dimensional Array
Two-Dimensional Array
Multi-Dimensional Array
One-Dimensional Array
The One-dimensional array can be defined as an array with a single row and multiple columns.
The elements in the 1D array are accessed using their index numbers.
47
C PROGRAMMING
1int arrayone[10];
Two-Dimensional Array
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. The elements of the
array are accessed using their intersection coordinates.
int arraytwo[10][5];
1
Multi-Dimensional Array
The multi-dimensional array can be defined as an array of arrays. The 3D array is organized as 3D
matrix which can be represented as the collection of multiple rows and columns. The elements of
the array are accessed using their 3D intersection coordinates.
1int arraythree[10][10][10];
Why do we need it? In this article, you will learn about the data structure array and its types
and why is it a widely used data structure. Let’s get into it.
An Array is a sequential collection of elements, of the same data type. They are stored
sequentially in memory. An Array is a data structure that holds a similar type of elements. The
array elements are not treated as objects in c like they are in java.
Imagine you are at a musical instrument store and I tell you to arrange all the keyboards under
the brand Casio at one place one above the other. This sequential collection of records is called
48
C PROGRAMMING
an Array. An array is a sequential collection of elements of the same data type. In our example
above, Casio is the data type and all the keyboards you collected are of the brand Casio. All the
elements in an array are addressed by a common name.
Datatype arrayName[arraySize];
We have a data type that can be any of the basic data types like int, float or double.
Array Name is the name of the array and we declare the size of the array.
Casio keyboardArray[100];
int test[30];
The array test will hold the elements of type int and will have a size 30.
ARRAY SIZE:
Array size is given at the time of declaration of the array. Once the size of the
array is given it cannot be changed. The compiler then allocates that much
memory space to the array.
int test[20];
49
C PROGRAMMING
In the example above, we have an array test, of type int. We have given the array
size to be 20. This means that 20 consecutive memory locations will be left free for
the array in the memory.
Here the array contains the values 12,41,3,13,7 and the indices are 0,1,2,3,4. If we want to
represent an element at index 4 it is represented as age[4] and the value 7 will be displayed.
Array initialization is done at the time of declaration. This can also be carried out later if the
user enters the array value as and when needed.
An array can be initialized during declaration. This is done by specifying the array elements at
the time of declaration. Here the array size is also fixed and it is decided by us.
int main()
return 0; }
EXPLANATION:
50
C PROGRAMMING
In the above example, we create an array of type int and with the name arr. We directly specify
the array elements. The size of the array is decided by counting the number of elements in our
array. In this case, the size is 4.
INITIALIZATION BY USER:
In this method, we let the user decide the size of the array. In this case, we need a variable to hold
the size of the array and a for loop to accept the elements of the array. We assign a random size
at the time of declaration and use only as needed. The size at the start is usually at the higher
side. We have a variable i to control the for loop.
#include<stdio.h>
int main()
int arr[50],n,i ;
scanf(“%d ”,n);
for(i=0;i<n;i++)
Scanf(“%d ”,arr[i]);
return 0;
OUTPUT:
EXPLANATION:
51
C PROGRAMMING
In the above program, we declare an array of size 50. We then ask the user to enter the number of
elements he wishes to enter in this array. We then accept the array elements entered by the user.
52
C PROGRAMMING
Displaying the array also requires the for-loop. We traverse to the entire array and
display the elements of the array.
Here is an example,
#include<stdio.h>
int main()
int arr[50],n,i ;
scanf(“%d ”,n);
for(i=0;i<n;i++)
Scanf(“%d ”,arr[i]);
for(i=0;i<n;i++)
Printf(“%d ”,arr[i]);
return 0;
OUTPUT:
53
C PROGRAMMING
EXPLANATION:
In the above program, we declare an array of size 50. We then ask the user to enter the number of
elements he wishes to enter in this array. We then accept the array elements entered by the user.
We then use a for loop again to display the array elements.
Accessing array elements is simple and is done by using the array index. Have a look at the
code below.
#include<stdio.h>
int main()
int arr[5],i ;
arr[4]=2;
arr[2]=17;
arr[0]=17;
for(i=0;i<5;i++)
printf(“%d ”,arr[i]);
return 0;
54
C PROGRAMMING
OUTPUT:
EXPLANATION:
In the program above, we have an array of size 5. We enter elements at different locations
using array index. We print the array to get the above output.
By Default, all the array elements are zero. What happens if we cross the array size?
In c, if we try to access the elements out of bound, error may not be shown by the compiler but
we will not get proper output.
MULTI-DIMENSIONAL ARRAY:
Arrays of arrays are multi-dimensional arrays. This is because each element in a multi-
dimensional array has an array of its own. We need n for loops to iterate through a
multidimensional array depending on the dimensions.
SYNTAX FOR DECLARING MULTI_DIMENSIONAL ARRAYS:
int a[10][20];
The size of the above array will be 10*20 that is 200 elements.
Each dimension requires one for loop. So, the two-dimensional array requires two- and three-
dimensional array requires three.
Consider the code:
#include<stdio.h>
int main()
55
C PROGRAMMING
return 0;
EXPLANATION:
In the above code, we display a 3*2 matrix. This array has 3 rows and 2 columns. We have 2 for
loops. Each responsible for one dimension of the array. The outer for loop takes care of rows and
inner of columns.
Similarly, we can write a code for three-dimensional array and there will be three for loops and
each dimension will be controlled by one for loop.
56
C PROGRAMMING
Strings
The string is defined as a one-dimensional array of characters terminated by a null character. The
character array or the string is used to store text such as word or sentences. Each character in the
array occupies one byte of memory, and the last character must always be 0.
char array
string literal
Function Functionality
strlen() Returns the length of the String
strcpy() Copies String from Source to Destination
strcat() Joins two Strings and stores result in first
strcmp() Compares the given two Strings
strrev() Reverses the String
strlwr() Converts String to Lower case
strupr() Converts String to Upper case
strchr() String scanning function
strncat() Concatenates String with the part of another
srtncmp() Compares the parts of two Strings
strncpy() Copies a part of the String
//Example
1#include<stdio.h>
2#include<string.h>
3int main( )
4{
5 int len;
6 char text[10]="saveetha" ;
7 length = strlen(array) ;
8 printf ( "string length is = %d n" , length ) ;
9 return 0;
10}
//Output
string length is = 7
Functions
57
C PROGRAMMING
A Function can be defined as a subdivided program of the main program enclosed within flower
brackets. Functions can be called by the main program to implement its functionality. This
procedure provides Code Re-usability and Modularity.
Library Functions
User-Defined Functions
Advantages of Functions
Function Declaration
A function is required to declared as Global and the name of the function, parameters of the
function and return type of the function are required to be clearly specified.
Function Call
While calling the function from anywhere in the program, care should be taken that the
datatype in the argument list and the number of elements in the argument list are matching.
Function Definition
After the function is declared, it is important that the function includes parameters declared,
code segment, and the return value.
58
C PROGRAMMING
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("Javatpoint");
}
Output
Hello Javatpoint
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
59
C PROGRAMMING
}
Example for Function with argument and without return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:
The sum is 34
60
C PROGRAMMING
Output
61
C PROGRAMMING
Let's understand call by value and call by reference in c language one by one.
Call by value in C
o In call by value method, the value of the actual parameters is copied into the
formal parameters. In other words, we can say that the value of the variable is
used in the function call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter
by the formal parameter.
o In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call
whereas formal parameter is the argument which is used in the function
definition.
Let's try to understand the concept of call by value in c language by the example
given below:
62
C PROGRAMMING
Call by reference in C
o In call by reference, the address of the variable is passed into the
function call as the actual parameter.
o The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is
passed.
o In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function
63
C PROGRAMMING
64
C PROGRAMMING
2 Changes made inside the function Changes made inside the function
is limited to the function only. The validate outside of the function
values of the actual parameters do also. The values of the actual
not change by changing the formal parameters do change by changing
parameters. the formal parameters.
3 Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory
location location
Recursion in C
Recursion is the process which comes into existence when a function calls
a copy of itself to work on a smaller problem. Any function which calls
itself is called recursive function, and such function calls are called
recursive calls. Recursion involves several numbers of recursive calls.
However, it is important to impose a termination condition of recursion.
Recursion code is shorter than iterative code however it is difficult to
understand.
Recursion cannot be applied to all the problem, but it is more useful for
the tasks that can be defined in terms of similar subtasks. For Example,
recursion may be applied to sorting, searching, and traversal problems.
65
C PROGRAMMING
1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
66
C PROGRAMMING
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
67
C PROGRAMMING
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }
Output
Enter the value of n?12
144
Let us consider the following example to understand the memory allocation of the recursive
functions.
68
C PROGRAMMING
Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value
of a variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register
extern RAM Zero Global Till the end of the main program Maybe
declared anywhere in the program
static RAM Zero Local Till the end of the main program, Retains
value between multiple functions call
69
C PROGRAMMING
Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are
defined.
The scope of the automatic variables is limited to the block in which they are
defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the
block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
8. return 0;
9. }
Output:
11. }
12. }
13. printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
14. }
Output:
11 20 20 20 11
Static
o The variables defined as static specifier can hold their value between the multiple function calls.
o Static local variables are visible only to the function or the block in which they are defined.
o A same static variable can be declared many times but can be assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }
Output:
0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
71
C PROGRAMMING
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }
Output:
10 24
11 25
12 26
Register
o The variables defined as the register is allocated the memory into the CPU registers depending upon
the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the register
variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU register. However, it
is compiler?s choice whether or not; the variables can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a variable.
o Static variables can not be stored into the register since we can not use more than one storage
specifier for the same variable.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
5. printf("%d",a);
6. }
72
C PROGRAMMING
Output:
0
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the address of
a register variable.
6. }
Output:
External
o The external storage class is used to tell the compiler that the variable defined as extern is declared
with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration and intended to
specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the external variable
within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be initialized
somewhere in the program which may be extern or static. If it is not, then the compiler will show an
error.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }
Output
73
C PROGRAMMING
Output
0
Example 3
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and initializer
at same time
6. printf("%d",a);
7. }
Output
Output
20
74
C PROGRAMMING
Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main()
5. {
6. printf("%d",a);
7. }
8. int a = 20; // compiler will show an error at this line
Output
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example, printf
is a library function used to print on the console. The library functions are created by the designers
of compilers. All C standard library functions are defined inside the different header files saved
with the extension .h. We need to include these header files in our program to make use of the
library functions defined in such header files. For example, To use the library functions such as
printf/scanf we need to include stdio.h in our program which is a header file that contains all the
library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
SN Header Description
file
1 stdio.h This is a standard input/output header file. It contains all the library
functions regarding standard input/output.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(),
calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like
sqrt(), pow(), etc.
75
C PROGRAMMING
9 signal.h All the signal handling functions are defined in this header file.
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following
result.
$./a.out testing
The argument supplied is testing
76
C PROGRAMMING
When the above code is compiled and executed with a two arguments, it produces the following
result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the
following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to
the first command line argument supplied, and *argv[n] is the last argument. If no arguments are
supplied, argc will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a
space then you can pass such arguments by putting them inside double quotes "" or single
quotes ''. Let us re-write above example once again where we will print program name and we
also pass a command line argument by putting inside double quotes −
#include <stdio.h>
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but
inside double quotes, it produces the following result.
$./a.out "testing1 testing2"
77
C PROGRAMMING
Pointer in C
What is Pointer in C?
The Pointer in C, is a variable that stores address of another variable. A pointer can also be
used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to
point to the next/ previous memory location. The purpose of pointer is to save memory
space and achieve faster execution time.
However, each variable, apart from value, also has its address (or, simply put, where it is
located in the memory). The address can be retrieved by putting an ampersand (&) before
the variable name.
If you print the address of a variable on the screen, it will look like a totally random number
(moreover, it can be different from run to run).
Now, what is a pointer? Instead of storing a value, a pointer will y store the address of a
variable.
78
C PROGRAMMING
Pointer Variable
Int *y = &v;
VARIABLE POINTER
A variable that points to the storage/mem
A value stored in a named storage/memory address
of another variable
Declaring a Pointer
Like variables, pointers in C programming have to be declared before they can be used in
your program. Pointers can be named anything you want as long as they obey C’s naming
rules. A pointer declaration has the following form.
data_type * pointer_variable_name;
Here,
data_type is the pointer’s base type of C’s variable types and indicates the type of the
variable that the pointer points to.
The asterisk (*: the same asterisk used for multiplication) which is indirection
operator, declares a pointer.
To get the address of a variable, we use the ampersand (&)operator, placed before the name
of a variable whose address we need. Pointer initialization is done with the following syntax.
Pointer Syntax
79
C PROGRAMMING
pointer = &variable;
#include <stdio.h>
int main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf("Address stored in a variable p is:%x\n",p);
//accessing the address
printf("Value stored in a variable p is:%d\n",*p);
//accessing the value
return 0;
}
Output:
Address stored in a variable p is:60ff08
Value stored in a variable p is:10
Operator Meaning
Serves 2 purpose
* 1. Declaration of a pointer
2. Returns the value of the referenced
variable
Types of Pointers in C
Following are the different Types of Pointers in C:
80
C PROGRAMMING
1. Null Pointer
We can create a null pointer by assigning null value during the pointer declaration. This
method is useful when you do not have any address assigned to the pointer. A null pointer
always contains value 0.
#include <stdio.h>
int main()
{
int *p = NULL; //null pointer
printf(“The value inside variable p is:\n%x”,p);
return 0;
}
Output:
#include <stdio.h>
int main()
{
void *p = NULL; //void pointer
printf("The size of pointer is:%d\n",sizeof(p));
return 0;
}
Output:
3. Wild pointer
A pointer is said to be a wild pointer if it is not being initialized to anything. These types of C
pointers are not efficient because they may point to some unknown memory location which
may cause problems in our program and it may lead to crashing of the program. One should
always be careful while working with wild pointers.
#include <stdio.h>
int main()
{
int *p; //wild pointer
printf("\n%d",*p);
return 0;
}
Output
timeout: the monitored command dumped core
sh: line 1: 95298 Segmentation fault timeout 10s main
Dangling pointer
Complex pointer
Near pointer
Far pointer
Huge pointer
#include <stdio.h>
/* Declare and initialize an int variable */
int var = 1;
/* Declare a pointer to int */
int *ptr;
int main( void )
{
/* Initialize ptr to point to var */
ptr = &var;
/* Access var directly and indirectly */
printf("\nDirect access, var = %d", var);
printf("\nIndirect access, var = %d", *ptr);
/* Display the address of var two ways */
printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);
/*change the content of var through the pointer*/
*ptr=48;
82
C PROGRAMMING
Pointer Arithmetics in C
The pointer operations are summarized in the following figure
Pointer Operations
83
C PROGRAMMING
The operators * and & have the same priority as the unary operators (the negation!,
the incrementation++, decrement–).
In the same expression, the unary operators *, &,!, ++, – are evaluated from right to left.
int X =10
int *P = &Y;
Y=*P+1 Y=X+1
*P=*P+10 X=X+10
*P+=2 X+=2
++*P ++X
(*P)++ X++
In the latter case, parentheses are needed: as the unary operators * and ++ are evaluated
from right to left, without the parentheses the pointer P would be incremented, not the
object on which P points.
Below table shows the arithmetic and basic operation that can be used when dealing with C
pointers
Operation Explanation
int *P1,*P2
Assignment P1=P2;
P1 and P2 point to the same integer variable
84
C PROGRAMMING
Int *P1;
Incrementation and decrementation
P1++;P1– ;
85
C PROGRAMMING
#include <stdio.h>
int main()
{
int a[5]={1,2,3,4,5}; //array initialization
int *p; //pointer declaration
/*the ptr points to the first element of the array*/
Pointer Addition/Increment
Since p currently points to the location 0 after adding 1, the value will become 1, and hence
the pointer will point to the memory location 1.
86
C PROGRAMMING
#include <stdio.h>
#include <string.h>
int main()
{
char str[]="Hello Guru99!";
char *p;
p=str;
printf("First character is:%c\n",*p); p
=p+1;
printf("Next character is:%c\n",*p);
printf("Printing all the characters in a string\n");
p=str; //reset the pointer
for(int i=0;i<strlen(str);i++)
{
printf("%c\n",*p);
p++;
}
return 0;
}
Output
First character is:H
Next character is:e
Printing all the characters in a string
H
e
l
l
o
G
u
r
u
9
9
!
Another way to deal strings is with an array of pointers like in the following program:
#include <stdio.h>
int main(){
char *materials[ ] = { "iron", "copper", "gold"};
printf("Please remember these materials :\n");
int i ;
for (i = 0; i < 3; i++) {
printf("%s\n", materials[ i ]);}
return 0;}
87
C PROGRAMMING
Advantages of Pointers in C
Pointers are useful for accessing memory locations.
Pointers provide an efficient way for accessing the elements of an array structure.
Pointers are used for dynamic memory allocation as well as deallocation.
Pointers are used to form complex data structures such as linked list, graph, tree, etc.
Disadvantages of Pointers in C
Pointers are a little complex to understand.
Pointers can lead to various errors such as segmentation faults or can access a
memory location which is not required at all.
If an incorrect value is provided to a pointer, it may cause memory corruption.
Pointers are also responsible for memory leakage.
Pointers are comparatively slower than that of the variables.
Programmers find it very difficult to work with the pointers; therefore it is
programmer’s responsibility to manipulate a pointer carefully.
Summary:
A pointer is nothing but a memory location where data is stored.
A pointer is used to access the memory location.
There are various types of pointers such as a null pointer, wild pointer, void pointer
and other types of pointers.
Pointers can be used with array and string to access elements more efficiently.
We can create function pointers to invoke a function dynamically.
Arithmetic operations can be done on a pointer which is known as pointer arithmetic.
Pointers can also point to function which make it easy to call different functions in the
case of defining an array of pointers.
When you want to deal different variable data type, you can use a typecast void
pointer.
88
C PROGRAMMING
The ,struct keyword is used to define the structure. Let's see the syntax
to define the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
The following image shows the memory allocation of the structure
employee that is defined in the above example.
89
C PROGRAMMING
Here, struct is the keyword; employee is the name of the structure; id, name,
and salary are the members or fields of the structure. Let's understand it by the
diagram given below:
1st way:
90
C PROGRAMMING
The variables e1 and e2 can be used to access the values stored in the structure.
Here, e1 and e2 can be treated in the same way as the objects in C++ and Java.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
If number of variables are not fixed, use the 1st approach. It provides you the
flexibility to declare the structure variable many times.
Let's see the code to access the id member of p1 variable by. (member)
operator.
p1.id
C Structure example
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
91
C PROGRAMMING
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Let's see another example of the structure in C language to store many employees
information.
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. e1.id=101;
12. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
13. e1.salary=56000;
14.
15. //store second employee information
16. e2.id=102;
17. strcpy(e2.name, "James Bond");
18. e2.salary=126000;
19.
20. //printing first employee information
92
C PROGRAMMING
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000
typedef in C
The typedef is a keyword used in C programming to provide some meaningful
names to the already existing variable in the C program
. It behaves similarly as we define the alias for the commands. In short, we can say that this
keyword is used to redefine the name of an already existing variable.
Syntax of typedef
typedef <existing_name> <alias_name>
For example, suppose we want to create a variable of type unsigned int, then it
becomes a tedious task if we want to declare multiple variables of this type. To
overcome the problem, we use a typedef keyword.
93
C PROGRAMMING
Now, we can create the variables of type unsigned int by writing the following
statement:
unit a, b;
1. #include <stdio.h>
2. int main()
3. {
4. typedef unsigned int unit;
5. unit i,j;
6. i=10;
7. j=20;
8. printf("Value of i is :%d",i);
9. printf("\nValue of j is :%d",j);
10. return 0;
11. }
Output
Value of i is :10
Value of j is :20
Using typedef with structures
struct student
{
char name[20];
int age;
94
C PROGRAMMING
};
struct student s1;
In the above structure declaration, we have created the variable of student type by
writing the following statement:
The above statement shows the creation of a variable, i.e., s1, but the statement is
quite big. To avoid such a big statement, we use the typedef keyword to create
the variable of type student.
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;
In the above statement, we have declared the variable stud of type struct student.
Now, we can use the stud variable in a program to create the variables of
type struct student.
From the above declarations, we conclude that typedef keyword reduces the length
of the code and complexity of data types. It also helps in understanding the
program.
95
C PROGRAMMING
#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}
We can also provide another name or alias name to the pointer variables with the help of the
typedef.
96
C PROGRAMMING
1. int* ptr;
In the above statement, we have declared the variable of type int*. Now, we can
create the variable of type int* by simply using the 'ptr' variable as shown in the
below statement:
1. ptr p1, p2 ;
C Array of Structures
Why use an array of structures?
Consider a case, where we need to store the data of 5 students. We can store it by using the
structure as given below.
1. #include<stdio.h>
2. struct student
3. {
4. char name[20];
5. int id;
6. float marks;
7. };
8. void main()
9. {
10. struct student s1,s2,s3;
11. int dummy;
12. printf("Enter the name, id, and marks of student 1 ");
13. scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
14. scanf("%c",&dummy);
97
C PROGRAMMING
Output
In the above program, we have stored data of 3 students in the structure. However,
the complexity of the program will be increased if there are 20 students. In that case,
we will have to declare 20 different structure variables and store them one by one.
This will always be tough since we will have to declare a variable every time we add a
student. Remembering the name of all the variables is also a very tricky task.
However, c enables us to declare an array of structures by using which, we can avoid
declaring the different structure variables; instead we can make a collection
containing all the structures that store the information of different entities .
Array of Structures in C
An array of structures in C can be defined as the collection of
multiple structures variables where each variable contains
information about different entities. The array of structures in
C are used to store information about multiple entities of
different data types. The array of structures is also known as the
collection of structures.
98
C PROGRAMMING
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
99
C PROGRAMMING
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
100
C PROGRAMMING
Union
A union is a special data type available in C that allows storing different data types
in the same memory location. union is the keyword used to declare
Union.
Union is a user-defined data type, but unlike structures, they share the
same memory location.
//Example
1#include<stdio.h>
2union Employee
3{
101
C PROGRAMMING
4 int Id;
5 char Name[25];
6 int Age;
7 long Salary;
8};
9void main()
10{
11 union Employee E;
12 printf("nEnter Employee Id : ");
13 scanf("%d",&E.Id);
14 printf("nEnter Employee Name : ");
15 scanf("%s",&E.Name);
16 printf("nEnter Employee Age : ");
17 scanf("%d",&E.Age);
18 printf("nEnter Employee Salary : ");
19 scanf("%ld",&E.Salary);
20 printf("nnEmployee Id : %d",E.Id);
21 printf("nEmployee Name : %s",E.Name);
22 printf("nEmployee Age : %d",E.Age);
23 printf("nEmployee Salary : %ld",E.Salary);
24}
//Output
Employee Id : 102011
Employee Name : Ajay
Employee Age : 26
Employee Salary : 45000
102
C PROGRAMMING
#include <stdio.h>
union abc
{
int a;
char b;
};
int main()
{
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}
In the above code, we have created a pointer variable, i.e., *ptr, that stores
the address of var variable. Now, ptr can access the variable 'a' by using
the (->) operator. Hence the output of the above code would be 90.
Memory Each member has a unique Memory All members share allocated Memory
Initialization All members are initialized together Only first member can be initialized
Data Access All members is accessed together One member is accessed at a time
103
C PROGRAMMING
Value Changing the value of one member Changing the value of one member
Change will not affect others will affect others
104
C PROGRAMMING
File Handling in C
In programming, we may require some specific input data to be generated several
numbers of times. Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only a limited amount of
data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on
the local file system through our C program. The following operations can be
performed on a file.
105
C PROGRAMMING
o The file name (string). If the file is stored at some specific location, then we
must mention the path at which the file is stored. For example, a file name can
be like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
Mode Description
106
C PROGRAMMING
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
107
C PROGRAMMING
13. }
14. fclose (fp ) ;
15. }
Output
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and
stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
Syntax:
108
C PROGRAMMING
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
Output:
109
C PROGRAMMING
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to
write data into file at desired location.
Syntax:
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR
and SEEK_END.
1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }
myfile.txt
C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful
if you have to use stream many times.
Syntax:
110
C PROGRAMMING
The ftell() function returns the current file position of the specified stream. We can
use ftell() function to get the total size of a file after moving file pointer at the end of
file. We can use SEEK_END constant to move the file pointer at the end of file.
Syntax:
111