7BCE1C1 - Programming in C
7BCE1C1 - Programming in C
NAME :
CLASS :
SUBJECT NAME :
SUBJECT CODE :
PROGRAMMING IN C
UNIT-I
Overview of C: Importance of C, sample C program, C program structure, executing C program.
Constants, Variables, and Data Types: Character set, C tokens, keywords and identifiers, constants,
variables, data types, declaration of variables, Assigning values to variables--- Assignment statement,
declaring a variable as constant, as volatile.
Operators and Expression: Arithmetic, Relational, logical, assignment, increment, decrement,
conditional, bitwise and special operators, arithmetic expressions, operator precedence, type
conversions, mathematical functions
Managing Input and Output Operators: Reading and
writing a character, formatted input, formatted output.
UNIT-II
Decision Making and Branching: Decision making with If, simple IF, IF ELSE, nested IF ELSE ,
ELSE IF ladder, switch, GOTO statement.
Decision Making and Looping: While, Do-While, For, Jumps in loops.
UNIT-III
Arrays: Declaration and accessing of one & two-dimensional arrays, initializing two-dimensional
arrays, multidimensional arrays.
Functions: The form of C functions, Return values and types, calling a function, categories of
functions, Nested functions, Recursion, functions with arrays, call by value, call by
reference, storage classes-character arrays and string functions.
UNIT-IV
Structures and Unions: Defining, giving values to members, initialization and comparison of
structure variables, arrays of structure, arrays within structures, structures within structures,
structures and functions, unions.Preprocessors: Macro substitution, file inclusion.
UNIT-V
Pointers: definition, declaring and initializing pointers, accessing a variable through address and
through pointer, pointer expressions, pointer increments and scale factor, pointers and arrays,
pointers and functions, pointers and structures.
TEXT BOOK
E. Balagurusamy, Programming in ANSI C, Fifth Edition, Tata McGraw-Hill, 2010
REFERENCE BOOKS
Byron Gottfried, Schaum’s Outline Programming with C, Fourth Edition, Tata McGraw-Hill, 2018.
Kernighan and Ritchie, The C Programming Language, Second Edition, Prentice Hall,1998
YashavantKanetkar, Let Us C, Eighteenth Edition, BPB Publications,2021
UNIT-I
History of c
1. It is robust language whose rich setup of built in functions and operator can be used to
write any complex program.
2. Program written in C are efficient due to several variety of data types and powerful
operators.
3. The C compiler combines the capabilities of an assembly language with the feature of
high level language. Therefore it is well suited for writing both system software and
business package.
4. There are only 32 keywords; several standard functions are available which can be used
for developing program.
5. C is portable language; this means that C programs written for one computer system can
be run on another system, with little or no modification.
6. C language is well suited for structured programming, this requires user to think of a
problems in terms of function or modules or block. A collection of these modules make a
program debugging and testing easier.
programming Style:
1. It has to use lowercase letters. Uppercase only used for symbolic constant.
Character set
1. Letters
2. Digits
3. Special characters
4. White space
Letters
C language supports all the alphabets from the English language. Lower and upper case letters
together support 52 alphabets.
lower case letters - a to z
UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special characters
C language supports a rich set of special characters- camma,period semicolon colan,question
mark ect( ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ |)
white spaces, backspaces,harizantal tab,carriage return,newline,form feed.
C Tokens
The smallest individual unit are known as tokens. C has six types of tokens as shown in fig.
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
1.6.3. Strings
The string constants are a sequence of characters enclosed in double quotes. A string is an
array of characters ended with a null character (\0). This null character indicates that
string has ended. Strings are always enclosed with double quotes (“ “).
Let us see how to declare String in C language −
Special Symbols
Some special backslash character constants are used in Output functions. These
characters combination is known as escape sequences.
Operators in C
Operators is a special symbol used to perform the functions. The data items on which the
operators are applied are known as operands. Operators are applied between the
operands.
Variables
A variable is a data name that may be used to store a data value. the values can be
changed during the execution time.
Rules for variable names
Data types
Data types are the keywords, which are used for assigning a type to a variable.
Primary (Fundamental)datatypes
Derived data types
User defined data types
Primary (Fundamental)datatypes
1. Integer(int)-Integer are whole numbers with a range. Integer occupy one word of
storage. C has three class of integer storage that is short int, int, long int all in signed and
unsigned forms. The storage size of int data type is 2 or 4 or 8 byte. int (2 byte) can store
values from -32,768 to +32,767.int (4 byte) can store values from -2,147,483,648 to
+2,147,483,647.
5. Void - The void has no values. This is usually used to specify the type of functions. The
type of function is said to be void when it does not return any value to the calling
function. It can also play a role of a generic type, meaning that it can represent any of the
other standard types.
Declaration of variables
After designing suitable variable names, we must declare them to the compiler. The declaration
does 2 things:
data-type v1,v2,…vn;
where v1,v2…vn are the names of variables. Example int count; double ratio
We often use certain unique constants in a program. These constants may appear repeatedly in a
number of places in the program. A constant is 3.142, for “pi” value. The “pi” value can be used
for many purposes in a program. We face two problems in the subsequent use of such programs.
Assignment of such constants to a symbolic name frees us from these problems. The symbolic
constant can be defined as follows:
#define symbolic_name value of constant
// Example
#define STRENGTH 100
#define PASS_MARK 50
Symbolic names are sometimes called constant identifiers. The following are the rules for
declaring symbolic constants,
The need of certain values of variables to remain constant during the execution of a program.
This can be done with by declaring the variable with the qualifier const at the time of
initialization.
Ex: const int class_size=40;
(value of the int variable class_size cannot be modified by the program).
Problem of data overflow occurs when the value of a variable is either too big or too
small for the data to hold
In floating point conversions, the values are rounded off to the number of significant
digits
An overflow normally results in the largest possible value a machine can hold and
underflow results in zero
The overflow problem may occur if the data type does not match the value of the constant
‘C’ does not provide any warning or indication of integer overflow. It simply gives
incorrect results. So care should be taken to define correct data types for handling I/O
values
Operators
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators require some data to operate on and such data is called operands.
Operators in C can be classified into following categories:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators
C programming language provides all basic arithmetic operators. These are used to perform
mathematical calculations like addition, subtraction, multiplication, division and modulus.
The ‘/’ is integer division which only gives integer part as result after division. ‘%’ is
modulo division which gives the remainder of integer division as result.
Relational Operators
These operators are used to compare the value of two variables.
Logical Operators
These operators are used to perform logical operations on the given two variables. Logical
operators are used when more than one conditions are to be tested and based on that result,
decisions have to be made. An expression which combines two or more relational
expressions is known as logical expression.
Assignment Operators
Assignment operators are used to assign the result of an expression to a variable. The most
useful assignment operator in C is ‘=’. C also has a set of following shorthand assignment
operators.
var op = exp;
is the same as the assignment
var = var op exp;
where var is a variable, op is arithmetic operator, exp is an expression. In this case, ‘op=’ is
known as shorthand assignment operator.
Conditional Operators
Conditional operators return one value if condition is true and returns another value is
condition is false.The operator pair “?” and “:” is known as conditional operator. These pair
of operators are ternary operators. The syntax is:
expression1 ? expression2 : expression3 ;
This syntax can be understood as a substitute of if else statement.
Consider an if else statement as:
if (a > b)
x=a;
else
x=b;
Now, this if else statement can be written by using conditional operator as:
x = (a > b) ? a : b ;
Bitwise Operators
In C programming, bitwise operators are used for testing the bits or shifting them left or
right.
Special Operators
C programming supports special operators like comma operator, sizeof operator, pointer
operators (& and *) and member selection operators (. and ->).
i). Comma Operator
The comma operator can be used to link the related expressions together. A comma linked
expression is evaluated from left to right and the value of the right most expression is the
value of the combined expression.
For example:
x = (a = 2, b = 4, a+b)
In this example, the expression is evaluated from left to right. So at first, variable a is
assigned value 2, then variable b is assigned value 4 and then value 6 is assigned to the
variable x. Comma operators are commonly used in for loops, while loops, while exchanging
values.
ii). Sizeof() operator
The sizeof operator is usually used with an operand which may be variable, constant or a data
type qualifier. This operator returns the number of bytes the operand occupies. Sizeof
operator is a compile time operator. The sizeof operator is usually used to determine the
length of arrays and structures when their sizes are not known. It is also used in dynamic
memory allocation.
x = sizeof (a);
y = sizeof(float);
Expressions
Arithmetic expression in C is a combination of variables, constants and operators written in a
proper syntax. C can easily handle any complex mathematical expressions but these
mathematical expressions have to be written in a proper syntax. Some examples of
mathematical expressions written in proper syntax of C are:
Evaluation of expression
Expressions are evaluated using an assignment statement of the form:
Variable=expression;
The expression evaluated first and the result then replaces the previous value of the variable on the left
hand side. All the variables used in the expression must be assigned values before evaluation attempted.
Examples of evaluation statement are
The blank space around an operator is optional and adds only to improve readability. When these
statement are used in program, the variable a,b,c and d must be defined before they are used in the
expressions.
First Pass
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets
changed.
For example,x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are evaluated first
from left to right. The expression is now evaluated in three passes as:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7
There may even arise a case where nested parentheses are present (i.e. parenthesis inside
parenthesis). In such case, the expression inside the innermost set of parentheses is evaluated
first and then the outer parentheses are evaluated.For example, we have an expression as:
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2
Operator Precedence The precedence is used to determine how an expression involving more
than one operator is evaluated. There are distinct levels of precedence and an operator may
belong to any of these levels. The operators at higher level of precedence are evaluated first. The
number of evaluation steps is equal to the number of operators in the arithmetic expression.
Mathematical function
Syntax:
putchar(var_name);
Formatted Input
It refers to an input data which has been arranged in a specific format. This is possible in C
using scanf(). We have already encountered this and familiar with this function.
Syntax:
scanf("control string", arg1, arg2, ..., argn);
The field specification for reading integer inputted number is:%w sd .Here the % sign denotes
the conversion specification; w signifies the integer number that defines the field width of the
number to be read. d defines the number to be read in integer format.
Input data items should have to be separated by spaces, tabs or new-line and the punctuation
marks are not counted as separators.
Formatted output
The function printf() is used for formatted output to standard output based on a format
specification. The format specification string, along with the data to be output, are the parameters
to the printf() function.
Syntax:
printf("control string", arg1, arg2, ..., argn);
In this syntax format is the format specification string. This string contains, for each variable to
be output, a specification beginning with the symbol % followed by a character called the
conversion character.
Reading and Writing Strings in C
There are two popular library functions gets() and puts() provides to deal with strings in C.
gets:
The char *gets(char *str) reads a line from stdin and keeps the string pointed to by the str and is
terminated when the new line is read or EOF is reached. The declaration of gets() function is:
Syntax:
char *gets(char *str);
Syntax:
int puts(const char *str)
‘C’ language processes decision making capabilities supports the flowing statements known as
control or decision making statements
1. If statement
2. switch statement
3. conditional operator statement
4. Goto statement
If Statement : The if statement is powerful decision making statement and is used to control
the flow of execution of statements The If statement may be complexity of conditions to be
tested
If(test expression)
{
statement block;
} statement-x ;
The statement -block may be a single statement or a group of statement if the test
expression is true the statement block will be executed. Otherwise the statement -block will be
skipped and the execution will jump to the statement –X. If the condition is true both the
statement –block sequence .
Flow chart :
Ex : If(category = sports)
{ marks = marks + bonus marks;
} printf(“%d”,marks);
If the student belongs to the sports category then additional bonus marks are added to
his marks before they are printed. For other bonus marks are not added .
If –Else Statement : The If statement is an extension of the simple If statement the general
form is
If (test expression)
{
true-block statements;
}
else
{
false-block statements;
}
statement – x;
If the test expression is true then block statement are executed, otherwise the false –block
statement are executed. In both cases either true-block or false-block will be executed not both.
Flow chart :
Ex : If (code == 1)
boy = boy + 1;
else
girl = girl + 1;
st-x;
Here if the code is equal to ‘1’ the statement boy=boy+1; Is executed and the control is
transfered to the statement st-n, after skipping the else part. If code is not equal to ‘1’ the
statement boy =boy+1; is skipped and the statement in the else part girl =girl+1; is executed
before the control reaches the statement st-n.
Nested If –else statement : When a series of decisions are involved we may have to use
more than one if-else statement in nested form of follows .
If(test expression)
{ if(test expression)
{ st –1;
}
else
{ st – 2;
}else
{
st – 3;
}
}st – x;
If the condition is false the st-3 will be executed otherwise it continues to perform the
nested If –else structure (inner part ). If the condition 2 is true the st-1 will be executed
otherwise the st-2 will be evaluated and then the control is transferred to the st-x
If ( test condition1)
{ if (test condition2)
st –1 ;
} else
if (condition 3)
{ if (condition 4)
st – 2;
}st – x;
Else-If ladder : A multi path decision is charm of its in which the statement associated with
each else is an If. It takes the following general form.
If (condition1)
St –1;
Else If (condition2)
St –2;
Else if (condition 3)
St –3;
Else
Default – st;
St –x;
This construct is known as the wise-If ladder. The conditions are evaluated from the top
of the ladder to down wards. As soon as a true condition is found the statement associated with
it is executed and the control the is transferred to the st-X (i.e.., skipping the rest of the ladder).
when all the n-conditions become false then the final else containing the default – st will be
executed.
Switch Statement : Instead of else –if ladder, ‘C’ has a built-in multi-way decision
statement known as a switch. The general form of the switch statement is as follows.
Switch (expression)
{
case value1 : block1;
break;
case value 2 : block 2;
break;
The expression is an integer expression or character value1, value-2 ---- are constants or
constant expressions and also known as case lables. Each of the values should be a unit within a
switch and may contain zero or more statements.
When the switch is executed the value of the expression is successively compared against
the values value-1,value-2------- If a case is found whose value matches with the of the
expression then the block of statements that follows the case are executed .
The break statement at the end of each block signals the end a particular case and causes
an exist from the switch statement transfering the control to the st-x following the switch. The
default is an optional case . If will be executed if the value of the expression doesn’t match with
any Of the case values then control goes to the St-x.
Ex : switch (number)
{
case 1 : printf(“Monday”);
break;
case 2 : printf(“Tuesday”);
break;
case 3 : printf(“Wednesday”);
break;
case 4 : printf(“Thursday”);
break;
case 5 : printf(“Friday”);
break;
default : printf(“Saturday”);
break;
}
The Conditional ( ? : ) Operator : These operator is a combinations of question and
colon and takes three operands this is also known as conditional operator. The general form of
the conditional operator is as follows
Ex : flag = ( x<0) ? 0 : 1
If ( x<0)
Flag = 0;
Else
Flag = 1;
Goto Statement : The goto statement is used to transfer the control of the program from one
point to another. It is something reffered to as unconditionally branching. The goto is used in the
form
Goto label;
Label statement : The label is a valid ‘C’ identifier followed by a colon. we can precode any
statement by a label in the form
Label : statement ;
This statement immediately transfers execution to the statement labeled with the label
identifier.
Ex : i = 1;
bc : if(1>5) Output : 1
goto ab; 2
printf(“%d”,i); 3
++i; 4
gotobc; 5
ab : {
printf(“%d”,i); }
Decision making looping
The ‘C’ language provides three loop constructs for performing loop operations they
are
1. The while statement
2. Do-while statement
3. The for statement
The While Statement : This type of loop is also called an entry controlled, is executed and
if is true then the body of the loop is executed this process repeated until the boolean expression
becomes false. Ones it becomes false the control is a transferred out the loop. The general form
of the while statement is
Ex : i = 1;
While(I<=5)
{ printf(“%d”,i);
i++; }
In the above example the loop with be executed until the condition is false
Do-While Statement : This type of loop is also called an exist controlled loop statement.
i.e.., The boolean expression evaluated at the bottom of the loop and if it is true then body of the
loop executed again and again until the boolean expression becomes false. Ones it becomes false
the control is do-while statement is
Do
{
body of the loop ;
}
while ( boolean expression)
Flowchart:
Ex : i = 1;
Do
{
printf(“%d”,i);
i++;
}
While(i<=5)
The For Statement : The for loop is another entry control led loop that provides a more
concise loop control structure the general form of the for loop is
Where initialization is used to initialize some parameter that controls the looping action,
‘test condition’ represents if that condition is true the body of the loop is executed, otherwise
the loop is terminated After evaluating information and the new value of the control variable is
again tested the loop condition. If the condition is satisfied the body of the loop is again
executed it this process continues until the value of the control variable false to satisfy the
condition.
Flow chart :
Break Statement : The break statement can be accomplish by using to exist the loop. when
break is encountered inside a loop, the loop is immediately exited and the program continues
with the statement which is followed by the loop. If nested loops then the break statement inside
one loop transfers the control to the next outer loop.
Continue Statement : The continue statement which is like break statement. Its work is to
skip the present statement and continues with the next iteration of the loop .
What is Array?
C programming language provides a data structure called the array, which
can store a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ...,
and number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last
element.
int anArrayName[10];
double balance[10];
You can initialize array in C either one by one or using a single statement
as follows:
The number of values between braces { } can not be larger than the
number of elements that we declare for the array between square
brackets [ ]. Following is an example to assign a single element of the
array:
o If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:
o You will create exactly the same array as you did in the previous
example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value
of 50.0. Array with 4th index will be 5th i.e. last element because all
arrays have 0 as the index of their first element which is also called
base index. Following is the pictorial representation of the same array
we discussed above:
The above statement will take 10th element from the array and assign the
value to salary variable.
Following is an example which will use all the above mentioned three
concepts viz. declaration, assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Two-Dimensional Arrays
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C
identifier. A two dimensional array can be think as a table which will have
x number of rows and y number of columns. A 2-dimentional array a,
which contains three rows and four columns can be shown as below:
form a[ i ][ j ], where a is the name of the array, and i and j are the
};
The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to previous example:
The above statement will take 4th element from the 3rd row of the array.
You can verify it in the above diagram. Let us check below program where
we have used nested loop to handle a two dimensional array:
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions,
although it is likely that most of the arrays you create will be of one or
two dimensions.
Multi-dimensional Arrays
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 2 , 3, 2
integer array:
int test[2][3][2];
Example C program for multi dimensional array,
// C Program to store and print 12 values entered by the user
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{ scanf("%d", &test[i][j][k]); }
}
}
// Printing values with proper index.
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
When the above code is compiled and executed, it produces the
following result
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
Dynamic Arrays
A string is a simple array with char as a data type. 'C' language does not
directly support string as a data type. Hence, to display a string in 'C', you
need to make use of a character array.
The general syntax for declaring a variable as a string is as follows,
The above example represents string variables with an array size of 15.
This means that the given character array is capable of holding 15
characters at most. The indexing of array begins from 0 hence it will store
characters from a 0-14 position. The C compiler automatically adds a
NULL character '\0' to the character array created.
Let's study the initialization of a string variable. Following example
demonstrates the initialization of a string variable,
When writing interactive programs which ask the user for input, C
provides the scanf(), gets(), and fgets() functions to find a line of text
entered from the user.
scanf() function:
When we use scanf() to read, we use the "%s" format specifier without
using the "&" to access the variable address because an array name acts
as a pointer. For example:
#include <stdio.h>
int main()
{
char name[10];
int age;
printf("Enter your first name and age: \n");
scanf("%s %d", name, &age);
printf("You entered: %s %d",name,age);
}
Output:
The problem with the scanf function is that it never reads an entire string.
It will halt the reading process as soon as whitespace, form feed, vertical
tab, newline or a carriage return occurs. Suppose we give input as
"Guru99 Tutorials" then the scanf function will never read an entire string
as a whitespace character occurs between the two names. The scanf
function will only read Guru99.
gets() function:
In order to read a string contains spaces, we use the gets() function. Gets
ignores the whitespaces. It stops reading when a newline is reached (the
Enter key is pressed).For example:
#include <stdio.h>
int main()
{
char filename[25];
printf("Enter your full name: ");
gets(full_name);
printf("My full name is %s ",full_name);
return 0;
}
Output:
fgets() function:
#include <stdio.h>
int main()
{
char name[10];
printf("Enter your name plz: ");
fgets(name, 10, stdin);
printf("My name is %s ",name);
return 0;
}
Output:
Example,
printf("%s", name);
String output is done with the fputs(), puts() and printf() functions.
fputs() function:
The fputs() needs the name of the string and a pointer to where you want
to display the text. We use stdout which refers to the standard output in
order to print to the screen. For example:
#include <stdio.h>
int main()
{
char town[40];
printf("Enter your town: ");
gets(town);
fputs(town, stdout);
return 0;
}
Output:
puts() function
The puts function prints the string on an output device and moves the
cursor back to the first position. A puts function can be used in the
following way,
#include <stdio.h>
int main()
{
char name[15];
gets(name); //reads a string
puts(name); //displays a string
return 0;
}
Function Purpose
#include <stdio.h>
#include <string.h>
int main ()
{
//string initialization
char string1[15]="Hello";
char string2[15]=" World!";
char string3[15];
int val;
//string comparison
val= strcmp(string1,string2);
if(val==0)
{
printf("Strings are equal\n");
}
else
{
printf("Strings are not equal\n");
}
//string concatenation
printf("Concatenated:%s",strcat(string1,string2));
//string length
printf("\nLengthstring1 :%d",strlen(string1));
printf("\nLengthstring2: %d",strlen(string2));
//string copy
printf("\nCopied:%s\n",strcpy(string3,string1));
//string1 is copied into string3
return 0;
}
Output:
FUNCTIONS
Need Multifunction program :
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division is such that each function performs a
specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to another
location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.
Here, int before function name indicates that this function returns integer value to the caller
while int inside parentheses indicates that this function will recieve an integer value from
caller.
Function Call
Here, function square is called in main
Function definition
A function definition provides the actual body of the function.
Syntax of function definition
return_value_typefunction_name (parameter_list)
Return statement returns the value and transfer control to the caller.
Defining a Function
The general form of a function definition in C programming language is as follows −
Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list refers
to the type, order, and number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
Function Body − The function body contains a collection of statements that define what the
function does.
Example
Given below is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum value between the two −
/* function returning the max between two numbers */
int max(int num1, int num2) {
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration has the following parts −
return_typefunction_name( parameter list );
For the above defined function max(), the function declaration is as follows
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the following
is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling
the function.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main
program.
To call a function, you simply need to pass the required parameters along with the function name,
and if the function returns a value, then you can store the returned value. For example −
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
}
return result;
}
We have kept max() along with main() and compiled the source code. While running the final
executable, it would produce the following result −
Max value is : 200
Return statement returns the value and transfer control to the caller.
return;
The above return statement does not return value to the caller.
return expression;
The above return statement returns the value of expression to the caller.
return 0;
The above return statement indicate whether the program executed correctly.
function calls
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a
function
1 Call by value
2 Call by reference
This method copies the address of an argument into the
formal parameter. Inside the function, the address is used to
access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function.
Category of Functions
A function depending an whether the arguments are present or not and whether a value is returned or not,
may belong to one of following categories
Output:
Enter n value: 5
12345
Note:
In the main() function, n value is passed to the nat() function. The n value is now stored in the formal argument n,
declared in the function definition and subsequently, the natural numbers upto n are obtained.
Output:
Enter n: 5
Factorial of the number : 120
Functions with no arguments and return values.
In this category, the functions has no arguments and it doesn’t receive any data from the calling function, but it returns a
value to the calling function. The calling function receives data from the called function. So, it is one way data
communication between calling and called functions.
Eg:
view source
print?
01 #include<stdio.h>
02 #include<conio.h>
03 int sum();
04 void main()
05 {
06 int s;
07 clrscr();
08 printf("\n Enter number of elements to be added :");
09 s=sum();
10 printf("\n Sum of the elements :%d",p);
11 getch();
12 }
13
14 int sum()
15 {
16 int a[20], i, s=0,n;
17 scanf("%d",&n);
18 printf("\n Enter the elements:");
19 for(i=0;i< n; i++)
20 scanf("%d",& a[i]);
21 for(i=0;i< n; i++)
22 s=s+a[i];
23 return s;
24 }
Nesting of functions
In some applications, we have seen that some functions are declared inside another function. This is
sometimes known as nested function, but actually this is not the nested function. This is called the
lexical scoping. Lexical scoping is not valid in C because the compiler is unable to reach correct
memory location of inner function.
Nested function definitions cannot access local variables of surrounding blocks. They can access
only global variables. In C there are two nested scopes the local and the global. So nested function
has some limited use. If we want to create nested function like below, it will generate error.
Example
#include<stdio.h>
main(void){
printf("Main Function");
intmy_fun(){
printf("my_fun function");
int my_fun2(){
my_fun2();
Output
text.c:(.text+0x1a): undefined reference to `my_fun2'
But an extension of GNU C compiler allows declaration of the nested function. For this we have to
add auto keyword before the declaration of nested function.
Example
#include<stdio.h>
main(void){
autointmy_fun();
my_fun();
printf("Main Function\n");
intmy_fun(){
printf("my_fun function\n");
printf("Done");
Output
my_fun function
Main Function
Done
Recursion
Recursion is the process of repeating items in a self-similar way. In programming languages,
if a program allows you to call a function inside the same function, then it is called a recursive call of
the function.
void recursion(){
recursion();/* function calls itself */
}
int main(){
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.
Number Factorial
The following example calculates the factorial of a given number using a recursive function –
#include<stdio.h>
unsignedlonglongint factorial(unsignedinti){
if(i<=1){
return1;
}
returni* factorial(i-1);
}
int main(){
inti=12;
printf("Factorial of %d is %d\n",i, factorial(i));
return0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −
#include<stdio.h>
intfibonacci(inti){
if(i==0){
return0;
}
if(i==1){
return1;
}
returnfibonacci(i-1)+fibonacci(i-2);
}
int main(){
inti;
for(i=0;i<10;i++){
printf("%d\t\n",fibonacci(i));
}
return0;
}
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34
As we already know in this type of function call, the actual parameter is copied to the formal
parameters.
#include<stdio.h>
voiddisp( charch)
{
printf("%c ", ch);
}
int main()
{
chararr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}
return0;
}
Output:
a bcdefghij
#include<stdio.h>
voiddisp( int *num)
{
printf("%d ", *num);
}
int main()
{
intarr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (inti=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return0;
}
Output:
1234567890
#include<stdio.h>
voidmyfuncn( int *var1, int var2)
{
/* The pointer var1 is pointing to the first element of
* the array and the var2 is the size of the array. In the
* loop we are incrementing pointer so that it points to
* the next element of the array on each increment.
*
*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
intvar_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return0;
}
Output:
Scope
Scope is defined as the area in which the declared variable is ‘available’. There are five scopes in
C: program, file, function, block, and prototype. Let us examine a dummy program to understand the
difference (the comments indicate the scope of the specific variable):
1 void foo() {}
2 // "foo" has program scope
3 static void bar() {
4 // "bar" has file scope
5 printf("hello world");
6 inti;
7 // "i" has block scope
8 }
void baz(int j);
9 // "j" has prototype scope
10 print:
11 // "print" has function scope
The foo function has program scope. All non-static functions have program scope, and they can
be called from anywhere in the program. Of course, to make such a call, the function needs to be
first declared using extern, before being called, but the point is that it is available throughout the
program.
The function bar has file scope — it can be called from only within the file in which it is
declared. It cannot be called from other files, unlike foo, which could be called after providing
the external declaration of foo.
The label print has function scope. Remember that labels are used as a target for jumps using
goto in C. There can be only one print label inside a function, and you can write a goto
print statement anywhere in the function, even before the label appears in the function. Only
labels can have function scope in C.
The variable i has block scope, though declared at the same level/block as print. Why is that so?
The answer is, we can define another variable with the same name i inside another block within
the bar function, whereas it is not possible for print, since it is a label.
The variable j has prototype scope: you cannot declare any other parameter with the same
name j in the function baz. Note that the scope of j ends with the prototype declaration: you can
define the function baz with the first argument with any name other than j.
Lifetime
The lifetime of a variable is the period of time in which the variable is allocated a space (i.e., the
period of time for which it “lives”). There are three lifetimes in C: static, automatic and dynamic. Let us
look at an example:
1 int foo() {
2 static int count = 0;
3 // "count" has static lifetime
4 int * counter = malloc(sizeof(int));
// "counter" has automatic lifetime
5 free(counter);
6 // malloc’ed memory has dynamic lifetime
7 }
8
In this code, the variable count has a static lifetime, i.e., its lifetime is that of the program. The
variable counter has an automatic lifetime — its life is till the function returns; it points to a
heap-allocated memory block — its life remains till it is explicitly deleted by the program, which
is not predictable, and hence it has a dynamic lifetime.
Visibility
Visibility is the “accessibility” of the variable declared. It is the result of hiding a variable in outer
scopes. Here is a dummy example:
1 inti;
2 // the "i" variable is accessible/visible here
3 void foo() {
4 inti;
5 // the outer "i" variable
6 // is not accessible/visible here
7 {
8 inti;
9 // two "i" variables at outer scopes
10 // are not accessible/visible here
11 }
12 // the "i" in this block is accessible/visible
13 // here and it still hides the outer "i"
14 }
15 // the outermost "i" variable
16 //is accessible/visible here
UNIT-IV
Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine data items of
different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book –
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member. The format of the struct statement is as follows –
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as
inti; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure −
struct Books
{
char title[50];
char author[50];
char subject[100];
intbook _id;
} book;
struct student
{
introll_no;
char name[30];
intphone_number;
};
main()
{
struct student p1, p2, p3;
}
Here, p1, p2 and p3 are the variables of the structure 'student'.
We can also declare structure variables at the time of defining structure as follows.
struct student
{
introll_no;
char name[30];
intphone_number;
}p1, p2, p3;
Now, let's see how to enter the details of each student i.e. roll_no, name and phone number.
Suppose, we want to assign a roll number to the first student. For that, we need to access the roll
number of the first student. We do this by writing
p1.roll_no = 1;
This means that use dot (.) to use variables in a structure. p1.roll_no can be understood as roll_no
of p1.
If we want to assign any string value to a variable, we will use strcpy as follows.
strcpy(p1.name, "Brown");
To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that
we wish to access. You would use the keyword struct to define variables of structure type. The
following example shows how to use a structure in a program −
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
intbook_id;
};
int main( ) {
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
C language supports multiple ways to initialize a structure variable. You can use any of the
initialization method to initialize your structure.
In C, we initialize or access a structure variable either through dot . or arrow -> operator. This is
the most easiest way to initialize or access a structure.
Example:
The above method is easy and straightforward to initialize a structure variable. However, C
language also supports value initialization for structure variable. Means, you can initialize a
structure to some default value during its variable declaration.
Example:
Invalid initialization:
// Declare and initialize structure variable
struct student stu1 = { 12, "Pankaj", 79.5f };
The above code will throw compilation error. Since the order of member type in structure is character
array, integer finally float. But, we aren't initializing the structure variable in the same order.
The above approach may suit all needs. In addition, C language supports flexibility to initialize
structure members in any order. I know this sounds bit confusing. As, just now I said C will
throw error if you try to initialize members in different order of declaration.
This approach is an extension of above. Here, you can specify member name along with the value.
Example:
Example:
#include <stdio.h>
intmain()
{
// Declare structure variable with default initialization
struct student stu1 = NEW_STUDENT;
return 0;
}
Output
Enter student roll no: 12
Enter student marks: 79.5
Student details
Name : Pankaj Prakash
Roll : 12
Marks: 79.50
Two variables of the same structure type can be copied the same way as ordinary variables.If e1
and e2 belong to the same type, then the following statement is valid. e1 = e2, and e2 = e1;
However, the statements that are shown here:e1 < e2; and e1 != e2; are not permitted.C language
doesn't permit any logical operations on structure variables.
We can compare two structure variables but comparison of members of a structure can only be
done individually.
Output:
student2 and student 3 are equal.
In C, the only operation that can be applied to struct variables is assignment. Any other operation
(e.g. equality check) is not allowed on struct variables.
For example, program 1 works without any error and program 2 fails in compilation.
Program 1
#include <stdio.h>
struct Point {
int x;
int y;
};
int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are copied to p2
printf(" p2.x = %d, p2.y = %d", p2.x, p2.y);
getchar();
return 0;
}
Program 2
#include <stdio.h>
struct Point {
int x;
int y;
};
int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are copied to p2
if (p1 == p2) // compiler error: cannot do equality check for
// whole structures
{
printf("p1 and p2 are same ");
}
getchar();
return 0;
}
Arrays Of Structures
Usually, we need a number of records of any kind of structure we declare. Suppose we need a
class record consisting of student’s name, roll number, age for 60 students. It is difficult to declare
60 structure variables.
In order to overcome this difficulty we declare an array structure variables. This implies that we
store the information of 60 students under a same structure variable name but withdifferent
subscript values.
Write a program to compue the monthly pay of 100 employees using each employee’s name, basic
pay, DA is computed as 52% of basic salary.
01 #include<stdio.h>
02 #include<conio.h>
03 void main()
04 {
05 struct employee
06 {
07 char ename[20];
08 int bp;
09 float da;
10 float gs;
11 }emp[100];
12 int i;
13 for(i=0;i<100;i++)
14 {
15 printf("\n Enter Emp name:");
16 gets(emp[i].ename);
17 printf("\n Enter Emp Basic pay:");
18 scanf("%d",&emp[i].bp);
19 emp[i].da= 0.52*emp[i].bp;
20 emp[i].gs= emp[i].bp+emp[i].da;
21 }
22 clrscr();
23 for(i=0;i<100;i++)
24 {
25 printf("\n Emp Name : %s",emp[i].ename);
26 printf("\n Emp Basic pay : %d",emp[i].bp);
27 printf("\n Emp DA : %f",emp[i].da);
28 printf("\n Emp GS : %f",emp[i].gs);
29 }
30 getch();
31 }
Below is the demonstration of a program that uses the concept of the array within a structure. The program
displays the record of a student comprising the roll number, grade, and marks secured in various subjects.
The marks in various subjects have been stored under an array called marks. The whole record is stored
under a structure called a candidate.
Nested structure in C is nothing but structure within structure. One structure can be declared inside
other structure as we declare structure members inside a structure.
The structure variables can be a normal structure variable or a pointer variable to access the data.
You can learn below concepts in this section.
#include <stdio.h>
#include <string.h>
structstudent_college_detail
{
intcollege_id;
char college_name[50];
};
structstudent_detail
{
int id;
char name[20];
float percentage;
// structure within structure
structstudent_college_detailclg_data;
}stu_data;
int main()
{
structstudent_detailstu_data = {1, "Raju", 90.5, 71145,
"Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Anna University
This program explains how to use structure within structure in C using pointer variable.
“student_college_detail’ structure is declared inside “student_detail” structure in this program. one
normal structure variable and one pointer structure variable is used in this program.
Please note that combination of .(dot) and ->(arrow) operators are used to access the structure
member which is declared inside the structure.
#include <stdio.h>
#include <string.h>
structstudent_college_detail
{
intcollege_id;
char college_name[50];
};
structstudent_detail
{
int id;
char name[20];
float percentage;
// structure within structure
structstudent_college_detailclg_data;
}stu_data, *stu_data_ptr;
int main()
{
structstudent_detailstu_data = {1, "Raju", 90.5, 71145,
"Anna University"};
stu_data_ptr = &stu_data;
return 0;
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Anna University
Like all other types, we can pass structures as arguments to a function. In fact, we can pass,
individual members, structure variables, a pointer to structures etc to the function. Similarly,
functions can return either an individual member or structures variable or pointer to the structure.
We can pass individual members to a function just like ordinary variables.The following program
demonstrates how to pass structure members as arguments to the function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
*/
5
6 struct student
7{
8 char name[20];
9 introll_no;
10int marks;
11};
12
voidprint_struct(char name[], introll_no, int marks);
13
14intmain()
15{
16struct student stu= {"Tim", 1, 78};
17print_struct(stu.name, stu.roll_no, stu.marks);
18return0;
19}
20
21voidprint_struct(char name[], introll_no, int marks)
22{
23printf("Name: %s\n", name);
printf("Roll no: %d\n", roll_no);
24 printf("Marks: %d\n", marks);
25 printf("\n");
26}
27
28
29
Expected Output:
1Name: Tim
2Roll no: 1
3Marks: 78
How it works:
1. In the main function add the following line after the call to print_struct() function.
1 #include<stdio.h>
2 #include<string.h>
3
4 /*
5 structure is defined above all functions so it is global.
6 */
7
8 struct student
9{
10char name[20];
11introll_no;
12int marks;
13};
14
15voidprint_struct(char name[], introll_no, int marks);
16
17intmain()
18{
19struct student stu= {"Tim", 1, 78};
20print_struct(stu.name, stu.roll_no, stu.marks);
21
22printf("New name: %s", stu.name);
23
24return0;
25}
26
27voidprint_struct(char name[], introll_no, int marks)
28{
29printf("Name: %s\n", name);
30printf("Roll no: %d\n", roll_no);
31printf("Marks: %d\n", marks);
32
33printf("\nChanging name ... \n");
34strcpy(name, "Jack");
35
36printf("\n");
37}
Expected Output:
1Name: Tim
2Roll no: 1
3Marks: 78
4
5Changing name ...
6
7New name: Jack
This verifies the fact that changes made by print_struct() function affect the original array.
The following program demonstrates how we can pass structure variable as an argument to the
function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
5 */
6
7 struct student
8{
9 char name[20];
10introll_no;
11int marks;
12};
13
14voidprint_struct(struct student stu);
15
16intmain()
17{
18struct student stu= {"George", 10, 69};
19print_struct(stu);
20return0;
21}
22
23voidprint_struct(struct student stu)
24{
25printf("Name: %s\n", stu.name);
26printf("Roll no: %d\n", stu.roll_no);
27printf("Marks: %d\n", stu.marks);
28printf("\n");
29}
Expected Output:
1Name: George
2Roll no: 10
3Marks: 69
How it works:
Although passing structure variable as an argument allows us to pass all the members of the
structure to a function there are some downsides to this operation.
1. Recall that a copy of the structure is passed to the formal argument. If the structure is large and you are
passing structure variables frequently then it can take quite a bit of time which make the program
inefficient.
2. Additional memory is required to save every copy of the structure.
The following program demonstrates how to pass structure pointers as arguments to a function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
5 */
6
7 struct employee
8{
9 char name[20];
10int age;
11chardoj[10]; // date of joining
12char designation[20];
13};
14
15voidprint_struct(struct employee *);
16
17intmain()
18{
19struct employee dev = {"Jane", 25, "25/2/2015", "Developer"};
20print_struct(&dev);
21
22return0;
23}
24
25voidprint_struct(struct employee *ptr)
26{
27printf("Name: %s\n", ptr->name);
28printf("Age: %d\n", ptr->age);
29printf("Date of joining: %s\n", ptr->doj);
30printf("Age: %s\n", ptr->designation);
31printf("\n");
32}
Expected Output:
1Name: Jin
2Age: 25
3Date of joining: 25/2/2015
4Age: Developer
How it works:
In lines 7-13, a structure employee is declared with four members namely name, age, doj(date of
joining) and designation.
In line 15, the prototype of function print_struct() is declared which accepts an argument of type
pointer to struct student.
In line 19, a structure variable dev of type struct employee is declared and initialized.
In line 20, print_struct() is called along with along with the address of variable dev. The formal
argument of print_struct() is assigned the address of variable dev. Now ptr is pointing to the
original structure, hence any changes made inside the function will affect the original structure.
The printf() statements from lines 27-30 prints the details of the developer.
The downside of passing structure pointer to a function is that the function can modify the
original structure. If that is what you intentionally want that's fine. However, if don't want
functions to modify original structure use the const keyword. Recall that const keyword when
applied to a variable makes it read-only.
Let's rewrite the previous program using const keyword.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
5 */
6
7 struct employee
8{
9 char name[20];
10int age;
11chardoj[10]; // date of joining
12char designation[20];
13};
14
15voidprint_struct(conststruct employee *);
16
17intmain()
18{
19struct employee dev = {"Jane", 25, "25/2/2015", "Developer"};
20print_struct(&dev);
21
22return0;
23}
24
25voidprint_struct(conststruct employee *ptr)
26{
27printf("Name: %s\n", ptr->name);
28printf("Age: %d\n", ptr->age);
29printf("Date of joining: %s\n", ptr->doj);
30printf("Age: %s\n", ptr->designation);
31
32//ptr->age = 11;
33
34printf("\n");
35}
Now even though we are passing a structure pointer to print_struct() function, any attempt to
modify the values of the structure will result in compilation error. Try commenting out code in
line 32 and see it yourself.
Unions
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain
a value at any given time. Unions provide an efficient way of using the same memory location
for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows –
union[union tag]{
member definition;
member definition;
...
member definition;
}[one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as
inti; or float f; or any other valid variable definition. At the end of the union's definition, before
the final semicolon, you can specify one or more union variables but it is optional. Here is the
way you would define a union type named Data having three members i, f, and str −
Union Data
{
inti;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union –
#include<stdio.h>
#include<string.h>
unionData{
inti;
float f;
charstr[20];
};
int main(){
unionDatadata;
return0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access. You would use the keyword union to define variables of union type. The
following example shows how to use unions in a program −
#include<stdio.h>
#include<string.h>
unionData{
inti;
float f;
charstr[20];
};
int main(){
unionDatadata;
data.i=10;
data.f=220.5;
strcpy(data.str,"C Programming");
printf("data.i : %d\n",data.i);
printf("data.f : %f\n",data.f);
printf("data.str : %s\n",data.str);
return0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the
value of str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which
is the main purpose of having unions −
#include<stdio.h>
#include<string.h>
unionData{
inti;
float f;
charstr[20];
};
int main(){
unionDatadata;
data.i=10;
printf("data.i : %d\n",data.i);
data.f=220.5;
printf("data.f : %f\n",data.f);
strcpy(data.str,"C Programming");
printf("data.str : %s\n",data.str);
return0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.
Size of structures
sizeof operator in C
The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is
because of the padding added by the compiler to avoid alignment issues. Padding is only added
when a structure member is followed by a member with a larger size or at the end of the structure.
Different compilers might have different alignment constraints as C standards state that alignment
of structure totally depends on the implementation.
Let’s take a look at the following examples for better understanding:
Case 1:
filter_none
edit
play_arrow
brightness_4
// C program to illustrate
// size of struct
#include <stdio.h>
int main()
{
struct A {
// sizeof(int) = 4
int x;
// Padding of 4 bytes
// sizeof(double) = 8
double z;
// sizeof(short int) = 2
short int y;
// Padding of 6 bytes
};
return 0;
}
Output:
Size of struct: 24
The red portion represents the padding added for data alignment and the green portion represents
the struct members. In this case, x (int) is followed by z (double), which is larger in size as
compared to x. Hence padding is added after x. Also, padding is needed at the end for data
alignment.
Case 2:
filter_none
edit
play_arrow
brightness_4
// C program to illustrate
// size of struct
#include <stdio.h>
int main()
{
struct B {
// sizeof(double) = 8
double z;
// sizeof(int) = 4
int x;
// sizeof(short int) = 2
short int y;
// Padding of 2 bytes
};
return 0;
}
Output:
Size of struct: 16
In this case, the members of the structure are sorted in decreasing order of their sizes. Hence padding
is required only at the end.
Case 3:
filter_none
edit
play_arrow
brightness_4
// C program to illustrate
// size of struct
#include <stdio.h>
int main()
{
struct C {
// sizeof(double) = 8
double z;
// sizeof(short int) = 2
short int y;
// Padding of 2 bytes
// sizeof(int) = 4
int x;
};
printf("Size of struct: %ld", sizeof(struct C));
return 0;
}
Output:
Size of struct: 16
Bit Fields
Bit Fields allow the packing of data in a structure. This is especially useful when memory or data
storage is at a premium. Typical examples include −
Packing several objects into a machine word. e.g. 1 bit flags can be compacted.
Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers.
C allows us to do this in a structure definition by putting :bit length after the variable. For example −
structpacked_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and a 9-bit
my_int.
C automatically packs the above bit fields as compactly as possible, provided that the maximum
length of the field is less than or equal to the integer word length of the computer. If this is not
the case, then some compilers may allow memory overlap for the fields while others would store
the next field in the next word.
Pointers
UNIT-V
POINTER
This variable can be of type int, char, array, function, or any other
pointer.
int n = 10;
A program being executed by a processor has two major parts - the code
and the data.
The code section is the code you've written and the data section holds
the variables you're using in the program.
All code and variables are loaded into memory (usually RAM) and the
processor executes the code from there.
When the program will run the processor will save these two numbers
in two different memory locations.
Adding these numbers can be achieved by adding the contents of two
different memory locations.
Example:1
#include <stdio.h>
int main()
{
int a = 55;
return 0;
}
Output:
Example 2
#include <stdio.h>
void f(int p)
{
printf("The address of p inside f() is %p\n", &p);
}
void g(int r)
{
printf("The address of r inside g() is %p\n", &r);
f(r);
}
int main()
{
int a = 55;
return 0;
}
Output
Syntax
Example
#include<stdio.h>
int main(){
int number=50;
int *p;
return 0;
Output
Value of p variable is 50
variableSteps:
#include <stdio.h>
int main(void)
//normal variable
//pointer variable
int *ptr;
//pointer initialization
ptr = #
return 0;
Output
The declaration ‘int **ptr2’ tells the compiler that ‘ptr2’ is a pointer
to a pointer of int type. Remember, the pointer ‘ptr2’ is not a
pointer to an integer, but rather a pointer to an integer pointer.
Example Program
#include <stdio.h>
// C program for chain of pointer
int main()
{
int var = 10;
// Pointer level-1
// Declaring pointer to variable var
int* ptr1;
// Pointer level-2
// Declaring pointer to pointer variable *ptr1
int** ptr2;
// Pointer level-3
// Declaring pointer to double pointer **ptr2
int*** ptr3;
// Displaying values
printf("Value of variable "
"var = %d\n",
var);
printf("Value of variable var using"
" pointer ptr1 = %d\n",
*ptr1);
printf("Value of variable var using"
" pointer ptr2 = %d\n",
**ptr2);
printf("Value of variable var using"
" pointer ptr3 = %d\n",
***ptr3);
return 0;
}
Output:
p1=p1+1;
Will cause the pointer p1 to point to the next value of its type. For
ex. If p1 is an integer pointer with an initial value, say 2800, then
after with an initial value, the value of p1 will be 2902, & not 2801.
Character 1 byte
Integers 2 bytes
Floats 4 bytes
Double 8 bytes
#include <stdio.h>
int main()
printf("After Swapping:\n\n");
return 0;
/*
*/
int temp;
temp = *a;
*a = *b;
*b = temp;
m = 10
n = 20
After Swapping:
m = 20
n = 10
Pointer To Strings
Example
#include <stdio.h>
int main()
int i;
for(i = 0; i < 2; i++)
printf("%s\n", cities[i]);
return 0;
Output
Iran
Iraq
Syntax:
struct name {
member1;
member2;
};
int main()
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
personPtr = &person1;
scanf("%d", &personPtr->age);
scanf("%f", &personPtr->weight);
printf("Displaying:\n");
return 0;