C First Semester Notes-1

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

Module 1

Introduction To C
The C Character Set
A character set in C Programming Language is set all valid characters that can be used to form words, numbers
and expression’s in source programs. The source character set is consist of the characters used for the source
program text, while the execution character set is the set of characters used during the execution of the
program. It is not necessary that source character set match and execution character set are same.

There are four types of Character Set:-


Character Set

Uppercase A-Z
1. Letters
Lowercase a-z

2. Digits All digits 0-9

Special All Symbols: , . : ; ? ' " ! | \ / ~ _$ % #


3.
Characters &^*-+<>(){ }[]

Blank space, Horizintal tab, Carriage


4. White Spaces
return, New line, Form feed

Identifiers
An identifier is used for any variable, function, data definition, labels in your program etc.
Before starting any language, you must at least know how you name an identifier.
In C language, an identifier is a combination of alphanumeric characters, i.e. first begin with a
letter of the alphabet or an underline, and the remaining are letter of an alphabet, any numeric digit,
or the underline.

Rules for naming identifiers


The rules that must be followed while naming the identifiers are as follows −
• The case of alphabetic characters is significant. For example, using "TUTORIAL" for a
variable is not the same as using "tutorial" and neither of them is the same as using
"TutoRial for a variable. All three refer to different variables.
• There is no rule on how long an identifier can be. We can run into problems in some
compilers, if an identifier is longer than 31 characters. This is different for the different
compilers.
• A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
• The first letter of an identifier should be either a letter or an underscore.
• You cannot use keywords like int, while etc. as identifiers.
Identifiers must be unique
For example,

int student;
float marks;

Here, student and marks are identifiers.


We have to remember that the identifier names must be different from keywords. We cannot use
int as an identifier, because int is a keyword.
Consider another example for identifier.

int var1, var2;


float Avg;
function sum();
Here,
• int, float, function are all keywords.
• var1, var2, Sum, Avg, are the identifiers.
Keywords are used along with identifiers to define them. Keywords explain the functionality of
the identifiers to the compiler.

Keywords
Keywords are predefined, reserved words in C language and each of which is associated with
specific features. These words help us to use the functionality of C language. They have special
meaning to the compilers.
There are total 32 keywords in C.

auto double int struct


break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

Here is an example of keywords in C language,

Example

#include <stdio.h>

int main() {

// char, int and float are keywords and used as datatypes

char c = 'H';

int b = 6, c;

float _d = 7.6;

// if and else is a keyword checking the value of b

if(b<5)

printf("Character Value : %c",a1);

else

printf("Float value : %f",_d);

return 0;
}

Output
Float value : 7.600000

Data Types
Data types in c refer to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted.
The types in C can be classified as follows −

Sr.No. Types & Description

1
Basic Types
They are arithmetic types and are
further classified into: (a) integer types
and (b) floating-point types.

2
Enumerated types
They are again arithmetic types and they
are used to define variables that can only
assign certain discrete integer values
throughout the program.

3
The type void
The type specifier void indicates that no
value is available.

4
Derived types
They include (a) Pointer types, (b)
Array types, (c) Structure types, (d)
Union types and (e) Function types.

The array types and structure types are referred collectively as the aggregate types. The type of a
function specifies the type of the function's return value. We will see the basic types in the
following section, where as other types will be covered in the upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage sizes and
value ranges −

Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned 1 byte 0 to 255


char

signed 1 byte -128 to 127


char

-32,768 to 32,767 or -
int 2 or 4 bytes 2,147,483,648 to
2,147,483,647

unsigned 2 or 4 bytes 0 to 65,535 or 0 to


int 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned 2 bytes 0 to 65,535


short

long 8 bytes or -9223372036854775808


(4bytes for 32 to
bit OS) 9223372036854775807

unsigned 8 bytes 0 to
long 18446744073709551615

To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in
bytes. Given below is an example to get the size of various type on a machine using different
constant defined in limits.h header file −
Live Demo

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>

int main(int argc, char** argv) {

printf("CHAR_BIT : %d\n", CHAR_BIT);


printf("CHAR_MAX : %d\n", CHAR_MAX);
printf("CHAR_MIN : %d\n", CHAR_MIN);
printf("INT_MAX : %d\n", INT_MAX);
printf("INT_MIN : %d\n", INT_MIN);
printf("LONG_MAX : %ld\n", (long) LONG_MAX);
printf("LONG_MIN : %ld\n", (long) LONG_MIN);
printf("SCHAR_MAX : %d\n", SCHAR_MAX);
printf("SCHAR_MIN : %d\n", SCHAR_MIN);
printf("SHRT_MAX : %d\n", SHRT_MAX);
printf("SHRT_MIN : %d\n", SHRT_MIN);
printf("UCHAR_MAX : %d\n", UCHAR_MAX);
printf("UINT_MAX : %u\n", (unsigned int) UINT_MAX);
printf("ULONG_MAX : %lu\n", (unsigned long) ULONG_MAX);
printf("USHRT_MAX : %d\n", (unsigned short) USHRT_MAX);

return 0;
}
When you compile and execute the above program, it produces the following result on Linux −
CHAR_BIT : 8
CHAR_MAX : 127
CHAR_MIN : -128
INT_MAX : 2147483647
INT_MIN : -2147483648
LONG_MAX : 9223372036854775807
LONG_MIN : -9223372036854775808
SCHAR_MAX : 127
SCHAR_MIN : -128
SHRT_MAX : 32767
SHRT_MIN : -32768
UCHAR_MAX : 255
UINT_MAX : 4294967295
ULONG_MAX : 18446744073709551615
USHRT_MAX : 65535
Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes and
value ranges and their precision −

Type Storage Value range Precision


size

float 4 byte 1.2E-38 to 6 decimal


3.4E+38 places

double 8 byte 2.3E-308 to 15 decimal


1.7E+308 places

long 10 byte 3.4E-4932 to 19 decimal


double 1.1E+4932 places

The header file float.h defines macros that allow you to use these values and other details about
the binary representation of real numbers in your programs. The following example prints the
storage space taken by a float type and its range values −
Live Demo

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>

int main(int argc, char** argv) {

printf("Storage size for float : %d \n", sizeof(float));


printf("FLT_MAX : %g\n", (float) FLT_MAX);
printf("FLT_MIN : %g\n", (float) FLT_MIN);
printf("-FLT_MAX : %g\n", (float) -FLT_MAX);
printf("-FLT_MIN : %g\n", (float) -FLT_MIN);
printf("DBL_MAX : %g\n", (double) DBL_MAX);
printf("DBL_MIN : %g\n", (double) DBL_MIN);
printf("-DBL_MAX : %g\n", (double) -DBL_MAX);
printf("Precision value: %d\n", FLT_DIG );

return 0;
}
When you compile and execute the above program, it produces the following result on Linux −
Storage size for float : 4
FLT_MAX : 3.40282e+38
FLT_MIN : 1.17549e-38
-FLT_MAX : -3.40282e+38
-FLT_MIN : -1.17549e-38
DBL_MAX : 1.79769e+308
DBL_MIN : 2.22507e-308
-DBL_MAX : -1.79769e+308
Precision value: 6
The void Type
The void type specifies that no value is available. It is used in three kinds of situations −

Sr.No. Types & Description

1
Function returns as void
There are various functions in C which
do not return any value or you can say
they return void. A function with no
return value has the return type as void.
For example, void exit (int status);

2
Function arguments as void
There are various functions in C which
do not accept any parameter. A function
with no parameter can accept a void. For
example, int rand(void);

3
Pointers to void
A pointer of type void * represents the
address of an object, but not its type. For
example, a memory allocation
function void *malloc( size_t size
); returns a pointer to void which can be
casted to any data type.

Constants
Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified after
their definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or
radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals −
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.
You can represent floating point literals either in decimal form or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or both; and
while representing exponential form, you must include the integer part, the fractional part, or
both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable
of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded by a backslash
for example, newline (\n) or tab (\t).
• Here, you have a list of such escape sequence codes −

Following is the example to show a few escape sequence characters −


Live Demo

#include <stdio.h>

int main() {
printf("Hello\tWorld\n\n");

return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that are
similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using white
spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"

"hello, \
dear"

"hello, " "d" "ear"


Defining Constants
There are two simple ways in C to define constants −
• Using #define preprocessor.
• Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −
#define identifier value
The following example explains it in detail −
Live Demo

#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main() {
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
Live Demo

#include <stdio.h>

int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.

Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −

Sr.No. Type & Description

1
char
Typically a single octet(one byte). It is
an integer type.

2
int
The most natural size of integer for the
machine.

3
float
A single-precision floating point value.
4
double
A double-precision floating point value.

5
void
Represents the absence of type.

C programming language also allows to define various other types of variables, which we will
cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this
chapter, let us study only basic variable types.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type
as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists
of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized
with NULL (all bytes have the value 0); the initial value of all other variables are undefined.
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the
given type and name so that the compiler can proceed for further compilation without requiring
the complete detail about the variable. A variable definition has its meaning at the time of
compilation only, the compiler needs actual variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define your variable in
one of the files which will be available at the time of linking of the program. You will use the
keyword extern to declare a variable at any place. Though you can declare a variable multiple
times in your C program, it can be defined only once in a file, a function, or a block of code.
Example
Try the following example, where variables have been declared at the top, but they have been
defined and initialized inside the main function −
Live Demo

#include <stdio.h>

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {

/* variable definition: */
int a, b;
int c;
float f;

/* actual initialization */
a = 10;
b = 20;

c = a + b;
printf("value of c : %d \n", c);

f = 70.0/3.0;
printf("value of f : %f \n", f);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of c : 30
value of f : 23.333334
The same concept applies on function declaration where you provide a function name at the time
of its declaration and its actual definition can be given anywhere else. For example −
// function declaration
int func();

int main() {

// function call
int i = func();
}

// function definition
int func() {
return 0;
}
Lvalues and Rvalues in C
There are two kinds of expressions in C −
• lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An
lvalue may appear as either the left-hand or right-hand side of an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some address in memory.
An rvalue is an expression that cannot have a value assigned to it which means an rvalue
may appear on the right-hand side but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take
a look at the following valid and invalid statements −
int g = 20; // valid statement

10 = 20; // invalid statement; would generate compile-time error

Declarations
In C programming, variables which are to be used later in different parts of the
functions have to be declared. Variable declaration tells the compiler two things:


The name of the variable
• The type of data the variable will hold
There are two ways of declaring variable in C programming.

1. Primary Type Declaration


2. User Defined Type Declaration
Primary Type Declaration
A variable can store any data type in C programming. The name of the variable has
nothing to do with its type. The general syntax of declaring a variable primarily is

data_type var1,var2,...varn;

Here, var1, var2,…varn are the names of valid variables.

Variables can also be defined in multiple lines instead of on the same line.

data_type var1;

data_type var2;

data_type varn;

When the variables are declared in single line, then the variables must be separated by
commas.

Note: All declaration statements must end with a semi-colon(;).

For example:

int age;

float weight;

char gender;

In these examples, age, weight and gender are variables which are declared as integer
data type, floating data type and character data type respectively.

User-Defined Type Declaration


In C programming, a feature known as “type definition” is available which allows a
programmer to define an identifier that represents an existing data type. The user
defined identifier can be used later in the program to declare variables. The general
syntax of declaring a variable by user-defined type declaration is:
typedef type identifier;

Here, type is an existing data type and identifier is the “new name” given to the data
type. Here, the new type is ‘new’ only in name but not the data type.

Note: typedef cannot create a new type

Consider an example:

typedef int age;

typedef float weight;

Here, age represents int and weight represent float which can be used later in the
program to declare variables as follows:

age boy1,boy2;

weight b1,b2;

Here, boy1 and boy2 are declared as as integer data type and b1 & b2 are declared as
floating integer data type.

The main advantage of using user-defined type declaration is that we can create
meaningful data type names for increasing the readability of a program.

Another user-defined data type is enumerated data type. The general syntax of
enumerated data type is:

enum identifier {value 1,value 2,...value n};

Here, identifier is a user-defined enumerated data type which can be used to declare
variables that can have one of the values enclosed within the braces. The values inside
the braces are known as enumeration constants. After this declaration, we can declare
variables to be of this ‘new’ type as:

enum identifier v1, v2, ... vn;

The enumerated variables v1, v2, … vn can only have one of the values value1,
value2, … valuen. The following kinds of declarations are valid:
v1=value5;

v3=value1;

User-defined Type Declaration Example


enum mnth {January, February, ..., December};

enum mnth day_st, day_end;

day_st = January;

day_end = December;

if (day_st == February)

day_end = November;

The compiler automatically assigns integer digits begriming with 0 to all the
enumeration constants. That is, the enumeration constant value1 is assigned
0, value2 is assigned 1, and so on. However, the automatic assignments can be
overridden by assigning values explicitly to thee enumeration constants.

For example:

enum mnth {January = 1, February, ..., December};

Here, the constant January is assigned value 1. The remaining values are assigned
values that increase successively by 1.

The definition and declaration of enumerated variables can be combined in one


statement. For example;

enum mnth {January, ... December} day_st, day_end;

Expressions

An expression is a combination of operators and operands which reduces to a single value. An


operation is performed on a data item which is called an operand. An operator indicates an
operation to be performed on data.
For example, z = 3+2*1
z=5

• Primary expressions − It is an operand which can be a name, a constant or any


parenthesized expression. Example − c = a+ (5*b);
• Postfix expressions − In a postfix expression, the operator will be after the operand.
Example − ab+
• Prefix expressions − n a prefix expression, the operator is before the operand. Example −
+ab
• Unary expression − It contains one operator and one operand. Example − a++, --b
• Binary expression − t contains two operands and one operator. Example − a+b, c-d
• Ternary expression − It contains three operands and one operator. For Example, Exp1?
Exp2 − Exp3. If Exp1 is true, Exp2 is executed. Otherwise, Exp3 is executed.

Example
Given below is the C program explaining the different types of expressions in C language −

Live Demo

#include<stdio.h>

int main(){

int a,b,c,d,z;

int p,q,r,s,t,u,v;

printf("enter the values of a,b,c,d:\n");

scanf("%d%d%d%d",&a,&b,&c,&d);

r=a++;

s=--b;

t=a+b;
u=c-d;

v=a+(5*b);

z = (5>3) ? 1:0;

printf("unaryexpression=%d\nunary expression=%d\n Binary

expression=%d\nBinary expression=%d\nPrimary expression=%d\nTernary


expression=%d\n",r,s,t,u,v,z);

Output
You will see the following output −

enter the values of a,b,c,d:


2346
unary expression=2
unary expression=2
Binary expression=5
Binary expression=-2
Primary expression=13
Ternary expression=1

Statements

C programs are collection of Statements, statements is an executable part of the program it will do
some action. In general all arithmetic actions and logical actions are falls under Statements Categories
anyway there are few Statement categories
▪ Expression Statements.
▪ Compound Statements.
▪ Selection Statements.
▪ Iterative Statements.
▪ Jump Statements.
Expression Statements:
It is combination of variables,Constants,operators,Function Calls and followed by a
semicolon. Expression can be any operation like Arithmetic operation or Logical Operation.
Few Examples for expression Statements
X = Y + 10 ;
20 > 90;
a?b:c;
a = 10 + 20 * 30;
; (This is NULL Statement ).

Compound Statement :
Compound statement is combination of several expression statements. Compound Statement
is Enclosed within the Braces { }.
Compound statement is also called as Block Statement.

There is no need of any semicolon at the end of Compound Statement.


Example for Compound Statement

{
int a=10,b=20,c;
c = a + b;
printf(“value of C is : %d n”,c);
}

You May like : Swapping The Nibbles of Character.


Selection Statements :
Selection Statements are used in decisions making situations we will look about
selections statements in Later Tutorials. Here is the few examples of Selection statements
▪ if
▪ if…else
▪ switch
Iterative Statements :
These are also Called as Loops. If we want to Execute a part of program many times we
will use loops.We will going to explain each and Every loop in Detail in Later Tutorials. Here is
the List of Basic loops in C language.

▪ for loop.
▪ while loop.
▪ do-while loop.
Jump Statements :
These are Unconditional statements Jump statements are useful for Transfer the Control
one part of program to other part of Program there are few Jump Statements in C
▪ goto.
▪ continue.
▪ break.
▪ return.
All these Selection and Iterative and Jump Statements are Keywords and all are Lower
Case Characters.
Data Input and Output
Single Character Input
getchar() is used to get or read the input (i.e a single character) at run time.

Declaration:

int getchar(void);

Example Declaration:

char ch;
ch = getchar();

Return Value:
This function return the character read from the keyboard.

Example Program:

/* Example Program For Single Character Input Function : getchar() In C Programming Language
little drops @ thiyagaraaj.com
Coded By:THIYAGARAAJ MP */

// Header Files
#include<stdio.h>
#include<conio.h>

//Main Function
void main()
{
char ch;
ch = getchar();
printf("Input Char Is :%c",ch);
}

Single Character Output


• putchar() displays any alphanumeric characters to the standard output device.

• It displays only one character at a time.

Declaration:

int putch(variable_name);

putchar Example Declaration:

char ch = 'a';
putchar(ch);

Remarks:

• putchar displays one character at a time to the Monitor.

putchar Example Program:

/* Example Program For Single Character OutputFunction : putchar() In C Programming Language


little drops @ thiyagaraaj.com
Coded By:THIYAGARAAJ MP */

// Header Files
#include<stdio.h>
#include<conio.h>

//Main Function
void main()
{
char ch='a';
putchar(ch);

getch();
}
Sample Output

Scanf
The C library function int scanf(const char *format, ...) reads formatted input from stdin.
Declaration
Following is the declaration for scanf() function.
int scanf(const char *format, ...)
Parameters
• format − This is the C string that contains one or more of the following items −
Whitespace character, Non-whitespace character and Format specifiers. A format
specifier will be like [=%[*][width][modifiers]type=] as explained below −

Sr.No. Argument & Description

1
*
This is an optional starting asterisk
indicates that the data is to be read from
the stream but ignored, i.e. it is not
stored in the corresponding argument.

2
width
This specifies the maximum number of
characters to be read in the current
reading operation.

3
modifiers
Specifies a size different from int (in the
case of d, i and n), unsigned int (in the
case of o, u and x) or float (in the case
of e, f and g) for the data pointed by the
corresponding additional argument: h :
short int (for d, i and n), or unsigned
short int (for o, u and x) l : long int (for
d, i and n), or unsigned long int (for o, u
and x), or double (for e, f and g) L : long
double (for e, f and g)

4
type
A character specifying the type of data
to be read and how it is expected to be
read. See next table.

fscanf type specifiers


type Qualifying Input Type of
argument

c Single character: Reads the next char *


character. If a width different
from 1 is specified, the function
reads width characters and
stores them in the successive
locations of the array passed as
argument. No null character is
appended at the end.

d Decimal integer: Number int *


optionally preceded with a + or
- sign

e, E, Floating point: Decimal number float *


f, g, containing a decimal point,
G optionally preceded by a + or -
sign and optionally followed by
the e or E character and a
decimal number. Two examples
of valid entries are -732.103
and 7.12e4

o Octal Integer: int *


s String of characters. This will char *
read subsequent characters until
a whitespace is found
(whitespace characters are
considered to be blank, newline
and tab).

u Unsigned decimal integer. unsigned


int *

x, X Hexadecimal Integer int *

• additional arguments − Depending on the format string, the function may expect a
sequence of additional arguments, each containing one value to be inserted instead of each
%-tag specified in the format parameter, if any. There should be the same number of these
arguments as the number of %-tags that expect a value.
Return Value
On success, the function returns the number of items of the argument list successfully read. If a
reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof
or ferror) and, if either happens before any data could be successfully read, EOF is returned.
Example
The following example shows the usage of scanf() function.
#include <stdio.h>

int main () {
char str1[20], str2[30];

printf("Enter name: ");


scanf("%s", str1);

printf("Enter your website name: ");


scanf("%s", str2);

printf("Entered Name: %s\n", str1);


printf("Entered Website:%s", str2);

return(0);
}

Printf
The C library function int printf(const char *format, ...) sends formatted output to stdout.
Declaration
Following is the declaration for printf() function.
int printf(const char *format, ...)
Parameters
• format − This is the string that contains the text to be written to stdout. It can optionally
contain embedded format tags that are replaced by the values specified in subsequent
additional arguments and formatted as requested. Format tags prototype
is %[flags][width][.precision][length]specifier, which is explained below −

Sr.No. Specifier & Output

1
c
Character

2
d or i
Signed decimal integer

3
e
Scientific notation (mantissa/exponent)
using e character

4
E
Scientific notation (mantissa/exponent)
using E character

5
f
Decimal floating point

6
g
Uses the shorter of %e or %f

7
G
Uses the shorter of %E or %f

8
o
Signed octal

9
s
String of characters

10
u
Unsigned decimal integer

11
x
Unsigned hexadecimal integer

12
X
Unsigned hexadecimal integer (capital
letters)

13
p
Pointer address

14
n
Nothing printed

15
%
Character

Sr.No. Flags & Description

1
-
Left-justify within the given field width;
Right justification is the default (see
width sub-specifier).

2
+
Forces to precede the result with a plus
or minus sign (+ or -) even for positive
numbers. By default, only negative
numbers are preceded with a -ve sign.

3
(space)
If no sign is going to be written, a blank
space is inserted before the value.

4
#
Used with o, x or X specifiers the value
is preceded with 0, 0x or 0X
respectively for values different than
zero. Used with e, E and f, it forces the
written output to contain a decimal point
even if no digits would follow. By
default, if no digits follow, no decimal
point is written. Used with g or G the
result is the same as with e or E but
trailing zeros are not removed.

5
0
Left-pads the number with zeroes (0)
instead of spaces, where padding is
specified (see width sub-specifier).

Sr.No. Width & Description

1
(number)
Minimum number of characters to be
printed. If the value to be printed is
shorter than this number, the result is
padded with blank spaces. The value is
not truncated even if the result is larger.

2
*
The width is not specified in the format
string, but as an additional integer value
argument preceding the argument that
has to be formatted.

Sr.No. .precision & Description

1
.number
For integer specifiers (d, i, o, u, x, X) −
precision specifies the minimum
number of digits to be written. If the
value to be written is shorter than this
number, the result is padded with
leading zeros. The value is not truncated
even if the result is longer. A precision
of 0 means that no character is written
for the value 0. For e, E and f specifiers
− this is the number of digits to be
printed after the decimal point. For g
and G specifiers − This is the maximum
number of significant digits to be
printed. For s − this is the maximum
number of characters to be printed. By
default all characters are printed until
the ending null character is encountered.
For c type − it has no effect. When no
precision is specified, the default is 1. If
the period is specified without an
explicit value for precision, 0 is
assumed.

2
.*
The precision is not specified in the
format string, but as an additional
integer value argument preceding the
argument that has to be formatted.
Sr.No. Length & Description

1
h
The argument is interpreted as a short
int or unsigned short int (only applies to
integer specifiers: i, d, o, u, x and X).

2
l
The argument is interpreted as a long int
or unsigned long int for integer
specifiers (i, d, o, u, x and X), and as a
wide character or wide character string
for specifiers c and s.

3
L
The argument is interpreted as a long
double (only applies to floating point
specifiers: e, E, f, g and G).

• additional arguments − Depending on the format string, the function may expect a
sequence of additional arguments, each containing one value to be inserted instead of each
%-tag specified in the format parameter (if any). There should be the same number of
these arguments as the number of %-tags that expect a value.
Return Value
If successful, the total number of characters written is returned. On failure, a negative number is
returned.
Example
The following example shows the usage of printf() function.
Live Demo

#include <stdio.h>

int main () {
int ch;

for( ch = 75 ; ch <= 100; ch++ ) {


printf("ASCII value = %d, Character = %c\n", ch , ch );
}
return(0);
}
Let us compile and run the above program to produce the following result −
ASCII value = 75, Character = K
ASCII value = 76, Character = L
ASCII value = 77, Character = M
ASCII value = 78, Character = N
ASCII value = 79, Character = O
ASCII value = 80, Character = P
ASCII value = 81, Character = Q
ASCII value = 82, Character = R
ASCII value = 83, Character = S
ASCII value = 84, Character = T
ASCII value = 85, Character = U
ASCII value = 86, Character = V
ASCII value = 87, Character = W
ASCII value = 88, Character = X
ASCII value = 89, Character = Y
ASCII value = 90, Character = Z
ASCII value = 91, Character = [
ASCII value = 92, Character = \
ASCII value = 93, Character = ]
ASCII value = 94, Character = ^
ASCII value = 95, Character = _
ASCII value = 96, Character = `
ASCII value = 97, Character = a
ASCII value = 98, Character = b
ASCII value = 99, Character = c
ASCII value = 100, Character = d
MODULE : 2
DECISION MAKING STATEMENT

We have a number of situations where we may have to change the order


of execution of statements based on certain conditions, or repeat a group
of statements until certain specified conditions are met .This involves
kind of decision making to see whether a particular condition has occurred
or not and then direct the computer to execute certain statements
accordingly.
Decision control structure in C can be implemented by using:-
1. If statement
2. If-else statement
3. Nested if else statement
4. else-if ladder
5. case control structure
6. conditional operator
if statement:- This is the most simple form of decision control statement.
In this form, a set of statements are executed only if the condition given
with if evaluates to true.
Its general syntax and flow chart is as under:-
if(condition)
{
Statements ;
}

A program to understand the if statement.


/* program to check whether the given number is negative*/
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf(“enter the number”);
scanf(“%d”,&num);
if(num<0)
{
printf(“the entered number is negative”);
}
getch();
}
}

if- else statement:-


This is a bi-directional control statement. This statement is used to test a
condition and take one of the two possible actions. If the condition
evaluates to true then one statement (or block of statements) is executed
otherwise other statement (or block of statements) is executed.
The general form and flow chart of if-else statement is as under:-
if(condition)
{
block of statements;
}
else
{
block of statements;
}

We illustrate if-else statement using the following program


/*Program to find the biggest of two numbers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2 ;
clrscr();
printf(“enter the two numbers”);
scanf(“%d %d”,&num1,&num2);
if(num1>num2)
{
printf(“the number %d is big”,num1);
}
else
{
printf(“the number %d is big”,num2);
}
getch();
}
Nested if-else:-
If we have if-else statement within either the body of an if statement or
the body of else statement or in the body of both if and else, then this is
known as nesting of if else statement.
The general form of nested if-else statement is as follows:-
if(condition1)
{
if(condition2)
statements;
else
statements;
}
else
{
if(condition3)
Statements;
else
Statements;
}
We give the following program to explain nesting of if else:-
/*program to find the largest of three numbers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b,c,large;
printf(“enter the three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
large=a;
else
large=c;
}
else
{
if(b>c)
large=b;
else
large=c;
}
printf(“largest number is %d”,large);
getch();
}

Else if ladder:-
This is a type of nesting in which there is an if-else statement in every else
part except the last else part. This type of nesting is called else if ladder.
The general syntax and flow chart of else if ladder is as follows:-
If(condition1)
statementA;
else if(condition2)
statementB;
else if(condition3)
statementC;
else
statementD;
A program to illustrate the else if ladder:-
/*program to find the grade of the student*/
#include<stdio.h>
#include<conio.h>
void main()
{
int marks;
printf(“enter the percentage of the student”);
scanf(“%d”,&marks);
if(marks>=80)
printf(“your grade is a”);
else if(marks>=70)
printf(“your grade is b”);
else if(marks>=60)
printf(“your grade is c”);
else if(marks>=50)
printf(“your grade is d”);
else
printf(“you are fail”);
getch();
}

SWITCH STATEMENT

Switch case statements are a substitute for long if statements and has
more
flexibility and a clearer format than else-if ladder. This statement is used
to select one out of the several numbers of alternatives present in a block.
This selection statement successively tests the value of an expression
against a list of integer or character constants. When a match is found, the
statements associated with that constant are executed.
The general syntax of switch case statement is as follows:-
switch(expression)
{
case constant1: statements;
case constant2: statements;
case constant3: statements;
………………………
………………………
case constantN: statements;
default : statement;
}
Here switch, case and default are keywords.
The expression following the switch keyword must give an integer value.
This expression can be any integer or character variable, or a function call
that returns an integer. It can also be arithmetic, relational, logical or
bitwise expression yielding an integer. It can be integer or character
constant also. Data types long int and short int are also allowed.The
constant following the case keyword should be of integer or character
type. We cannot use floating point or string constant.
A program to explain switch case statement
/*program to print day of the week*/
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
clrscr();
printf(“enter the day number from 1 to7”);
scanf(“%d”,&day);
switch(day)
{
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;
case 6:printf(“saturday”);
break;
case 7: printf(“sunday”);
break;
default:printf(“wrong input”);
}
getch();
}
NOTE:- In switch case statement, if we do not associate a break statement
with every case then from the case for which the expression matches with
the constant, all the statements are executed until the switch case block
ends. This situation is referred to as Fall Through. Conditional operator:-
It is a ternary operator and is used to perform simple conditional
operations. It is used to do operations similar to if-else statement.
The general syntax of conditional operator is as under:-
Test expression? expression1:expression2
Here firstly the test expression is evaluated.
If the test expression evaluates to true then the expression1 is evaluated
and it becomes the value of the whole expression.
If the test expression evaluates to false then the expression2 is evaluated
and it becomes the value of the whole expression.
For eg., a>b ? a : b
Here firstly the expression a>b is evaluated. If it evaluates to true then the
value of a becomes the value of the whole expression otherwise value of
b becomes the value of whole expression.

BREAK STATEMENT

The break statement in C programming has the following two usages −


• When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the
loop.
• It can be used to terminate a case in the switch statement (covered in the next
chapter).
If you are using nested loops, the break statement will stop the execution of the
innermost loop and start executing the next line of code after the block.

Syntax
The syntax for a break statement in C is as follows −
break;

Flow Diagram

Example
Live Demo
#include <stdio.h>

int main () {

/* local variable definition */


int a = 10;

/* while loop execution */


while( a < 20 ) {

printf("value of a: %d\n", a);


a++;

if( a > 15) {


/* terminate the loop using break statement */
break;
}
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

CONTINUE STATEMENT
Continue is also a loop control statement just like the break
statement. continue statement is opposite to that of break statement, instead of
terminating the loop, it forces to execute the next iteration of the loop.
As the name suggest the continue statement forces the loop to continue or
execute the next iteration. When the continue statement is executed in the loop,
the code inside the loop following the continue statement will be skipped and
next iteration of the loop will begin.
Syntax:
continue;

Example:
Consider the situation when you need to write a program which prints number
from 1 to 10 and but not 6. It is specified that you have to do this using loop
and only one loop is allowed to use.
Here comes the usage of continue statement. What we can do here is we can
run a loop from 1 to 10 and every time we have to compare the value of iterator
with 6. If it is equal to 6 we will use the continue statement to continue to next
iteration without printing anything otherwise we will print the value.
Below is the implementation of the above idea:

// C program to explain the use


// of continue statement

#include <stdio.h>

nt main() {

// loop from 1 to 10

for (int i = 1; i <= 10; i++) {

// If i is equals to 6,

// continue to next iteration

// without printing

if (i == 6)

continue;

else

// otherwise print the value of i

printf("%d ", i);


}

return 0;

Output:
1 2 3 4 5 7 8 9 10

LOOPING STATEMENT

Iterations or loops are used when we want to execute a statement or block


of statements several times.The repetition of loops is controlled with the
help of a test condition. The statements in the loop keep on executing
repetitively until the test condition becomes false.
There are the following three types of loops:-
1. While loop
2. Do-while loop
3. For loop
All these loops are explained as under:-
While loop : - It is the fundamental looping statement in C. It is suited for
the problems where it is not known in advance that how many times a
statement or block of statements will be executed.
The general syntax of while loop is as under:-
While(condition)
{
Statement(s);
}
We explain the working of while loop with the help of flow chart as
under:-
Firstly the condition given with while is evaluated. If the condition
evaluates to true then the statements given in the body of the loop are
executed. After the execution of all the statements the condition is again
checked and if it again evaluates to true then the statements given in the
body of the loop are again executed. In this way the statements are
executed again and again until the condition given evaluates to false.For
terminating the loop, a termination condition is given in the loop body
which makes the condition false at some point of time and as a result of
which the loop terminates. If we do not give the termination condition
then the loop goes on repeating again and again infinite times. Such loops
are referred to as infinite loops.
We explain the while loop with the help of following program.
/*program to find the sum of digits of the given number.*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n,num,rem,sum=0;
printf(“Enter the number”);
scanf(“%d”,&num);
n=num;
while(num>0)
{
rem=num%10;
sum =sum+rem;
num=num/10;
}
printf(“the sum of the digits of %d is =%d”,n,sum);
getch();
}

do-while loop :-
The do-while statement is also used for looping. It is similar to while loop
and is used for the problems where it is not known in advance that how
many times the statement or block of statements will be executed.
However, unlike while loop, in case of do-while, firstly the statements
inside the loop body are executed and then the condition is evaluated. As
a result of which this loop is executed at least once even if the condition
is initially false. After that the loop is repeated until the condition
evaluates to false.
Since in this loop the condition is tested after the execution of the loop, it
is also known as posttest loop.
The general syntax of do-while loop is as follows:-
do
{
Statement(s);
}while(condition);
The flow chart of do-while is given as under:-
For loop :-
The general syntax of for loop consists of three expressions separated by
semicolons. It is given as follows:-
for(expression1;expression2;expression3)
Body of loop
condition
Next statement
out of loop
{
Statement(s);
}
Here the expression1 is the initialization expression,expression2 is the test
expression and expression3 is the update expression. Expression1 is
executed only once when the loop starts and is used to initialize the loop
variables. Expression2 is a condition and is tested before each iteration of
the loop. Expression3 is an update expression and is executed each time
after the body of the loop is executed.
The flow chart of for loop is given as follows:-
FUNCTIONS:
• Defining A Function, Accessing A Function, Function Prototypes,
• Passing Arguments to a Function, Return Values and Their Types,
Category of Functions, Recursion,
• Storage Classes: Automatic Variables, External, Variables, Static
Variables, Register Variable

➢ C functions
One of the strength of the c language is c functions. C enable s it’s programmers to break up a program into
segments commonly known as functions. Every function in the program is supposed to perform a well
defined task

A function is a self contained block of program statements


that perform a particular task.

C functions can be classified into two categories, namely library functions and user defined functions.

1. Library functions
2. User-defined functions

Library functions are those functions which are already defined in C library. These functions are not
required to be written by us. Example printf() , scanf() , strcat() etc. You just need to include appropriate
header files to use these functions.
User-defined functions on the other hand, are those functions which are defined by the user at the time of
writing program. main() is an example of user-defined functions. main() is a function called by the
Operating system when program is loaded and returns to the Operating system when terminated.

Benefits of using functions:


• Avoid repetition of codes. You just have to call the function by its name to use it, wherever
required.
• It makes the program more readable and easy to understand.
• Divide a complex problem into simpler ones.
• Reduces chances of error.
• Editing and debugging becomes easier by using function.

Program using multiple function


Elements of user defined functions:
In order to make use of user defined functions we need to establish three elements that are related to
functions:-

• Function declaration or( Function Prototype)


• Function definition
• Function call

➢ Function declaration: Like variables all functions in a c program must be declared


before they are invoked. A function declaration (also known as function prototype) consists of four
parts
• Function type(return type)
• Function name
• Parameter list
• Terminating semicolon

They are coded in the following format

function_type function name(data_type variable1,………..);


OR
function_type function name(data_type list);

examples of declaration statements


• int add_numbers(void);
• int mean(int x,int y);
• float FtoC(float faren);
• double power(double val, unsigned power);
• void init(void);
• sub_num();

This is very similar to the function header line except the terminating semicolon.

Points to note:
1. The parameter list must be separated by commas.
2. The parameter names do not need to be the same in the prototype declaration and the function
definition.
3. The types must match the types of parameters in the function definition, in number and order
4. Use of parameter names in the declaration is optional
5. If the function has no formal parameters, the list is written as (void).
6. The return type is optional, when the function returns int type data.
7. The return type must be void if no value is returned.
8. When the declared types do not match with the types in the function definition, compiler will
Produce an error.

When a function does not take any parameters and does not return any value, its prototype is
written as:
void display (void):
A prototype declaration may be placed in two places in a program

1. Above all the functions (including main).


2. Inside a function definition.

When we place the declaration above all the functions (in the global declaration section), the prototype
is referred to as a global prototype. Such declarations are available for all the functions in the program.
When we place it in a function definition (In the local declaration section), the prototype is called a
local prototype. Such declarations are primarily used by the functions containing them. The place of
declaration of a function defines a region in a program in which the function may be used by other
functions. This region is known as the scope of the function. It is a good programming style to declare
prototypes in the global declaration section before main. It adds flexibility, provides an excellent quick
reference to the functions used in the program, and enhances documentation
➢ Function definition :
It is an independent program module that is specially written to implement the requirements of
Function. It includes the following elements.

a) Function type
b) Function name Function header
c) List of parameters
d) Local variable declarations
e) Function statements Function body
f) return statements

The general format of function definition to implement these ywo parts is given below

Function type function name (parameter list)


{
Local variable declaration
Function statements1;
Function statements2;
…………………..
…………………..
Return statement;
}

Function header consist of three parts: the function type (also known as return type),the function name
and the formal parameter list. Not that the semicolon is not used at the end of the function header.

Function type: it specifies the type of value (like float or double) that the function is expected to return
to the program calling the function. If the return type is not explicitly specified C will assume that it is an
integer type. If the function is not returning anything, then we need to specify the return type as void.

Function name: it is any valid c identifier and therefore must follow the same rules of formation as other
variable names in C. the name should be appropriate to the task performed by the function.
List of parameters: also known as arguments. It declares the variables that will receive the data sent by
the calling program. They serve as the input data to the function to carry out the specified task. Since they
represent the actual input values they are often referred to as formal parameters.

Function body contains the declarations and statements necessary for performing the required task .The
body enclosed in braces, contains three parts in the given order
1) Local declarations that specify the variables needed by the function
2) Function statements that perform the task of the function
3) A return statement that returns the value evaluated by the function.

If a function returns nothing, return statement can be avoided. However, note that its return type should be
specified as void. It is nice to have a return statement even for void functions. A function can return only a
single value

Example

a) Float mul ( float x,float y)


{
Float result; /*local variable*/
Result =x*y; /*computes the prodect*/
Return (result); /*returns the result*/
}

b) void sum (int a, int b)


{
printf ("sum = %s", a + b); /* no local variables */
return; /* optional *
}

c) void display (void)


{
/* no local variables */
printf ("No type, no parameters");
/* no return statement */
}

Note

1. When a function reaches its return statement, the control is transferred back to the calling program
. In the absence of a return statement, the closing brace acts as a void return.
2. A local variable is a variable that is defined inside a function and used without having any role in
the communication between functions.

➢ Function call:
Functions call statement access the function, which means program control passes to that function. After
completion of the function the program control returns back to the calling environment
• The general form of function call is
function_name(<variable 1,variabke 2,…….>); function_name() ;
OR OR
variable_name=function_name(variable1,variabke2,…….>); variable_name = function_name();

A function can be called by simply using the function name followed by a list of parameters(or arguments), if any
enclosed in paranthesis.example.

main()
{
Int y;
y=mul(10,5); /* function call */
Printf(“%d\n”,y);
}

When the compiler encounters a function call, the control is transferred to the function mul(). This
function is then executed line by line as described and a value is returned when a return statement is
encountered. This value is assigned to y. This is illustrated below:

main()
{
int y:
y =mul (10,5); /*call*/
}
int mul (int x, int y)
{
int p; /* local variable*/
p=x *y; /*x =10, y = 5*/
return (p);
}

The function call sends two integer values 10 and 6 to the function

int mul(int x, int y)

Which are assigned to x and y respectively. The function computes the product x and y, assigns the
result to the local variable p, and then returns the value 25 to the main where it is assigned to y again
There are many different ways to call a function. Listed below are some of the ways the function mul
can be invoked
mul (10,5)
mul (m. 5)
mul (10. n)
mul (m, n)
mul (m + 5. 10)
mul (10, mul(m,n))
mul (expression, expression2)
Note that the sixth call uses its own call as its one of the parameters, When we use expressions, they
should be evaluated to single values that can be passed as actual parameters, A function which returns a
value can be used in expressions like any other variable. Each of the following statements is valid:

printf("%d\n", mul (p,q));


y mul(p,q) / (p+q):
1f (mul (m,n)>total) printf("large");

However, a function cannot be used on the right side of an assignment statement.


For instance,

mul(a,b) =15;

is invalid
A function that does not return any value may not be used in expressions; but can be called in
to perform certain tasks specified in the function.. Such functions may be called in by simply stating their
names as independent statements

Example:

main()
{
printline();
}

Note the presence of a semicolon at the end


Function Call
A function call is a postfix expression. The operator (..) is at a very high level of precedence. Therefore,
when a function call is used as a part of an expression, it will be evaluated first, unless parentheses are
used to change the order of precedence.
In a function call, the function name is the operand and the parentheses set (...) which contains the
actual parameters is the operator. The actual parameters must match the function's formal parameters
in type, order and number. Multiple actual parameters must be separated by commas.
Note
1. If the actual parameters are more than the formal parameters, the extra actual arguments
will be discarded.
2. On the other hand, if the actuals are less than the formals, the unmatched formal
arguments will be initialized to some garbage,
3. Any mismatch in data types may also result in some garbage values.

Parameters Everywhere!
Parameters (also known as arguments) are used in following three places:
1. in declaration (prototypes),
2. in function call, and
3. in function definition.

• The parameters used in prototypes and function definitions are called formal parameters.
• The parameters used in function calls are called actual parameters.
• Actual parameters used in a calling statement may be simple constants, variables, or expressions.
• The formal and actual parameters must match exactly in type, order and number. Their names,
however, do not need to match.
➢ Passing Arguments To A Function:
There are two approaches to passing argument to a function:

• Call by Value
• Call by Reference/Address
Call by Value
In this approach, the values are passed as function argument to the definition of function.

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.

Example of call by value


#include<stdio.h>

void main()
{
int A=10,B=20;

printf("\nValues before calling %d, %d",A,B);

fun(A,B); //Statement 1

printf("\nValues after calling %d, %d",A,B);

}
void fun(int X,int Y) //Statement 2
{
X=11;
Y=22;
}

Output :

Values before calling 10, 20


Values after calling 10, 20

In the above example, statement 1 is passing the values of A and B to the calling function fun(). fun() will
receive the value of A and B and put it into X and Y respectively. X and Y are value type variables and
are local to fun(). Any changes made by value type variables X and Y will not effect the values of A and
B.

Call by reference
In this approach, the references/addresses are passed as function argument to the definition of function

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 are performed on the value stored at the address
of the actual parameters, and the modified value gets stored at the same address.

Example of call by reference

#include<stdio.h>
void main()
{
int A=10,B=20;
printf("\nValues before calling %d, %d",A,B);
fun(&A,&B); //Statement 1
printf("\nValues after calling %d, %d",A,B);
}
void fun(int *X,int *Y) //Statement 2
{
*X=11;
*Y=22;
}
Output :
Values before calling 10, 20
Values after calling 11, 22

In the above example, statement 1 is passing the reference of A and B to the calling function fun(). fun()
must have pointer formal arguments to receive the reference of A and B. In statement 2 *X and *Y is
receiving the reference A and B. *X and *Y are reference type variables and are local to fun(). Any
changes made by reference type variables *X and *Y will change the values of A and B respectively
➢ Return Values And Their Types:
A function may or may not send back any value to the calling function. In it does it is done through
the return statement. While it is possible to pass to the called function any number of
values, the called function can only return one value per call, at the most The return statement can
take one of the following forms:

return;
or
return(expression)

The first, the 'plain' return does not return any value it acts much as the closing brace of the function.
When a return is encountered the controlisimmediately passed back to the calling function. An example of
the use of a simple return is as follows:

1f(error)
return;
The second form of roturn with an expression returns the value of the expression. For example, the
function
int mul (int x, int y)
int p:
px"y
return(p):
returns the value of p which is the product of the values of x and y. The last two statements can be
combined into one statement as follows:

return (x*y);

A function may have more than one return statements. This situation arises when the value returned is
based on certain conditions. For example:
if( x < 0)
return(0);
else
return (1):

What type of data does a function return? All functions by default return int type data. But what
happens if a function must return some other type? We can force a function to return a particular type of
data by using a type specifier in the function header as discussed earlier. When a value is returned, it is
automatically cast to the function's type. In functions that do computations using doubles, yet return ints,
the returned value will be truncated to an integer. For instance, the function

int product (void)


{
return (2.5 * 3.0);
}

will return the value 7. only the integer part of the result.
NESTING OF FUNCTIONS
C permits nesting of functions freely. main can call function1, which calls function2, which calls
function3, ...... and so on. There is in principle no limit as to how deeply functions can be nested.
Consider the following program:

float ratio (int x, int y, int z);


int difference (int x, int y);
main
{
int a, b, C;
scanf("\d d d", 8, 8, 8c):
printf("* In, ratio(a,b,c)):
float ratiofint n, int y, int z)
if(differencely. :))
return(x/y-2));
else
return(0.0):
int difference(int p. inta)
if (p = 0)
return (1):
else
return(0);

}
The above program calculates the ratio a/b-c and prints the result. We have the following three
functions:

main()
ratio()
difference()
main reads the values of a, b, and cand calls the function ratio to calculate the value alb-c). This ratio
cannot be evaluated if (6-c) = 0. Therefore, ratio calls another function difference to test whether the
difference (b-c) is zero or not difference returns 1. if b is not equal to c; otherwise returns zero to the
function ratio. In tum, ratio calculates the value a/b-c) if it receives 1 and returns the result in float. In
tase, ratio receives zero from difference, it sends back 0.0 to main indicating that (b-C) = 0 Nesting of
function calls is also possible. For example, a statement like

P = mul(mul(5,2).6);

Is valid. This represents two sequential function calls. The inner function call is evaluated first and the
ratured value is again used as an actual argument in the outer function call. If mul returns the product
of its arguments, then the value of p would be 60 (= 5 x 26).Note that the nesting does not mean defining
one function within another. Doing this is illegal.
➢ Category Of Functions
There can be 4 different types of user-defined functions they are:
1. Function with no arguments and no return value
2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and a return value
1. Function with no arguments and no return value

When a function has no arguments it does not receive any data from the calling function. Similarly when it
does not return a value the calling function does not receive any data from the called function. Such
functions can either be used to display information or they are completely dependent on user inputs.
Function declaration : void function();
Function call : function();
Function definition : void function()
{
statements;
}

Example:
#include<stdio.h>
main (){
void sum ();
clrscr ();
sum ();
getch ();
}
void sum (){
int a,b,c;
printf("enter 2 numbers:\n");
scanf ("%d%d", &a, &b);
c = a+b;
printf("sum = %d",c);
}
Output
Enter 2 numbers:
3
5 sum=
2.Function with no arguments and a return value

There could be occasions where we may need to design functions that may not take any arguments but
returns a value to the calling function. A example for this is getchar function it has no parameters but it
returns an integer an integer type data that represents a character.

Function declaration : int function();


Function call : function();
Function definition : int function()
{
statements;
return x;
}

Example:
#include<stdio.h>
main (){
int sum ();
int c;
c= sum ();
printf(“sum = %d”,c);
getch ();
}
int sum (){
int a,b,c;
printf(“enter 2 numbers”);
scanf (“%d%d”, &a, &b);
c = a+b;
return c;
}
Output
Enter two numbers 10 20
30
3.Function with arguments and no return value

When a function has arguments, it receive any data from the calling function but it returns no values.

Function declaration : void function ( int );


Function call : function( x );
Function definition : void function( int x )
{
statements;
}

Example:
#include<stdio.h>
main (){
void sum (int, int );
int a,b;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
sum (a,b);
getch ();
}
void sum ( int a, int b){
int c;
c= a+b;
printf (“sum=%d”, c);
}
Output
Enter two numbers 10 20
Sum=30
4.Function with arguments and a return value

Function declaration : int function ( int );


Function call : function( x );
Function definition : int function( int x )
{
statements;
return x;
}

Example:
#include<stdio.h>
main (){
int sum ( int,int);
int a,b,c;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
c= sum (a,b);
printf ("sum=%d", c);
getch ();
}
int sum ( int a, int b ){
int c;
c= a+b;
return c;

Output
Enter two numbers 10 20
Sum=30

➢ Recursion:
When a called function in turn calls another function process of chaining occurs. Recursion is a special
case of this process, where a function calls itself. a very simple example of recursion is presented below.
main()
{
Printf(“This is an example of recursion”);
main();
}
When executed, this program will produce an output something like this:
This is an example of recursion
This is an example of recursion
This is an example of recursion
This is an ex
Execution is terminated abruptly, otherwise the execution will continue indefinitely.

For implementing recursion-


1. the problem must be decomposed to smaller problems of same type
2. Each time a function is called it must be closer to the solution
3. it needs a base condition which acts as the terminating condition Missing or incorrect base case will
generate an infinite sequence of calls resulting in stack overflow
• Recursive algorithms generally have an if statement of the given form

if(this is base case) then


solve it directely
elseredefine the problem using recursion

• Recursive functions uses a stack of data areas (consists of parameters, local variables and certain system
information) called ‘runtime stack’

• The memory area for each call is placed on the top of stack and taken off when the execution of the call
is complete • C uses this stacking principle for all nested function calls including recursion

a) Evaluation of factorials of a given number.

The factors of a given number n is expressed as a series of repetitive multiplications as shown below:
factorial of n = n(n-1)(n-2).........1.
For example
factorial of 4 = 4 x 3 x 2 x 1 = 24
A function to evaluate factorial of n is as follows:

factorial(int n)
{
int fact;
if (n=-1)
return(1);
else
fact - nefactorial(n-1);
return(fact);
}

Let us see how the recursion works. Assume n = 3. Since the value of n is not 1, the statement
fact - n * factorial(n-1);
will be executed with n = 3. That is,
fact - 3 * factorial(2);
will be evaluated. The expression on the right-hand side includes a call to factorial with n = 2. This call
will return the following value:
2.*factorial(1)
Once again factorial is called with n = 1. This time, the function returns 1. The sequence of operations can
be summarized as follows:
fact = 3 * factorial(2)
= 3.2. factorial(1)
= 3:21
=6
b) Fibonacci series using recursion (1,1,2,3,5,8,..)
• fib(n)= fib(n-1)+fib(n-2)
# include<stdio.h>
int fib(int);
int main()
{
int n,i;
printf(“Enter the number of terms”);
scanf(“%d”,&n);
for(i =1;i<=n,i++)
printf(“ %d ”, fib(i));
return 0;
}
/* function using recursion */
int fib(int n)
{
if (n==1) ||(n==2)
return 1;
else
return ( fib(n-1)) + fib(n-2) );
}

c) Sum of digits of a number

# include<stdio.h>
int sum (int);
int main()
{
int n,s;
printf(“Enter the number”);
scanf(“%d”,&n);
s= sum(n);
printf(“sum of digits of %d = %d”, n,s);
return 0;
}
/* function using recursion */
int sum(int n)
{
if (n==0)
return 0;
else
return ( n%10 +sum(n/10)) ;

Recursive functions can be effectively used to solve problems where solution is expressed in terms of
successively applying the same solution to subsets of the problem. When we write recursive functions we
must have an if statement somewhere to force the function to return without the recursive calls being
executed. Otherwise, the function will never return.

Scope and extent of variables

Scope: The region of the source code over which the declaration of an identifier is visible is
called the scope of the identifier. Scope relates to the accessibility, the period of existence and
the boundary of usage of variables in a statement block or a function

Extent: The period of time for which the memory is associated with the identifier is called
extent of the identifier

Global versus Local variables

Global variables – variables that are declared outside all functions and that can be accessed by all
functions
• Created at the beginning of the program and remain in existence till the end of execution •If not initialized
, it takes the value zero by default
•If a global and local variable has the same name, in the function local variable is used and global variable
is ignored.

Local variables –variables declared within the function and is usable only inside the function • created
automatically at the point of their declaration and ends when control is transferred to the calling point
•If not initialized takes some unknown junk value.

➢ Storage Classes:
Storage Classes are used to describe the features of a variable/function. These features basically
include the scope, visibility and life-time which help us to trace the existence of a particular variable
during the runtime of a program. C provides four storage class specifiers to be used with data type
specifiers in the declaration statement.

C language uses 4 storage classes, namely:

• Auto ( Automatic ) storage class


• Static storage class
• Extern ( External ) storage class
• Register storage class

The general form of variable declaration that includes storage class specifier is

storage_class_specifier data_type variable_name;

• Automatic storage class (auto)

• By default all variables within a function are automatic, i.e., these variables are created automatically
when the function is invoked.
• Even if variable declaration does not include the keyword auto, such variables are implicitly specified as
belonging to automatic storage class
• These variables are local to the function and has life so long as control is within the function.
•If not initialized, they take some garbage value

Syntax:

auto Data-type Variable-name;


OR
Data-type Variable-name

Example:

#include<stdio.h>

void display();
void main()
{
auto int a=10; //OR int a=10;

printf("\nA : %d",a);
display();
printf("\nA : %d",a);

}
void display()

{
int a=20; //OR auto int
a=20;

printf("\nA : %d",a);
}

Output :

A : 10
A : 20
A : 10

• Static storage class (static)

The static storage class instructs the compiler to keep a local variable in existence during the life-time of
the program instead of creating and destroying it each time it comes into and goes out of scope.
Therefore, making local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's
scope to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member to be
shared by all the objects of its class.

• A static variable is allotted a permanent storage location in memory. Its default value is zero
• These are not destroyed on function’s exit, but has life for the entire program duration
• They are visible only within the function
• These variables will retain their previous values from the previous call to the succeeding call

Syatax:
static Data-type Variable-name;

Example:

#include<stdio.h>

void display();
void main()
{
display();
display();
display();
}

void display()
{
static int a=1;

printf("\nA : %d",a);

a++;

Output :

A:1
A:2
A:3

In the above example, we does not use static keyword then the output will be :

Output :

A:1
A:1
A:1

• Register storage class (register)

• These variables are stored in CPU registers and hence speeds up execution
• Register specifier can be applied only to int and char type
• The number of register storage class variables is limited by the number of registers. if more
variables are specified, those above the limit will be converted as automatic variables
• Scope, life time and initial value are same as automatic variables
• Cannot apply Address operator (&).
The register should only be used for variables that require quick access such as counters.

Syntax:

register Data-type Variable-name;

Example
#include <stdio.h>
int main()
{
register int i;
for( i=1; i<=20000; i++)
printf(“%d “, i);
return 0;
}
• External storage class (extern)
Extern stands for external storage class. Extern storage class is used when we have global functions or
variables which are shared between two or more files. Keyword extern is used to declaring a global variable
or function in another file to provide the reference of variable or function which have been already defined
in the original file.
The variables defined using an extern keyword are called as global variables. These variables are accessible
throughout the program. Notice that the extern variable cannot be initialized it has already been defined in
the original file

• These are global variables. If shared between functions within a single file no need to specify
extern. Initial value 0
•If several programs are to be written and compiled separately and later linked to form an executable
program, and some variables are to be used by all/some programs then we use external storage class.

Syntax:

extern Data-type Variable-name;

OR

Data-type Variable-name;

Storage Declaration Storage Default Initial Scope Lifetime


Class Value

auto Inside a Memory Unpredictable Within the Within the


function/block function/block function/block

register Inside a CPU Garbage Within the Within the


function/block Registers function/block function/block
extern Outside all Memory Zero Entire the file and program
functions other files where the runtime
variable is declared
as extern

Static Inside a Memory Zero Within the program


(local) function/block function/block runtime

Static Outside all Memory Zero Global program


(global) functions runtime
MODULE 3
ARRAYS

Defining an Array, Processing an Array, Multidimensional array, Array


Operations. Strings: puts and gets function, One dimensional Array,
Character Array, Array of Strings, Passing 1d and 2d arrays to function,
String handling without using String functions.

• Arrays a kind of data structure that can store a fixed-size sequential


collection of elements of the same type. An array is used to store a collection
of data, but it is often more useful to think of an array as a collection of
variables of the same type.
• An array is a variable that can store multiple values.
• How to declare an array?

dataType arrayName[arraySize];

For example,

float mark[5];

Here, we declared an array, mark, of floating-point type. And its size is 5.


Meaning, it can hold 5 floating-point values.

It's important to note that the size and type of an array cannot be changed once it is
declared.

• Access Array Elements

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0], the
second element is mark[1] and so on.
Few keynotes:
Arrays have 0 as the first index, not 1.

In this example, mark[0] is the first element.

If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]

Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1]
will be 2124d. Similarly, the address of mark[2] will be 2128d and so on.

This is because the size of a float is 4 bytes.

• How to initialize an array?


It is possible to initialize an array during declaration.

For example,

int mark[5] = {19, 10, 8, 17, 9};

You can also initialize an array like this.


int mark[] = {19, 10, 8, 17, 9};

Here, we haven't specified the size. However, the compiler knows its size is 5 as
we are initializing it with 5 elements.
Example 1: Array Input/Output

// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}
printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
Output
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

Using Arrays

Elements of an array are accessed by specifying the index ( offset ) of the desired
element within square [ ] brackets after the array name.

Array subscripts must be of integer type. ( int, long int, char, etc. )

VERY IMPORTANT: Array indices start at zero in C, and go to one less than the
size of the array. For example, a five element array will have indices zero through
four. This is because the index in C is actually an offset from the beginning of the
array. ( The first element is at the beginning of the array, and hence has zero
offset. )

Landmine: The most common mistake when working with arrays in C is


forgetting that indices start at zero and stop one less than the array size.
Arrays are commonly used in conjunction with loops, in order to perform the same
calculations on all ( or some part ) of the data items in the array.

Sample Programs Using 1-D Arrays

The first sample program uses loops and arrays to calculate the first twenty
Fibonacci numbers. Fibonacci numbers are used to determine the sample points
used in certain optimization methods.

/* Program to calculate the first 20 Fibonacci numbers. */

#include <stdlib.h>

#include <stdio.h>

int main( void ) {

int i, fibonacci[ 20 ];

fibonacci[ 0 ] = 0;

fibonacci[ 1 ] = 1;

for( i = 2; i < 20; i++ )

fibonacci[ i ] = fibonacci[ i - 2 ] + fibonacci[ i - 1 ];

for( i = 0; i < 20; i++ )

printf( "Fibonacci[ %d ] = %f\n", i, fibonacci[ i ] );

Basic Operations
Following are the basic operations supported by an array.

• Traverse − print all the array elements one by one.


• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the value.

Traverse Operation

This operation is to traverse through the elements of an array.

Example

Following program traverses and prints the elements of an array:

#include <stdio.h>

main() {

int LA[] = {1,3,5,7,8};

int item = 10, k = 3, n = 5;

int i = 0, j = n;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

}
When we compile and execute the above program, it produces the following result

Output

The original array elements are :

LA[0] = 1

LA[1] = 3

LA[2] = 5

LA[3] = 7

LA[4] = 8

Insertion Operation

Insert operation is to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given index
of array.

Here, we see a practical implementation of insertion operation, where we add data


at the end of the array −

Example

#include <stdio.h>

main() {

int LA[] = {1,3,5,7,8};

int item = 10, k = 3, n = 5;


int i = 0, j = n;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

n = n + 1;

while( j >= k) {

LA[j+1] = LA[j];

j = j - 1;

LA[k] = item;

printf("The array elements after insertion :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

When we compile and execute the above program, it produces the following result

Output

The original array elements are :

LA[0] = 1

LA[1] = 3

LA[2] = 5

LA[3] = 7

LA[4] = 8

The array elements after insertion :

LA[0] = 1

LA[1] = 3

LA[2] = 5

LA[3] = 10

LA[4] = 7

LA[5] = 8

Deletion Operation

Deletion refers to removing an existing element from the array and re-organizing
all elements of an array.

Example
#include <stdio.h>

void main() {

int LA[] = {1,3,5,7,8};

int k = 3, n = 5;

int i, j;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

j = k;

while( j < n) {

LA[j-1] = LA[j];

j = j + 1;

n = n -1;

printf("The array elements after deletion :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

}
When we compile and execute the above program, it produces the following result

Output

The original array elements are :

LA[0] = 1

LA[1] = 3

LA[2] = 5

LA[3] = 7

LA[4] = 8

The array elements after deletion :

LA[0] = 1

LA[1] = 3

LA[2] = 7

LA[3] = 8

Binary search in C

Binary search in C language to find an element in a sorted array. If the array isn't
sorted, you must sort it using a sorting technique such as merge sort. If the element
to search is present in the list, then we print its location. The program assumes that
the input numbers are in ascending order.
#include <stdio.h>

int main()

int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");

scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)

scanf("%d", &array[c]);

printf("Enter value to find\n");

scanf("%d", &search);

first = 0;

last = n - 1;

middle = (first+last)/2;

while (first <= last) {

if (array[middle] < search)

first = middle + 1;

else if (array[middle] == search) {


printf("%d found at location %d.\n", search, middle+1);

break;

else

last = middle - 1;

middle = (first + last)/2;

if (first > last)

printf("Not found! %d isn't present in the list.\n", search);

return 0;

Sorting
In simple word, sorting means arranging the given elements or data in an ordered
sequence. The main purpose of sorting is to easily & quickly locate an element in a
sorted list & design an efficient algorithm around

//C Program to sort an array in ascending or descending order

#include <stdio.h>

void main()

int i,j,n,a[100],temp,p,q,temp1;

printf("Enter the size of array : \n") ; //Taking size of array

scanf("%d",&n) ;

printf("Enter the elements : \n") ; //Taking input from user

for(i=0;i<n;i++)

scanf("%d",&a[i]) ;

for(i=0;i<n;i++) // loop for sorting array in ascending order

for(j=i+1;j<n;j++) { if(a[i]>a[j])

temp=a[i];

a[i]=a[j];
a[j]=temp;

printf("Ascending order of an array : \n"); //print ascending order

for(i=0;i<n;i++)

printf("%d ",a[i]) ;

for(p=0;p<n;p++) // loop for sorting array in descending order

for(q=p+1;q<n;q++)

if(a[p]<a[q])

temp1=a[p];

a[p]=a[q];

a[q]=temp1;

}
}

printf("\n Descending order of an array : \n"); // print descending order

for(p=0;p<n;p++)

printf("%d ",a[p]) ;

Output:-

Enter the size of array :

Enter the elements :

Ascending order of an array :

12579

Descending order of an array :


97521

Multidimensional Arrays
• Multi-dimensional arrays are declared by providing more than one set of
square [ ] brackets after the variable name in the declaration statement.
• One dimensional arrays do not require the dimension to be given if the array
is to be completely initialized. By analogy, multi-dimensional arrays do not
require the first dimension to be given if the array is to be completely
initialized. All dimensions after the first must be given in any case.
• For two dimensional arrays, the first dimension is commonly considered to
be the number of rows, and the second dimension the number of columns.
We will use this convention when discussing two dimensional arrays.
• Two dimensional arrays are considered by C/C++ to be an array of ( single
dimensional arrays ). For example, "int numbers[ 5 ][ 6 ]" would refer to a
single dimensional array of 5 elements, wherein each element is a single
dimensional array of 6 integers. By extension, "int numbers[ 12 ][ 5 ][ 6 ]"
would refer to an array of twelve elements, each of which is a two
dimensional array, and so on.
• Another way of looking at this is that C stores two dimensional arrays by
rows, with all elements of a row being stored together as a single unit.
Knowing this can sometimes lead to more efficient programs.
• Multidimensional arrays may be completely initialized by listing all data
elements within a single pair of curly {} braces, as with single dimensional
arrays.
• It is better programming practice to enclose each row within a separate
subset of curly {} braces, to make the program more readable. This is
required if any row other than the last is to be partially initialized. When
subsets of braces are used, the last item within braces is not followed by a
comma, but the subsets are themselves separated by commas.
• Multidimensional arrays may be partially initialized by not providing
complete initialization data. Individual rows of a multidimensional array
may be partially initialized, provided that subset braces are used.
• Individual data items in a multidimensional array are accessed by fully
qualifying an array element. Alternatively, a smaller dimensional array may
be accessed by partially qualifying the array name. For example, if "data"
has been declared as a three dimensional array of floats, then data[ 1 ][ 2 ][ 5
] would refer to a float, data[ 1 ][ 2 ] would refer to a one-dimensional array
of floats, and data[ 1 ] would refer to a two-dimensional array of floats. The
reasons for this and the incentive to do this relate to memory-management
issues that are beyond the scope of these notes.

Sample Program Using 2-D Arrays

#include <stdio.h>

int main( void )

int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };

int b[ 2 ][ 3 ] = { { 1, 2, 3 }, { 3, 2, 1 } };

int sum[ 2 ][ 3 ], row, column;


/* First the addition */

for( row = 0; row < 2; row++ )

for( column = 0; column < 3; column++ )

sum[ row ][ column ] =

a[ row ][ column ] + b[ row ][ column ];

/* Then print the results */

printf( "The sum is: \n\n" );

for( row = 0; row < 2; row++ ) {

for( column = 0; column < 3; column++ )

printf( "\t%d", sum[ row ][ column ] );

printf( '\n' ); /* at end of each row */

return 0;

String and Character Array


String is a sequence of characters that are treated as a single data item and
terminated by a null character '\0'. Remember that the C language does not support
strings as a data type. A string is actually a one-dimensional array of characters in
C language. These are often used to create meaningful and readable programs.

For example: The string "home" contains 5 characters including the '\0' character
which is automatically added by the compiler at the end of the string.
String Handling Functions:

C language supports a large number of string handling functions that can be used
to carry out many of the string manipulations. These functions are packaged in the
string.h library. Hence, you must include string.h header file in your programs to
use these functions.

The following are the most commonly used string handling functions.

Method Description

strcat() It is used to concatenate(combine) two strings

strlen() It is used to show the length of a string

strrev() It is used to show the reverse of a string

strcpy() Copies one string into another

strcmp() It is used to compare two string


Example:

#include <stdio.h>

#include <string.h>

int main () {

char str1[12] = "Hello";

char str2[12] = "World";

char str3[12];

int len ;

/* copy str1 into str3 */

strcpy(str3, str1);

printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */

strcat( str1, str2);

printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */

len = strlen(str1);

printf("strlen(str1) : %d\n", len );

return 0;

When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello

strcat( str1, str2): HelloWorld

strlen(str1) : 10

Array of Strings
What is an Array of String?

The string is a collection of characters, an array of a string is an array of arrays of


characters. Each string is terminated with a null character. An array of a string is
one of the most common applications of two-dimensional arrays.

scanf( ) is the input function with %s format specifier to read a string as input from
the terminal. But the drawback is it terminates as soon as it encounters the space.
To avoid this gets( ) function which can read any number of strings including
white spaces.
puts() is used to display a string contained in a string variable . It also adds a new
line character to the end of the string

puts(string variable);

Eg. puts(str);

Sting is an array of characters terminated with the special character known as the
null character (“\0”).

Syntax

The syntax for array of string is as follows:

datatype name_of_the_array[size_of_elements_in_array];

char str_name[size];

Example

datatype name_of_the_array [ ] = { Elements of array };

char str_name[8] = “Strings”;

Str_name is the string name and the size defines the length of the string (number of
characters).

A String can be defined as a one-dimensional array of characters, so an array of


strings is two –dimensional array of characters.

Syntax

char str_name[size][max];
Syntax

char str_arr[2][6] = { {‘g’,’o’,’u’,’r’,’i’,’\0’}, {‘r’,’ a’,’ m’,’\0’}};

Alternatively, we can even declare it as

Syntax

char str_arr[2][6] ={“gouri”, ”ram”};

From the given syntax there are two subscripts first one is for how many strings to
declare and the second is to define the maximum length of characters that each
string can store including the null character. C concept already explains that each
character takes 1 byte of data while allocating memory, the above example of
syntax occupies 2 * 6 =12 bytes of memory.

Now for two-dimensional arrays, we have the following syntax and memory
allocation. For this, we can take it as row and column representation (table format).

char str_name[size][max];

In this table representation, each row (first subscript) defines as the number of
strings to be stored and column (second subscript) defines the maximum length of
the strings.

char str_arr[2][6] = { {‘g’,’o’,’u’,’r’,’i’,’\0’}, {‘r’,’ a’,’ m’,’\0’}};

Alternatively, we can even declare it as

Syntax:

char str_arr[2][8] ={“gouri”, ”ram”};


Program to read an array of strings.

#include<stdio.h>

int main()

char names[3][20];

int i;

printf(”\nEnter three string values\n”);

for(i=0;i<3;i++)

gets(names[i]);printf(”\nElements of string array are”);

for(i=0;i<3;i++)

printf(“\n%s”,names[i]);

return (0);

Output

Enter three string values

Lovejot

Ajay

Amit

Elements of string array are


Lovejot

Ajay

Amit

Difference between char array and string literal


There are two main differences between char array and literal.

We need to add the null character '\0' at the end of the array by ourself whereas, it
is appended internally by the compiler in the case of the character array.

The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.

Passing Arrays as Function Arguments in C


A one dimensional array can be easily passed as a pointer , would have to declare a
formal parameter in one of following three ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is
going to be received.

Way-1

Formal parameters as a pointer −

void myFunction(int *param,int size)

.
.

Way-2

Formal parameters as a sized array −

void myFunction(int param[10],int size)

. . .}

Way-3

Formal parameters as an unsized array −

void myFunction(int param[],int size)

Note :

in C, we must pass size of array as a parameter. Size may not be needed only in
case of ‘\0’ terminated character arrays, size can be determined by checking end of
string character.
Example 1:

#include <stdio.h>

void fun(int *arr, unsigned int n)

int i;

for (i=0; i<n; i++)

printf("%d ", arr[i]);

// Driver program

int main()

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

unsigned int n = sizeof(arr)/sizeof(arr[0]);

fun(arr, n);

return 0;

Example 2:

#include <stdio.h>
void fun(int arr[], unsigned int n)

int i;

for (i=0; i<n; i++)

printf("%d ", arr[i]);

// Driver program

int main()

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

unsigned int n = sizeof(arr)/sizeof(arr[0]);

fun(arr, n);

return 0;

Example 3:

#include <stdio.h>

#include <string.h>
void fun(char *arr)

int i;

unsigned int n = strlen(arr);

printf("n = %d\n", n);

for (i=0; i<n; i++)

printf("%c ", arr[i]);

// Driver program

int main()

char arr[] = "geeksquiz";

fun(arr);

return 0;

}
Passing a 2D array as a parameter in C
Just like a 1-D array, when a 2-D array is passed to a function, the changes made
by function effect the original array.

when a 2-D is passed to a function it is optional to specify the size of the left most
dimensions. So if we have an array of 2 rows and 3 dimensions then it can be
passed to a function in the following two ways:

int two_d[2][3] = { {99,44,11},


{4,66,9} };

1st way:

void function(int a[][3],int size)

// statements;

2nd way:

void function(int *a, int m, int n)

// statements;

}
2-D arrays are stored in row-major order i.e first row 0 is stored, then next to it row
1 is stored and so on. Therefore in C, a 2-D array is actually a 1-D array in which
each element is itself a 1-D array. Since the name of the array points to the 0th
element of the array. In the case of a 2-D array, 0th element is an array.

Hence we can also declare a function where the formal argument is of type pointer
to an array.

3rd way:

void function(int (*a)[3])

// statements;

Essentially in all the three cases discussed the type of the variable a is a pointer to
an array of 3 integers, they differ only in the way they are represented.
Example 1:

#include <stdio.h>

const int N = 3;

void print(int arr[][N], int m)

int i, j;

for (i = 0; i < m; i++)

for (j = 0; j < N; j++)

printf("%d ", arr[i][j]);

int main()

int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

print(arr, 3);

return 0;

}
Output

123456789
Example 2:

#include <stdio.h>

void print(int *arr, int m, int n)

int i, j;

for (i = 0; i < m; i++)

for (j = 0; j < n; j++)

printf("%d ", *((arr+i*n) + j));

int main()

int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

int m = 3, n = 3;

// We can also use "print(&arr[0][0], m, n);"

print((int *)arr, m, n);

return 0;
}

Output

123456789
Example 3:

#include <stdio.h>

const int M = 3;

void print(int (*arr)[M])

int i, j;

for (i = 0; i < M; i++)

for (j = 0; j < M; j++)

printf("%d ", arr[i][j]);

int main()

int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

print(arr);

return 0;
}

Output

123456789
String Handling Without Using String Functions

* C Program to Reverse a String

We can reverse a given string by simply swapping ith character from the start and
ith character from the end of the string. Each pair of characters is only swapped
once. If we swap a pair twice then we will obtain the same string.

Steps

1. Let N be the size of String.

2. Set i = 0 and j = N – 1

3. Repeat the following steps while i < j

• Swap(string[i] , string[j])

• ++i

• –j

We will implement our own strlen() function. In C/C++, every string ends with a
null character ‘\0’. To calculate the size of the string, we will traverse each
character of the array until we reach ‘\0’ and use a variable ‘count’ to count the
number of characters in the string.
#include<stdio.h>

// function to find the length of string

int length(char* string)

int count = 0;

// increment count until we reach the null charcter '\0'

// null character marks the end of string

while (string[count] != '\0')

++count;

} return count;

// function to reverse string

void reverse(char* string)

char temp;

int i, j, n;
n = length(string);

// swapping string[i] and string[j] until i<j

for (i = 0, j = n - 1; i < j; ++i, --j)

temp = string[j];

string[j] = string[i];

string[i] = temp;

}
int main()

char string[100];

printf("Enter a String: ");

scanf("%s", string);

printf("\nString Before Reverse: %s", string);

reverse(string);

printf("\n\nString After Reverse: %s", string);

*C program to copy string

Here we are giving one string in input and then with the help of for loop we
transfer the content of first array to the second array.
// CPP program to copy one string to other

// without using in-built function

#include <stdio.h>

int main()

// s1 is the source( input) string and s2 is the destination string

char s1[] = "GeeksforGeeks", s2[100], i;

// Print the string s1

printf("string s1 : %s\n", s1);

// Execute loop till null found

for (i = 0; s1[i] != '\0'; ++i) {

// copying the characters by

// character to str2 from str1

s2[i] = s1[i];
}

s2[i] = '\0';

// printing the destination string

printf("String s2 : %s", s2);

return 0;

}
Output:

string s1 : GeeksforGeeks

String s2 : GeeksforGeeks

*C program to Compare Two Strings

If string are equal then print “Equal strings” else print “Unequal strings”.

Examples:

Input: s1 = “geeksforgeeks”, s2 = “geeks”


Output: Uequal Strings

Input: s1 = “geeksforgeeks”, s2 = “geeksforgeeks”


Output: Equal Strings

There are three possible cases occur when we compare two strings:

1.Both the strings are the same means difference of ASCII value between
both the strings is 0.
2.Both the strings are different means ASCII value of first not matching character
in the first string is less than the second string then the difference
between both the strings is (<0).

3.Both the strings are different means ASCII value of first not matching character
in the first string is greater than the second string then the difference
between both the strings is (>0).

Based on the above three conditions, the idea is to compare each character of the
given strings one by one whenever condition 2 or 3 occurs then print “Unequal
strings” else print “Equal strings”.

Below is the implementation of the above approach:


// C program to compare the two strings

// without using strcmp() function

#include <stdio.h>

// Function that compares the two string

void compareStrings(char* x, char* y)

int flag = 0;

// Iterate a loop till the end

// of both the strings

while (*x != '\0' || *y != '\0') {

if (*x == *y) {

x++;

y++;

// If two characters are not same


// print the difference and exit

else if ((*x == '\0' && *y != '\0')

|| (*x != '\0' && *y == '\0')

|| *x != *y) {

flag = 1;

printf("Uequal Strings\n");

break;

// If two strings are exactly same

if (flag == 0) {

printf("Equal Strings\n");

// Driver Code

int main(void)

// Given strings s1 and s2


char s1[20] = "python";

char s2[20] = "dsa";

// Function Call

compareStrings(s1, s2);

return 0;

}
MODULE 4
Pointer
A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a
pointer before using it to store any variable address.
Declaring a pointer
The general form of a pointer variable declaration is −
type *var-name;

The pointer in c language can be declared using * (asterisk symbol). It is also known
as indirection pointer used to dereference a pointer.

1. int *a; //pointer to int


2. char *c; //pointer to char

Pointer Example

An example of using pointers to print the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number
variable, i.e., fff4. The value of number variable is 50. But the address of pointer
variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable
p.

Example

#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number; //stores the address of number variable
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
return 0;
}

Output

Address of number variable is fff4


Address of p variable is fff4
Value of p variable is 50

Pointer to array
int arr[10];
int *p[10]=&arr; // Variable p of type pointer is pointing to the
address of an integer array arr.
Pointer to a function
void show (int);
void(*p)(int) = &display; // Pointer p is pointing to the address
of a function
Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees, etc. and used with arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.
Usage of pointer

There are many applications of pointers

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc()


functions where the pointer is used.

2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It reduces
the code and improves the performance.

Address Of (&) Operator

The address of operator '&' returns the address of a variable. But, we need to use %u
to display the address of a variable.

The address operator cannot be applied to expressions, constants or register


variables.

The type of the pointer and the variable whose address is contained in the pointer
must be of same type.

int a=3; *p;

float *q;

p= &a; /* valid */

q= &a; /* invalid */

Example

#include<stdio.h>
int main(){
int number=50;
printf("value of number is %d, address of number is %u",number,&number);
return 0;
}

Output

value of number is 50, address of number is fff4


NULL Pointer

A pointer that is not assigned any value but NULL is known as the NULL pointer.
If you don't have any address to be specified in the pointer at the time of declaration,
you can assign NULL value. It will provide a better approach.

int *p=NULL;

VOID Pointer

A void pointer is a pointer that has no associated data type with it. A void pointer
can hold address of any type and can be typcasted to any type.

int a = 10;
char b = 'x';

void *p = &a; // void pointer holds address of int 'a'


p = &b; // void pointer holds address of char 'b'

Advantage of void pointers: malloc() and calloc() return void * type and this allows
these functions to be used to allocate memory of any data type (just because of void
*)

int main(void)
{
// Note that malloc() returns void * which can be
// typecasted to any type like int *, char *, ..
int *x = malloc(sizeof(int) * n);
}
Difference between void and Null Pointer

A null pointer is basically a null value assigned to a pointer of any data type
whereas a void pointer is a data type which remains void as long as an address of a
data type is not assigned to it.
The data type of the pointer is nothing but the type of data stored at the memory
location where the pointer is pointed. When you are not sure about the type of data
that is going to store at a particular memory location, you need to create the void
pointer.
Null pointer does not contain a reference of any variable/value. Hence we may state
that it has a NULL as its value making it a null pointer.
Void pointer is always of type void *

Mainly such pointers are used for dynamic memory allocations (using malloc(),
calloc() and realloc() functions) , where memory block reserved is pointer to by a
void pointer and as the pointer value is returned it has to be explicitly type casted
to a particular desired type.

Operations on pointers

We can perform arithmetic operations on the pointers like addition, subtraction, etc.
However, as we know that pointer contains the address, the result of an arithmetic
operation performed on the pointer will also be a pointer if the other operand is of
type integer. In pointer-from-pointer subtraction, the result will be an integer value.
Following arithmetic operations are possible on the pointer :

o Increment
o Decrement
o Addition
o Subtraction
o Comparison

Incrementing Pointer

If we increment a pointer by 1, the pointer will start pointing to the immediate next
location. This is somewhat different from the general arithmetic since the value of
the pointer will get increased by the size of the data type to which the pointer is
pointing.
We can traverse an array by using the increment operation on a pointer which will
keep pointing to every element of the array, perform some operation on that, and
update itself in a loop.

The Rule to increment the pointer is given below:

1. new_address= current_address + i * size_of(data type)

Where i is the number by which the pointer get increased.

32-bit

For 32-bit int variable, it will be incremented by 2 bytes.

64-bit

For 64-bit int variable, it will be incremented by 4 bytes.

Let's see the example of incrementing pointer variable on 64-bit architecture.

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p); // in our case, p will
get incremented by 4 bytes.
return 0;
}

Output

Address of p variable is 3214864300


After increment: Address of p variable is 3214864304
Traversing an array by using pointer
#include<stdio.h>
void main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
printf("printing array elements...\n");
for(i = 0; i< 5; i++)
{
printf("%d ",*(p+i));
}
}

Output

printing array elements...


1 2 3 4 5
Decrementing Pointer in C

Like increment, we can decrement a pointer variable. If we decrement a pointer, it


will start pointing to the previous location. The formula of decrementing the pointer
is given below:

new_address= current_address - i * size_of(data type)


32-bit

For 32-bit int variable, it will be decremented by 2 bytes.

64-bit

For 64-bit int variable, it will be decremented by 4 bytes.


example of decrementing pointer variable on 64-bit OS.

#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now point t
o the immidiate previous location.
}

Output

Address of p variable is 3214864300


After decrement: Address of p variable is 3214864296
Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer
is given below:

new_address= current_address + (number * size_of(data type))


32-bit

For 32-bit int variable, it will add 2 * number.

64-bit

For 64-bit int variable, it will add 4 * number.

example of adding value to pointer variable on 64-bit architecture.

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}

Output

Address of p variable is 3214864300


After adding 3: Address of p variable is 3214864312

As you can see, the address of p is 3214864300. But after adding 3 with p variable,
it is 3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it
increments 12. But if we were using 32-bit architecture, it was incrementing to 6
only, i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit OS.

Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. Subtracting
any number from a pointer will give an address. The formula of subtracting value
from the pointer variable is given below:

new_address= current_address - (number * size_of(data type))


32-bit

For 32-bit int variable, it will subtract 2 * number.

64-bit

For 64-bit int variable, it will subtract 4 * number.

example of subtracting value from the pointer variable on 64-bit architecture.

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}

Output

Address of p variable is 3214864300


After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the
previous address value.

However, instead of subtracting a number, we can also subtract an address from


another address (pointer). This will result in a number. It will not be a simple
arithmetic operation, but it will follow the following rule.

If two pointers are of the same type,

1. Address2 - Address1 = (Subtraction of two addresses)/size of data type whic


h pointer points

example to subtract one pointer from an another.

#include<stdio.h>
void main ()
{
int i = 100;
int *p = &i;
int *temp;
temp = p;
p = p + 3;
printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
}

Output
Pointer Subtraction: 1030585080 - 1030585068 = 3
Illegal arithmetic with pointers

There are various operations which can not be performed on pointers. Since, pointer
stores address hence we must ignore the operations which may lead to an illegal
address, for example, addition, and multiplication. A list of such operations is given
below.

o Address + Address = illegal


o Address * Address = illegal
o Address % Address = illegal
o Address / Address = illegal
o Address & Address = illegal
o Address ^ Address = illegal
o Address | Address = illegal
o ~Address = illegal

Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
Normally, a pointer contains the address of a variable. When we define a pointer to
a pointer, the first pointer contains the address of the second pointer, which points
to the location that contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by


placing an additional asterisk in front of its name. For example, the following
declaration declares a pointer to a pointer of type int −
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that
value requires that the asterisk operator be applied twice.

#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);

return 0;
}

When the above code is compiled and executed, it produces the following result −
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

Passing pointers to a function


• This allows data items within the calling portion, to be accessed by
the function, altered within the function and then returned to the
calling portion of the program in altered form
• This is referred to as passing arguments by reference. Arrays are
passed to functions by reference.
•When pointers are used as arguments to a function, the function
prototypes are like
void fun1 (int *p, int *q);
void fun1 (int *, int * );

Call by value

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.

main()

{ int a,b;

fun1(a,b);

Formal argument declaration

Fun1 (int a, int b)

Call by Value Example: Swapping the values of the two variables

#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printin
g the value of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of
actual parameters do not change by changing the formal
parameters in call by value, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); //
Formal parameters, a = 20, b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference

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 are
performed on the value stored at the address of the actual parameters, and the
modified value gets stored at the same address.

main()

{ int a,b;

fun1(&a, &b);

Formal argument declaration

Fun1 (int *a, int *b)

Call by reference Example: Swapping the values of the two variables

#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printin
g the value of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values o
f actual parameters do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
// Formal parameters, a = 20, b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference


Call by value Call by reference

A copy of the value is passed into the An address of value is passed into the
function function

Changes made inside the function is Changes made inside the function validate
limited to the function only. The values of outside of the function also. The values of the
the actual parameters do not change by actual parameters do change by changing the
changing the formal parameters. formal parameters.

Actual and formal arguments are created Actual and formal arguments are created at
at the different memory location the same memory location
Pointer And One-Dimensional Arrays
An array is a set of consecutive locations, having a common name and each location is identified
by an index number.
The name of the array is the beginning address of the array, called the base address of the array.
ie, it is the address of the first element. The array name is referred to as an address constant. The
array name is really a pointer to the 1st element in the array.

Both a and &a[0] is the same ie., base address(2010). Array name can be used as a pointer and
an integer value to represent the offset from the base address.

Address Value
&a[0] a+0 *(a+0) a[0] 11
&a[1] a+1 *(a+1) a[1] 12
&a[2] a+2 *(a+2) a[2] 13

In general
a+i denotes address of ith element
*(a+i) denotes the value at the address(a+i) which is same as a[i]
The address of an array cannot be altered using expressions like ++a.
The subscript notation is converted by compiler to pointer notation. So, if pointer notation is
used in programs , the programs work faster since no conversion is needed.

Processing 1D array using pointer notation


void main()
{ int i, n, a[15];
printf(“Enter the no.of elements to be stored”);
scanf(“%d”,&n);
for (i=0;i<n;i++)
{ printf(“enter the element”);
scanf(“%d”, a+i);
}
for (i=0;i<n;i++)
printf(“%d\t”, *(a+i));
}

Accessing elements of an array through a pointer


void main()
{
int i, *p, a[7] = { 11,12,13,14,15,16,17};
p=a; /* no need for & since array name itself is an address */
for(i=0; i<7 ; i++)
{ printf(“%d”, *p);
p++;
}
}
Pointers And 2D Arrays

2D array is an array of 1D arrays.


A gives the base address and its first element is the 1st 1D array . So, a is a pointer to its 1st 1D
array.
1D array itself is a pointer, so a can be considered as a pointer to pointer.
So, a+0(a[0]) is address of 1st array, a+1(a[1]) address of 2nd and so on.
*(a+0) gives the content at address a+0 which is a 1D array.

To get address of 0th element in the a+0 th array *(a+0) +0 .


Content at this address is *(*(a+0)+0) a[0][0].
In general a[i][j]= *(*(a+i)+j).
Program 1
void main()
{
int a[10][10], i, j, r, c;
printf(“Enter the number of rows and columns”);
scanf(“%d %d”,&r,&c);
for(i=0; i<r; i++)
for(j=0; j<c; j++)
scanf(“%d”, &a[i][j]);
for(i=0;i<r;i++)
{
for(j=0; j<c; j++)
printf(“%d\t”, a[i][j]);
printf(“\n”);
}
}
Program 2
void main()
{
int a[10][10], i, j, r, c;
printf(“Enter the number of rows and columns”);
scanf(“%d %d”,&r,&c);
for(i=0; i<r; i++)
for(j=0; j<c; j++)
scanf(“%d”, *(a+i)+j);
for(i=0;i<r;i++)
{
for(j=0; j<c; j++)
printf(“%d\t”, *(*(a+i)+j) );
printf(“\n”);
}
}

Pointer To an Array
int (*x) [20] – means x is defined to be a pointer to a group of contiguous , 1 D array, 20 element
integer arrays .
x points to the 1st 20 element array which is the 0th row of the original 2D array.
x+1 points to the 2nd 20 element array which is the 1st row of the original 2D array and so on.

Array elements can be referred as *(*x+i)+j)

In this example the pointer to array (ptr) incremented is shifted forward by 10 bytes which is the
base size .
*p gives the value 3, but *ptr gives 3000 which is the base address of array to which it points.

main()
{ int *p , (*ptr)[5], arr[5];
p=arr;
ptr=arr;
printf(“p= %u ptr= %u\n”, p, ptr);
p++;
ptr++;
printf(“p= %u ptr= %u”, p, ptr);
}
Output
p= 3000 ptr=3000
p= 3002 ptr=3010

Pointers and strings


• A char pointer can be initialized with a string constant
• char *p = “Aluva”;
• p is a pointer that points to the 1st character of the string constant.
• Comparison of the strings defined as arrays and strings defined as pointers
char str[]=“Mumbai”; char *ptr= “Chennai”;

• str being name of array is a constant pointer and the elements of the array
are as initialized.
• The string constant “Chennai “ is allocated space(8 bytes) somewhere in
memory and the starting address of this block is assigned to ptr.
• str always contains the same address, whereas ptr can contain any other
address
• . Eg. ptr=“ Delhi”;
Array of pointers to strings
• Array of pointers to string is array of char pointers, each pointer pointing to
a string. Each element of this array contains the base address of a string.
• char *arrp[]= {“white”,”red”, “green”, “yellow”, “blue”};
• The size can be specified, but here not specified and taken from the no.of
initializers
Program to sort strings alphabetically using array of pointers to strings
Pointer to Pointer (Multiple Indirection)
A pointer to a pointer is a form of multiple indirection or a chain of pointers.
Normally, a pointer contains the address of a variable. When we define a pointer to
a pointer, the first pointer contains the address of the second pointer, which points
to the location that contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by


placing an additional asterisk in front of its name. For example, following is the
declaration to declare a pointer to a pointer of type int −
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that
value requires that the asterisk operator be applied twice, as is shown below in the
example −

int main ()
{
int var;
int *ptr;
int **pptr;

var = 3000;
ptr = &var;
pptr = &ptr;
printf( "Value of var : %d\n",var);
printf ( "Value available at *ptr : %d\n",*ptr);
printf ("Value available at **pptr : %d",**pptr );
return 0;
}

Dynamic memory allocation


• In programs memory locations for variables were allocated at compile time.
This type of memory allocation is known as static memory allocation. We used
fixed sized arrays, which may or may not be big enough.
• There is a possibility of (1) overflow since no array bounds are checked and
(2) wastage of space due to large size declared.
• Once allocated, the size of array cannot be altered at runtime.
• Dynamic memory allocation overcomes all these drawbacks. Memory is
allocated at runtime.
• Memory allocated can be released, increased or decreased based on
requirement in the application
• The memory is allocated in heap

• The standard C library has built in library functions for dealing with
dynamic memory allocation. The prototypes of those functions are included in
header files alloc.h and stdlib.h

• malloc- used to allocate a block of contiguous memory of requested size and


returns a pointer to the 1st byte of the block.

Syntax is
ptr= (data_type*)malloc(size);

where size is no.of bytes to be allocated and ptr is a pointer of type data_type,
which collects the address of the 1st byte of the memory allocated . The memory
block allocated will have garbage values. If allocation is unsuccessful, the function
returns NULL

• calloc – allocates multiple blocks of memory, all of which are of same size
and returns pointer to the 1st byte of the first block.

Syntax is : ptr= (data_type*)calloc(n, size);

where n is the no.of blocks to be allocated and size is the no.of bytes in each
block and ptr is a pointer of type data_type, which collects the address of the 1st
byte of the first memory block allocated . The memory allocated will contain zeros.

• realloc – used to alter the size of memory block allocated.


Syntax is
ptr =(data_type*)realloc(ptr, newsize);

If realloc cannot make the old block of memory bigger ‘in place’ , it reallocates
to a new location where enough space is available and returns the address to ptr.
Data in the old block will also be shifted to the new block.

• free- used to release a block of memory, previously allocated.

Syntax is --- free(ptr);

where ptr is the pointer to the 1st byte of the block to be released. The memory
block is returned back to the free list within the heap.
Rearranging strings (dynamic allocation applied) (max of twenty strings each of
length 15 characters)

main()
{ char *x[20] , *temp; /* max of 20 ptrs*/
int i, j, n;
printf(“enter no.of strings”); scanf(“%d”, &n); for(i=0;i<n;i++)
{ /* allocate memory */
x[i]= (char*) malloc(15 *sizeof(char)) printf(“enter string”);
gets(x[i]);
}

for(i=0; i<n-1; i++) for(j=i+1; j< n; j++)


if (strcmp(x[i],x[j])>0)
{ /* pointer rearrangement */
temp= x[i]; x[i]= x[j]; x[j]= temp;
}
printf(“after sorting”); for(i=0;i<n;i++) puts(x[i]);
}
Structure
Structure is a user-defined data type in C language which allows us to
combine data of different types together. Structure helps to construct a
complex data type which is more meaningful. It is somewhat similar to
an Array, but an array holds data of similar type only. But structure on the
other hand, can store data of any type, which is practical more useful.

For example: If I have to write a program to store Student information,


which will have Student's name, age, branch, permanent address, father's
name etc, which included string values, integer values etc, how can I use
arrays for this problem, I will require something which can hold data of
different types together.

In structure, data is stored in form of records.

Defining a Structure
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 −
struct [structure tag] {

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 int i; 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];
int book_id;
} b1,b2;

Or
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

Now write given code inside the main() function.

struct Books b1,b2;

The variables b1 and b2 can be used to access the values stored in the structure.

Accessing Structure Members


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.

Let's see an example of the structure in C language to store many employees


information.

#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.salary=56000;

//store second employee information


e2.id=102;
strcpy(e2.name, "James Bond");
e2.salary=126000;

//printing first employee information


printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);

//printing second employee information


printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
return 0;
}

Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized
at compile time.
struct Patient
{
float height;
int weight;
int age;
};

struct Patient p1 = { 180.75 , 73, 23 }; //initialization

or

struct Patient p1;


p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

c language does not permit the initialization of individual structure members


within the template. The initialization mut be done only in the declaration of
the actual variables. Note that compile time initialization of the structure
variable must have the following elements:
1. The keyword struct
2. The structure tag name
3. The name of the variable to be declared
4. The assignment operator =
5. A set of values for the members of the structure variables, separated by
commas and enclosed in braces
6. A terminating semicolon.

Copying and Comparing Structure Variables

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.

Operations on structure
• Accessing members with dot operator e.empno=10; strcpy(e.name,
“Ram”);
• Assigning one structure variable to another of same type struct emp
e1,e2; e2=e1;
• Knowing the size of a structure variable using sizeof() operator
printf(“%d”, sizeof(e));
• Size of a structure is the sum of sizes of its members.
• Checking whether two structure variables of same type are equal or not
equal using == and != All members of 1st structure variable are checked
for equality with the corresponding members of 2nd variable and returns
one 1 if they are equal , otherwise 0. All members of 1st structure variable
are checked for inequality with the corresponding members of 2nd
variable and returns one 1 if they are unequal , otherwise 0.
Array of Structures
An array of structres 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.

• The most common use of structure in C programming is an array of


structures.
• To declare an array of structure, first the structure must be defined and
then an array variable of that type should be defined.
• For Example − struct book b[10]; //10 elements in an array of structures
of type ‘book’
Example
The following program shows the usage of array of structures.that stores
information of 5 students and prints it.
1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
5. char name[10];
6. };
7. int main(){
8. int i;
9. struct student st[5];
10. printf("Enter Records of 5 students");
11. for(i=0;i<5;i++){
12. printf("\nEnter Rollno:");
13. scanf("%d",&st[i].rollno);
14. printf("\nEnter Name:");
15. scanf("%s",&st[i].name);
16. }
17. printf("\nStudent Information List:");
18. for(i=0;i<5;i++){
19. printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
20. }
21. return 0;
22. }

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

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

Arrays within structures

▪ A structure can also contain array members just like normal members
such int, float
▪ We can declare an array if we need to store multiple values inside structure.
▪ Structure may include as many array members as we require.
▪ Syntax for declaring array within structure is not different than the
conventional syntax. The only difference is that it is declared inside the
structure.

▪ Consider the following example for storing student’s information where we


have declared an array of mark to store marks of six subjects and display on
the screen.

▪ Since we need to store marks for six subjects, we have to use looping structure
but the same is not true for character array of one dimension.

Array within Structure Example:

#include "stdio.h"

#include "conio.h"

#include "string.h"

struct student

int rno;

char name[20]; // Character array

int mark[6]; // Integer Array with six elements

float per;

};

void main()

{
struct student s1; // structure variable declaration

int tot = 0;

clrscr();

// individual member initialization.

printf(“\n Enter Student Roll No :”);

scanf(“%d”, &s1.rno);

printf(“\n Enter Student Name :”);

gets(s1.name);

// read marks for six subjects using loop

for(i = 0 ; i < 6 ; i++ )

printf(“\n Enter Subject %d mark :”,i+1);

scanf(“%d”, &s1.mark[i]);

tot = tot + s1.mark[i];

}
// calculate percentage

s1.per = tot/6 ;

printf(“\n Roll No : %d\t Name : %s”,s1.rno, s1.name);

for( i = 0 ; i < 6 ; i++ ) // display marks

printf(“\n%d”,s1.mark[i]);

printf(“\nTotal : %d\t Percentage : %.2f”,tot, s1.per );

getch();

Purpose of Array within Structure


When you find yourself to store a string value, then you have to go for
array within structure. because your name comes under character data
type alone, thus array is capable of storing data of same data type
User defined structure types
The C programming language provides a keyword called typedef, which you
can use to give a type a new name. Following is an example to define a
term BYTE for one-byte numbers −
typedef unsigned char BYTE;
After this type definition, the identifier BYTE can be used as an abbreviation
for the type unsigned char, for example..
BYTE b1, b2;
By convention, uppercase letters are used for these definitions to remind the
user that the type name is really a symbolic abbreviation, but you can use
lowercase, as follows −
typedef unsigned char byte;
You can use typedef to give a name to your user defined data types as well.
For example, you can use typedef with structure to define a new data type and
then use that data type to define structure variables directly as follows –

#include <stdio.h>
#include <string.h>

typedef struct Books {


char title[50];
char author[50];
char subject[100];
int book_id;
} Book;

int main( ) {

Book book;

strcpy( book.title, "C Programming");


strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;

printf( "Book title : %s\n", book.title);


printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);

return 0;
}
When the above code is compiled and executed, it produces the following
result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407

Structure within a structure


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.

The structure can be nested in the following ways.

By separate structure

By Embedded structure

1) Separate structure
Here, we create two structures, but the dependent structure should be
used inside the main structure as a member. Consider the following
example.

struct Date

int dd;

int mm;

int yyyy;

};

struct Employee

int id;

char name[20];

struct Date doj;

}emp1;

As you can see, doj (date of joining) is the variable of type Date. Here
doj is used as a member in Employee structure. In this way, we can use
Date structure in many structures.

2) Embedded structure
The embedded structure enables us to declare the structure inside the
structure. Hence, it requires less line of codes but it can not be used in
multiple data structures. Consider the following example.

struct Employee

int id;

char name[20];

struct Date

int dd;

int mm;

int yyyy;

}doj;

}emp1;

Accessing Nested Structure

We can access the member of the nested structure by


Outer_Structure.Nested_Structure.member as given below:

e1.doj.dd

e1.doj.mm

e1.doj.yyyy
C Nested Structure example

Let's see a simple example of the nested structure in C language.

#include <stdio.h>

#include <string.h>

struct Employee

int id;

char name[20];

struct Date

int dd;

int mm;

int yyyy;

}doj;

}e1;

int main( )

//storing employee information

e1.id=101;

strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array


e1.doj.dd=10;

e1.doj.mm=11;

e1.doj.yyyy=2014;

//printing first employee information

printf( "employee id : %d\n", e1.id);

printf( "employee name : %s\n", e1.name);

printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n",


e1.doj.dd,e1.doj.mm,e1.doj.yyyy);

return 0;

structs and Pointers

Here's how you can create pointers to structs.

struct name {

member1;

member2;

};
int main()

struct name *ptr, Harry;

Here, ptr is a pointer to struct.

Example: Access members using Pointer

To access members of a structure using pointers, we use the ->


operator.

#include <stdio.h>

struct person

int age;

float weight;

};

int main()

struct person *personPtr, person1;


personPtr = &person1;

printf("Enter age: ");

scanf("%d", &personPtr->age);

printf("Enter weight: ");

scanf("%f", &personPtr->weight);

printf("Displaying:\n");

printf("Age: %d\n", personPtr->age);

printf("weight: %f", personPtr->weight);

return 0;

In this example, the address of person1 is stored in the personPtr pointer


using personPtr = &person1;.

Now, you can access the members of person1 using the personPtr
pointer.

Passing structure to function


Just like other variables, a structure can also be passed to a function. We may
pass the structure members into the function or pass the structure variable at
once. Consider the following example to pass the structure variable employee
to a function display() which is used to display the details of an employee.

1. #include<stdio.h>
2. struct address
3. {
4. char city[20];
5. int pin;
6. char phone[14];
7. };
8. struct employee
9. {
10. char name[20];
11. struct address add;
12. };
13. void display(struct employee);
14. void main ()
15. {
16. struct employee emp;
17. printf("Enter employee information?\n");
18. scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.
add.phone);
19. display(emp);
20. }
21. void display(struct employee emp)
22. {
23. printf("Printing the details....\n");
24. printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.
phone);
25. }

Passing individual members to function


#include <stdio.h>
struct student
{
int reg_no;
char name [20] ;
float percent;
};
void display (int, char [] , float) ;
int main (void)
{
struct student s;
printf ("Enter reg_no, name and percent \n" ) ;
scant ("%d%s%f" , &S.reg_no , s.name, &s .percent) ;
display (s .reg_no, s.name, s .percent) ;
return 0;
void display (int reg_no, char name [] , float percent)
{
printf ("%6d%15s%6 .2f" , reg_no, name, percent) ;
}

Passing an entire structure to a function

#include <stdio.h>
struct student
{
int reg_no;
char name [20] ;
float percent;
);
void display(struct student) ;
int main (void)
{
struct student s;
printf ("Enter reg_no, name and percent \n");
scanf ("%d%s%f", &s.reg_no, s.name, &s.percent);
display (s) ;
return 0;
}
void display(struct student s)
{
printf ("%6d%15s%6.2f \nn, s.reg_no, s.name, s.percent) ;
}

passing address of a structure to a function


#include <stdio.h>
struct student
{
int reg_no ;
char name [ 2 0 ] ;
float percent;
};
void display( struct student* );

int main (void)


struct student s;
printf ("Enter reg_no, name and percent \n");
scanf ("%d%s%f", &s.reg_no, s.name, &s.percent);
display (&s) ;
return 0;
}
void display (struct student *sp)
{
printf ("%6d%15s%6.2f \n", sp->reg_no, sp->name, sp->percent);
}

Passing an array of structures to function


#include <stdio.h>
struct emp
{
int empno;
char name [20];
float salary;
};
void display (struct emp [] , int );
int main (void)
{
struct emp e[10] ;
int i,n;
printf ( "Enter number of Employees \n" );
scanf ( " %d",&n) ;
printf ( "Enter %d employees details \n",n );
for (i = 0;i<n;i++ )
scanf("%d%s%f", &e[i].empno, e[i].name,&e[i].salary);
priritf ( "The list of employees \n" ) ;
display (e,n);
return 0 ;
}
void display (struct emp e[] , int n) {
int i ;
for ( i=0;i<n;i++ )
Printf("%6d%15s%8.2f\n",e[i].empno, e[i].name, e[i].salary);
}
Self Referential Structures
Self Referential structures are those structures that have one or more pointers
which point to the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-
referential in nature.
Example:

struct node {

int data1;

char data2;

struct node* link;

};

int main()

struct node ob;

return 0;

}
Union
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 int i; 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 {
int i;
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>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}
When the above code is compiled and executed, it produces the following
result −
Memory size occupied by data : 20

Accessing Union Members


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>
union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

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);

return 0;
}
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>
union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

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);

return 0;
}
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.

Union within structure


union utemp

{
int i;

float f;

double d;

};

struct stemp

int type;

char name[20];

union temp u;

};

Arrays within union


Union student

Int reg_no;

Char name[20];

};

MODULE 5
1. Introduction to Files in C:
A File is a collection of data stored in the secondary memory. So far data was entered
into the programs through the keyboard. So Files are used for storing information that can be
processed by the programs. Files are not only used for storing the data, programs are also stored
in files. In order to use files, we have to learn file input and output operations. That is, how data
is read and how to write into a file.
A Stream is the important concept in C. The Stream is a common, logical interface to the
various devices that comprise the computer. So a Stream is a logical interface to a file. There are
two types of Streams, Text Stream and Binary Stream. A Text File can be thought of as a stream
of characters that can be processed sequentially. It can only be processed in the forward
direction.

2. Using Files in C:
To use a file four essential actions should be carried out. These are,
a. Declare a file pointer variable.
b. Open a file using the fopen() function.
c. Process the file using suitable functions.
d. Close the file using the fclose() and fflush() functions.

2.1. Declaration of file pointer:


A pointer variable is used to points a structure FILE. The members of the FILE structure are
used by the program in various file access operation, but programmers do not need to concerned
about them.
FILE *file_pointer_name;
Eg : FILE *fp;

2.2. Opening a file


To open a file using the fopen() function. Its syntax is,
FILE *fopen(const char *fname,const char* mode);
const char *fname represents the file name. The file name is like “D:\\501\example.txt”.
Here D: is a drive, 501 is the directory, example.txt is a file name.
const char *mode represents the mode of the file. It has the following values.

Mode Description
r Opens a text file in reading mode

w Opens or create a text file in writing mode

a Opens a text file in append mode

r+ Opens a text file in both reading and writing mode

w+ Opens a text file in both reading and writing mode

a+ Opens a binary file in reading mode

rb Opens a binary file in reading mode

wb Opens or create a binary file in writing mode

Ab Opens a binary file in append mode

rb+ Opens a binary file in both reading and writing mode

wb+ Opens a binary file in both reading and writing mode

ab+ Opens a binary file in both reading and writing mode

Difference between write mode and append mode is,


Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are
used to write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will not
happen. Append mode is used to append or add data to the existing data of file(if any). Hence,
when
you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the
file.
2.3. Closing and Flushing Files
The file must be closed using the fclose() function. Its prototype is ,
int fclose(FILE *fp);
The argument fp is the FILE pinter associated with the stream. Fclose() returns 0 on success and
-1
on error.
fflush() used when a file’s buffer is to be written to disk while still using the file. Use of
fflushall() to flush the buffers of all open streams. The prototype of these two functions are,
int flushall(void);
int fflush(FILE *fp);
Examples:
/* Program to check whether the file exist or not */
void main()
{
FILE *fp;
char *x;
clrscr();
printf("\n enter the file name : ");
gets(x);
fp=fopen(x,"r");
if(fp==NULL)
{
printf("The file ---%s--- is not found in the present directory",x);
}
else
{
printf("The file ---%s--- is found in the present directory",x);
}
fclose(fp);
getch();
}
3. Character input / output:
Two functions are used to read the character from the file and write it into another file. These
functions are getc() & putc() functions.
Its prototype is,
int getc(FILE *file_pointer);
putc( char const_char, FILE *file_pointer);

3.1Detecting the end of a file:


When reading from a text-mode file character by character, one can look for the end-of-file
character. The symbolic constant EOF is defined in stdio.h as -1, a value never used by a real
character.
Eg: while((c=getc(fp)!=EOF). This is the general representation of the End Of the File.
Examples:
/* Read a string into a text file */
void main()
{
FILE *fp;
char text[80];
int i;
clrscr();
fp=fopen("Sample.txt","w");
printf("\n Enter the text : ");
gets(text);
for(i=0;i<strlen(text);i++) // Read a stream of charcters
putc(text[i],fp);
if(fp!=NULL)
printf("\n The string copied into a text file ");
fclose(fp);
getch();
}
4.File Handling Functions
File Handling is the storing of data in a file using a program. In C programming language, the
programs store results, and other data of the program to a file using file handling in C. Also, we
can extract/fetch data from a file to work with it in the program.

The operations that you can perform on a File in C are −

● Creating a new file

● Opening an existing file

● Reading data from an existing file

● Writing data to a file

● Moving data to a specific location on the file

● Closing the file

Creating or opening file using fopen()


The fopen() function is used to create a new file or open an existing file in C. The fopen function
is defined in the stdio.h header file.

Now, lets see the syntax for creation of a new file or opening a file
file = fopen(“file_name”, “mode”)
This is a common syntax for both opening and creating a file in C.

Parameters
file_name − It is a string that specifies the name of the file that is to be opened or created using
the fopen method. mode: It is a string (usually a single character ) that specifies the mode in
which the file is to be opened. There are various modes available to open a file in C, we will
learn about all of them later in this article.

When will a file be created?


The fopen function will create a new file when it will not find any file of the specified name in
the specified location. Else, if the file is found it will be opened with the mode specified.

Let’s see can example which will make the concept clear, Suppose we are opening a file named
hello.txt using the fopen function. The following will be the statement,

file = fopen(“hello.txt”, “w”)


This will search for a file named hello.txt in the current directory. If the file exists, it will open
the file otherwise it will create a new file named “hello.txt” and open it with write mode
(specified using “w”).

Now, let’s see all types of modes that are available for us to read or write a file in C, and see
code snippets that will show sample runs of the code.

Mode = “r” − open for reading, this mode will open the file for reading purpose only, i.e. the
contents can only be viewed, nothing else like edits can be done to it.

This mode cannot create a new file and open() returns NULL, if we try to create a new file using
this mode.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "r")){
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using r mode");
fclose(file);
return 0;
}
Output
File opened successfully in read mode
We have created a file named hello.txt in our current directory but if we try to access other file
then we will get “The file is not present! cannot create a new file using r mode” as output.

Mode = “rb” − open for reading in binary mode, this mode will open the file for reading in
binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to
it.

This mode cannot create a new file and open() returns NULL, if we try to create a new file using
this mode.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("program.txt", "rb")){
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using rb mode");
fclose(file);
return 0;
}
Output
The file is not present! cannot create a new file using rb mode

Mode = “w” − open for writing only, this mode will open the file if present in the current
directory for writing only i.e. reading operation cannot be performed. If the file is not present in
the current directory, the program will create a new file and open it for writing.

If we open a file that contains some text in it, the contents will be overwritten.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("helo.txt", "w")){
printf("File opened successfully in write mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in write mode or a new file is created
You can see here, we have tried to open file “helo.txt” which is not present in the directory, still
the function returned the success message because it has create a file named “helo.txt”.

Mode = “wb” − open for writing in binary mode, this mode will open the file if present in the
current directory for writing in binary mode i.e. reading operation cannot be performed. If the
file is not present in the current directory, the program will create a new file and open it for
writing in binary mode.

If we open a file that contains some text in it, the contents will be overwritten.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "wb")){
printf("File opened successfully in write in binary mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in write in binary mode or a new file is created
Mode = “a” − open for append only, this mode will open the file if present in the current
directory for writing only i.e. reading operation cannot be performed. If the file is not present in
the current directory, the program will create a new file and open it for writing. If we open a file
that contains some text in it, the contents will not be overwritten; instead the new text will be
added after the existing text in the file.

Example
Live Demo

#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "a")){
printf("File opened successfully in append mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in append mode or a new file is created
Mode = “ab” − open for append in binary, this mode will open the file if present in the current
directory for writing in binary only i.e. reading operation cannot be performed. If the file is not
present in the current directory, the program will create a new file and open it for writing in
binary.

If we open a file that contains some text in it, the contents will not be overwritten; instead the
new text will be added after the existing text in the file.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "ab")){
printf("File opened successfully in append in binary mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in append in binary mode or a new file is created
Mode = “r+” − open for reading and writing both, this mode will open the file for both reading
and writing purposes i.e. both read and write operations can be performed to the file.

This mode cannot create a new file and open() returns NULL, if we try to create a new file using
this mode.

If we open a file that contains some text in it and write something, the contents will be
overwritten.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "r+")){
printf("File opened successfully in read and write both");
}
else
printf("The file is not present! cannot create a new file using r+ mode");
fclose(file);
return 0;
}
Output
File opened successfully in read and write both
We have created a file named hello.txt in our current directory but if we try to access another file
then we will get “The file is not present! cannot create a new file using r+ mode” as output.

Mode = “rb+” − open for reading in binary mode, this mode will open the file for reading in
binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to
it.

This mode cannot create a new file and open() returns NULL, if we try to create a new file using
this mode.

If we open a file that contains some text in it and write something, the contents will be
overwritten.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("program.txt", "rb+")){
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using rb+ mode");
fclose(file);
return 0;
}
Output
The file is not present! cannot create a new file using rb+ mode
Mode = “w” − open for writing and reading, this mode will open the file if present in the current
directory for writing and reading operation both. If the file is not present in the current directory,
the program will create a new file and open it for reading and writing.
If we open a file that contains some text in it, the contents will be overwritten.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("helo.txt", "w+")){
printf("File opened successfully in read-write mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in read-write mode or a new file is created
You can see here, we have tried to open file “helo.txt” which is not present in the directory, still
the function returned the success message because it has create a file named “helo.txt”.

Mode = “wb+” : open for writing and reading in binary mode, this mode will open the file if
present in the current directory for writing and reading in

binary mode. If the file is not present in the current directory, the program will create a new file
and open it for reading and writing in binary mode. If we open a file that contains some text in it,
the contents will be overwritten.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "wb+")){
printf("File opened successfully in read-write in binary mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in read-write in binary mode or a new file is created
Mode = “a+” − open for read and append, this mode will open the file if present in the current
directory for both reading and writing. If the file is not present in the current directory, the
program will create a new file and open it for reading and writing.

If we open a file that contains some text in it, the contents will not be overwritten; instead the
new text will be added after the existing text in the file.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "a+")){
printf("File opened successfully in read-append mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in read-append mode or a new file is created

Mode = “ab+” − open for read and append in binary, this mode will open the file if present in the
current directory for both reading and writing in binary. If the file is not present in the current
directory, the program will create a new file and open it for reading and writing in binary. If we
open a file that contains some text in it, the contents will not be overwritten; instead the new text
will be added after the existing text in the file.

Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "ab+")){
printf("File opened successfully in read-append in binary mode or a new file is created");
}
else
printf("Error!”);
fclose(file);
return 0;
}
Output
File opened successfully in read
Reading Data for from an existing file
We can read content of a file in c using the fscanf() and fgets() and fgetc() functions. All are used
to read contents of a file. Let’s see the working of each of the function −

fscanf()
The fscanf() function is used to read character set i.e strings from the file. It returns the EOF,
when all the content of the file are read by it.

Syntax
int fscanf(FILE *stream, const char *charPointer[])
Parameters
FILE *stream: the pointer to the opened file.
const char *charPointer[]: string of character.
Example
#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
while(fscanf(file,"%s", str)!=EOF){
printf("%s", str);
}
}
else
printf("Error!”);
fclose(file);
return 0;
}
Output
Helloworld
fgets()
The fget() function in C is used to read string from the stream.

Syntax
char* fgets(char *string, int length, FILE *stream)
Parameter
char *string: It is a string which will store the data from the string.
int length: It is an int which gives the length of string to be considered.
FILE *stream: It is the pointer to the opened file.
Example
#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
printf("%s", fgets(str, 50, file));
}
fclose(file);
return 0;
}
Output
Hello world
fgetc()
The fgetc() function in C is used to return a single character from the file. It gets a character from
the file and returns EOF at the end of file.

Syntax
char* fgetc(FILE *stream)
Parameter
FILE *stream: It is the pointer to the opened file.
Example
#include <stdio.h>
int main(){
FILE * file;
char str;
if (file = fopen("hello.txt", "r")){
while((str=fgetc(file))!=EOF)
printf("%c",str);
}
fclose(file);
return 0;
}
Output
Hello world
Writing Data to a file in C
We can write data to a file in C using the fprintf(), fputs(), fputc() functions. All are used to write
contents to a file.

Let’s see the working of each of the function −

fprintf()
The fprintf() function is used to write data to a file. It writes a set of characters in a file.

Syntax
int fprintf(FILE *stream, char *string[])
Parameters
FILE for *stream: It is the pointer to the opened file.
char *string[]: It is the character array that we want to write in the file.
Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
if(fprintf(file, "tutorials Point”) >= 0)
printf("Write operation successful");
}
fclose(file);
return 0;
}
Output
Write operation successful
fputf()
The fputf() function in C can be used to write to a file. It is used to write a line (character line) to
the file.

Syntax
int fputs(const char *string, FILE *stream)
Parameters
Constant char *string[]: It is the character array that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
Example
Live Demo

#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
if(fputs("tutorials Point", file) >= 0)
printf("String written to the file successfully...");
}
fclose(file);
return 0;
}
Output
String written to the file successfully…
fputc()
The fputc() function is used to write a single character to the file.

Syntax
int fputc(char character , FILE *stream)
Parameters
char character : It is the character that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
fputc('T', file);
}
fclose(file);
return 0;
}
Output
‘T’ is written to the file.
fclose()
The fclose() function is used to close the open file. We should close the file after performing
operations on it to save the operations that we have applied to it.

Syntax
fclose(FILE *stream)
Parameters
FILE for *stream: It is the pointer to the opened file.
Example
#include <stdio.h>
int main(){
FILE * file;
char string[300];
if (file = fopen("hello.txt", "a+")){
while(fscanf(file,"%s", string)!=EOF){
printf("%s", string);
}
fputs("world", file);
}
fclose(file);
return 0;
}
Output
Hello
File contains
Helloworld
5.Formatted input/output functions

Formatted console input/output functions are used to take one or more inputs from the user at
console and it also allows us to display one or multiple values in the output to the user at the
console.
Some of the most important formatted console input/output functions are -

Functions
scanf()
This function is used to read one or multiple inputs from the user at the console.

printf()
This function is used to display one or multiple values in the output to the user at the console.

sscanf()
This function is used to read the characters from a string and stores them in variables.

sprintf()
This function is used to read the values stored in different variables and store these values in a
character array.

7.Binary Files
A binary file is a file that uses all 8 bits of a byte for storing the information .It is the form which
can be interpreted and understood by the computer.

The only difference between the text file and binary file is the data contain in text file can be
recognized by the word processor while binary file data can’t be recognized by a word processor.

1.wb(write)
this opens a binary file in write mode.
SYNTAX:
fp=fopen(“data.dat”,”wb”);
2.rb(read)
this opens a binary file in read mode
SYNTAX:
fp=fopen(“data.dat”,”rb”);
3.ab(append)
this opens a binary file in a Append mode i.e. data can be added at the end of file.
SYNTAX:
fp=fopen(“data.dat”,”ab”);
4.r+b(read+write)
this mode opens preexisting File in read and write mode.
SYNTAX:
fp=fopen(“data.dat”,”r+b”);
5.w+b(write+read)
this mode creates a new file for reading and writing in Binary mode.
SYNTAX:
fp=fopen(“data.dat”,”w+b”);
6.a+b(append+write)
this mode opens a file in append mode i.e. data can be written at the end of file.
SYNTAX:
fp=fopen(“data.dat”,”a+b”);
Additional features of C

Enumeration
Enumeration is a user defined datatype in C language. It is used to assign names to the integral
constants which makes a program easy to read and maintain. The keyword “enum” is used to
declare an enumeration.
Here is the syntax of enum in C language,
enum enum_name{const1, const2, ....... };
The enum keyword is also used to define the variables of enum type. There are two ways to define
the variables of enum type as follows.
enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};
enum week day;
For example:

enum fruits{mango, apple, strawberry, papaya};


The default value of mango is 0, apple is 1, strawberry is 2, and papaya is if we
want to change these default values, then we can do as given below:
enum fruits
{
mango=2,
apple=1,
strawberry=5,
papaya=7,
};

Enumerated type declaration


we need to declare the variable of a pre-defined type such as int, float, char, etc. Similarly, we can
declare the variable of a user-defined data type, such as enum. Let's see how we can declare the
variable of an enum type.

Suppose we create the enum of type status as shown below:


enum status{false,true};

Now, we create the variable of status type:


enum status s; // creating a variable of the status type.

In the above statement, we have declared the 's' variable of type status.

To create a variable, the above two statements can be written as:

enum status{false,true} s;
In this case, the default value of false will be equal to 0, and the value of true will be equal to 1.

simple program of enum.

#include <stdio.h>
enum weekdays{Sunday=1,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
int main()
{
enum weekdays w; // variable declaration of weekdays type
w=Monday; // assigning value of Monday to w.
printf("The value of w is %d",w);
return 0;
}

Output

Why do we use enum?


The enum is used when we want our variable to have only a set of values. For example, we create
a direction variable. As we know that four directions exist (North, South, East, West), so this
direction variable will have four possible values. But the variable can hold only one value at a
time. If we try to provide some different value to this variable, then it will throw the compilation
error.

The enum is also used in a switch case statement in which we pass the enum variable in a switch
parenthesis. It ensures that the value of the case block should be defined in an enum.

Some important points related to enum

o The enum names available in an enum type can have the same value.

o If we do not provide any value to the enum names, then the compiler will automatically
assign the default values to the enum names starting from 0.
o We can also provide the values to the enum name in any order, and the unassigned names
will get the default value as the previous one plus one.
o The values assigned to the enum names must be integral constant, i.e., it should not be of
other types such string, float, etc.
o All the enum names must be unique in their scope, i.e., if we define two enum having same
scope, then these two enums should have different enum names otherwise compiler will
throw an error.

Bitwise Operator

The bitwise operators are the operators used to perform the operations on the data at the bit-level.
When we perform the bitwise operations, then it is also known as bit-level programming. It
consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the
calculations faster.
We have different types of bitwise operators in the C programming language. The following is the
list of the bitwise operators:

Operator Meaning of operator

& Bitwise AND operator

| Bitwise OR operator

^ Bitwise exclusive OR operator

~ One's complement operator (unary operator)

<< Left shift operator

>> Right shift operator

Let's look at the truth table of the bitwise operators.

X Y X&Y X|Y X^Y


0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 1

Bitwise AND operator

Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are
written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then
the output of the bitwise AND operation is 1; otherwise, the output would be 0.

For example,

We have two variables a and b. a =6; b=4; The binary representation of the above two variables are
given below: a = 0110 b = 0100 When we apply the bitwise AND operation in the above two varia
bles, i.e., a&b, the output would be: Result = 0100
Bitwise AND operator through the program.
#include <stdio.h>
int main() {
int a=6, b=14; // variable declarations
printf("The output of the Bitwise AND operator a&b is %d",a&b);
return 0;
}

In the above code, we have created two variables, i.e., 'a' and 'b'. The values of 'a' and 'b' are 6 and
14 respectively. The binary value of 'a' and 'b' are 0110 and 1110, respectively. When we apply
the AND operator between these two variables,

a AND b = 0110 && 1110 = 0110

Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are
written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the output
would be 1, otherwise 0.

For example,

We consider two variables, a = 23; b = 10; The binary representation of the above two variable
s would be: a = 0001 0111 b = 0000 1010 When we apply the bitwise OR operator in the above
two variables, i.e., a|b , then the output would be:
Result = 0001 1111

As we can observe from the above result that the bits of both the operands are compared one by
one; if the value of either bit is 1, then the output would be 1 otherwise 0.

The bitwise OR operator through a program.


#include <stdio.h>
int main()
{
int a=23,b=10; // variable declarations
printf("The output of the Bitwise OR operator a|b is %d",a|b);
return 0;
}
Output
The output of the Bitwise OR operator a|b is 31

Bitwise exclusive OR operator

Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides
of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then the output
would be 1, otherwise 0.

For example,

We consider two variables a and b,


a = 12;
b = 10;
The binary representation of the above two variables would be:
a = 0000 1100
b = 0000 1010
When we apply the bitwise exclusive OR operator in the above two variables (a^b), then the resu
lt would be:
Result = 0000 1110

As we can observe from the above result that the bits of both the operands are compared one by
one; if the corresponding bit value of any of the operand is 1, then the output would be 1 otherwise
0.

Bitwise exclusive OR operator through a program.

#include <stdio.h>
int main()
{
int a=12,b=10; // variable declarations
printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);
return 0;
}

Output
The output of the Bitwise exclusive OR operator a^b is 6

Command Line Arguments

The arguments passed from command line are called command line arguments. These arguments
are handled by main() function.

To support command line argument, you need to change the structure of main() function as given
below.
int main(int argc, char *argv[] )

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Example of command line arguments where we are passing one argument with file name.

#include <stdio.h>
void main(int argc, char *argv[] ) {
printf("Program name is: %s\n", argv[0]);
if(argc < 2)
{
printf("No argument passed through command line.\n");
}
else{
printf("First argument is: %s\n", argv[1]);
}
}

Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define
directive. There are two types of macros:

1. Object-like Macros
2. Function-like Macros
Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:

#define PI 3.14

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

#define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No. Macro Description

1 _DATE_ represents current date in "MMM DD YYYY" format.

2 _TIME_ represents current time in "HH:MM:SS" format.

3 _FILE_ represents current file name.


4 _LINE_ represents current line number.

5 _STDC_ It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example


#include<stdio.h>
int main(){
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
rintf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ );
return 0;
}

Output:

Date :July 11 2021

Time :10:12:32

Line :8

STDC :1

The macro is not less than similar to functions, but macro has built-in macro also. In C, the macro
is used to define any constant value or any variable with its value in the entire program that will
be replaced by this macro name, where macro contains the set of code that will be called when the
macro name is used in the program. The macro uses the “#define” directive to define the macro in
C programming language. This is very useful to save time and have less code writing.

Macro Caveats

⚫ Macro definitions are not stored in the object file. They are only active for the duration of a
single source file starting when they are defined and ending when they are undefined (using
#undef), redefined, or when the end of the source file is found.
⚫ Macro definitions you wish to use in multiple source files may be defined in an include file
which may be included in each source file where the macros are required.
⚫ When a macro with arguments is invoked, the macro processor substitutes the arguments into
the macro body and then processes the results again for additional macro calls. This makes
it possible, but confusing, to piece together a macro call from the macro body and from the
macro arguments.
⚫ Most experienced C programmers enclose macro arguments in parentheses when they are
used in the macro body. This technique prevents undesired grouping of compound
expressions used as arguments and helps avoid operator precedence rules overriding the
intended meaning of a macro.
⚫ While a macro may contain references to other macros, references to itself are not expanded.
Self-referencing macros are a special feature of ANSI Standard C in that the self-reference
is not interpreted as a macro call. This special rule also applies to indirectly self-referencing
macros (or macros that reference themselves through another macro).

Conditional Compilation (#if, #ifdef, #ifndef, #else, #elif, #endif, and defined)

Six directives are available to control conditional compilation. They delimit blocks of program
text that are compiled only if a specified condition is true. These directives can be nested. The
program text within the blocks is arbitrary and may consist of preprocessor directives, C
statements, and so on. The beginning of the block of program text is marked by one of three
directives:

⚫ #if
⚫ #ifdef
⚫ ifndef

Optionally, an alternative block of text can be set aside with one of two directives:

◆#else
◆#elif

The end of the block or alternative block is marked by the #endif directive.

If the condition checked by #if , #ifdef , or #ifndef is true (nonzero), then all lines between the
matching #else (or #elif ) and an #endif directive, if present, are ignored.
If the condition is false (0), then the lines between the #if , #ifdef , or #ifndef and
an #else , #elif , or #endif directive are ignored.

You might also like