0% found this document useful (0 votes)
146 views89 pages

2021 April C Prog

Uploaded by

b540kc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
146 views89 pages

2021 April C Prog

Uploaded by

b540kc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

INTELLISE IT C Programming Language

C Programming Language:
Binary Language
0 / 1
FALSE / TRUE
LOW / HIGH
OFF / ON
Machine Level Language / Binary
5 + 8 = 13+75
101 + 1000 = 1101
5000 + 8000 = 13000
0100011101110011110010101010 + 11010111001100110010101001 = 10110011111111111000010101
High level language (Programming Language)/ C Programming Language (English Alphabet/Digits)
Software program - Compiler
C Compiler - TurboC, Borland C, Microsoft C, IIT Bombay, Apple C, GCC (Code Blocks)
Assembly Language (Hexa-decimal. 0-9 A-F) / Middle Level / Intermediate Language
Machine Level Language / Binary / Low Level
English Language C Programming Language
1. Alphabets, digits, +, -, / , x English Language Alphabets
(A-Z, a-z), (0-9), (A-Z, a-z, 0-9), +, -, x , /, etc.
2. Words, numbers, Grammar Tokens, Keywords, Literals, values, constants, data, identifiers
3. Sentences, expressions Statements, instructions, commands, syntax
4. Paragraphs Functions
5. Chapter/Lessons Programs
History of C Programming Language:
C is a general purpose, high level, procedural, structure oriented, computer programming language.
Developed in 1972 by Dennis M. Ritchie and Brian Kernighan at the Bell Laboratories.
C is the successor of the B language which was introduced around the early 1970s.
In 1978 it got K&R standard and was publicly available.
The language is ASNI (American National Standard Institute) standardized in 1988.
C Program Structure:
A C program basically consists of the following parts:
● Preprocessor Commands
● Functions
● Variables
● Statements & Expressions
● Comments

First C Program:
#include<stdio.h>
void main( )
{
printf(“Hello All”);
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 1


INTELLISE IT C Programming Language

Tokens in C:
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string
literal, or a symbol.
For example, in the above shown C Program, the printf( ) statement (function) has various tokens in it, such
as,
printf(“Hello All”);
1. printf - name of the function (identifier)
2. (, “, ”, ), ; - all these are symbols
3. “Hello All” - string literal (value)
Semicolons:
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended
with a semicolon. It indicates the end of one logical entity.
Comments:
Comments are like helping text in your C program and they are ignored by the compiler.
C programming language has 2 types of comments:
1. Single line comment (//)
The text followed by 2 forward slash is commented out of the program. Means, C compiler does not read the
text given after the 2 forward slash.
Example:
//This is my first program
2. Multiline comments (/* … */)
The text enclosed within the forward slash and asterisk symbol (/*) and asterisk symbol and forward slash
(*/) is also commented out by the C compiler. Generally this type of comment is used to comment out multi
lines of text in your program.
Example:
/*This is my program.
I have developed it as my first C program.
The program was developed on 23rd April 2021*/
Identifiers:
A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier
starts with a letter A to Z, a to z, or an underscore (_) followed by zero or more letters, underscores, and digits
(0 to 9).
C does not allow punctuation characters such as !, @, #, $, %, ^, &, *, (, ), -, +, =, etc. within identifiers.
C is a case-sensitive programming language. That is why, A is not equal to a.
Keywords:
C programming language has a total of 32 keywords. Keywords are nothing but reserved words to which some
meaning is associated. These reserved words can not be used as constants or variables or any other identifier
names.
Literals/Constants:
The values, data, information on which we perform operations in our C program is known as constants.
Example:
18, 24, 2021, 3.14, 41.86, etc.
Data types:
Data types in C refer to an extensive system used for declaring variables (containers) of 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.
Sourabha Malve : 8605400907 https://www.intelliseit.com 2
INTELLISE IT C Programming Language

A. Basic types:
They are arithmetic types and are further classified into
1. Integer
Example: 18, 24, 2021, etc
2. Floating point.
Example: 3.14, 42.85, 98.5, -2.3, etc
3. Character.
Example: ‘A’, ‘+’, ‘f’, ‘5’, etc
B. 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.
C. The void type
The void type specifier indicates that no value is available
D. Derived types:
They are derived from any one data type those are stated above. They include
1. Pointer types
2. Array types
3. Structure types
4. Union types
5. Function types
Format Specifier:
The format specifiers are used in C for input and output purposes. Using this concept the compiler can
understand what type of data a variable can accept, store or print during the input and output operation.
Memory Memory Measurement Units:
1 binary bit = 0/1
8 bits = 1 byte
1024 bytes = 1 Kilobyte
1024 Kilobytes = 1 Megabyte
1024 Megabytes = 1 Gigabyte
1024 Gigabytes = 1 Terabyte
Integer Types:
Standard integer types include the following data types:
Sr. Type Storage Size Value Range Format Specifier
1. int 2 bytes or -32768 to 32767 %d
4 bytes -2147483648 to 2147483647
2. unsigned int 2 bytes or 0 to 65535 %u or %i
4 bytes 0 to 4294967295
3. long 4 bytes or -2147483648 to 2147483647 %l or %ld or %li
8 bytes -9223372036854775808 to
9223372036854775807
4. unsigned long 8 bytes 0 to 18446744073709551615 %lu

Floating-point types:
Standard floating-point types that store real numbers in them have the following types:
Sourabha Malve : 8605400907 https://www.intelliseit.com 3
INTELLISE IT C Programming Language

Sr. Type Storage Size Range Format Specifier


1. float (6 decimal places) 4 byte 1.2E-38 to 3.4E+38 %f
2. double (15 decimal places) 8 byte 2.3E-308 to 1.7E+308 %lf
3. long double (19 decimal places 12 bytes 3.4E-4932 to 1.1E+4932 %Lf

Character types:
Standard character type is used to store any one letter (A-Z)/(a-z), digit(0-9), symbol(+, -, *, /, !, @, #, $, %, ^,
&, (, ), {, }, [, ], <, >, ?, etc) and so on, that is, all the keys present on the keyboard can be stored into character
type.
For character types C compiler uses ASCII code to store the binary of character value.
ASCII - American Standard Code for Information Interchange.
‘A’ - 65
‘B’ - 66
‘C’ - 67

‘a’ - 97
‘b’ - 98
‘c’ - 99
...

Sr. Type Storage Size Range Format Specifier


1. char 1 byte -128 to 127 or 0 to 255 %c
2. unsigned char 1 byte 0 to 255 %c
3. signed char 1 byte -128 to 127 %c

Variables:
A variable is nothing but a name given to a storage area that our program 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 value present in that
variable. In short, a variable is just a holder or container for the value.
Declaration of Variables:
In C programs to perform operations we require data, and this data needs to be stored into memory. To store
data into memory we need to allocate memory and that is done by the declaration of variables.
Syntax:
dataType variableName;
Example:
int no;
char ch;
float fl;

C allows us for the declaration of multiple variables belonging to one single data type in one statement.
Syntax:
dataType variableName1, variableName2, variableName3, …;

Sourabha Malve : 8605400907 https://www.intelliseit.com 4


INTELLISE IT C Programming Language

Example:
int rollNo1, rollNo2, rollNo3;
float subject1, subject2, subject3, subject4, subject5;

Note that: if we use a variable to which no any value is assigned, the for integer variable its default value is
garbage value (any random positive/negative value), for floating-point variable the default initial value is 0.0,
and for a character variable the default initial value is nothing/blank.
Ths we need to assign a value to a variable before using it.
Assigning value:
To assign value/data to a variable, we first need to declare the variable then we can assign any value to a
variable, provided the value should belong to the type of variable and should be present within the range of its
data type.
Syntax:
variableName = value;

Example:
no = 26;
fl = 25.4;
ch = ‘A’;

Storage of value in memory:


The value that we assign to any variable will be stored in its binary form in the allocated memory.
For an integer variable’s value the binary of the assigned integer value will be first converted into its
respective binary, which is done by the C compiler, and will be stored into the memory.
Example:
Binary of integer value 26 can be calculated as:
26 / 2 = 0
13 / 2 = 1
6 /2=0
3 /2=1
1 =1
26 = (0000 0000 0001 1010)
Binary of floating point value 25.4 can be calculated and stored into memory.
Binary of character value is calculated from the ASCII code.
Value ‘A’ will be stored in memory as:
The ASCII value of ‘A’ is 65. Binary of value 65 is calculated and stored into the memory.
65/ 2 = 1
32/ 2 = 0
16/ 2 = 0
8/2=0
4/2=0
2/2=0
1 =1
‘A’ = 65 = (1000001)
Initialization of variables:
If we assign value to a variable at the time of its declaration then it is called as Initialization of variable.
Syntax:
dataType variableName = value;

Sourabha Malve : 8605400907 https://www.intelliseit.com 5


INTELLISE IT C Programming Language

Example:
int no = 30;
float pi = 3.14;
char c = ‘S’;

For multiple variables,


Syntax:
dataType variableName1 = value, variableName2 = value2,...;

Example:
int rollNo1 = 101, rollNo2 = 102;
float subject1 = 85.6, subject2 = 94;

Programs:
Program for Integer Data types:
#include<stdio.h>
void main( )
{
int no;
unsigned int uno;
long int lno;
unsigned long ulno;
no = 25;
uno = 25;
lno = 25;
ulno = 25;
printf("\nno = %d", no);
printf("\nuno = %u", uno);
printf("\nlno = %ld", lno);
printf("\nulno = %lu", ulno);
printf("\nSize of no = %d", sizeof(no));
printf("\nSize of uno = %d", sizeof(uno));
printf("\nSize of lno = %d", sizeof(lno));
printf("\nSize of ulno = %d", sizeof(ulno));
}

Program for Floating point Data types:


#include<stdio.h>
void main( )
{
float f = 2.5; //Initialization of variable
double d = 2.5;
long double l = 2.5;
printf("\nFloat = %f", f);
printf("\nDouble = %lf", d);
printf("\nLong double = %Lf", l);
printf("\nSize of f = %d", sizeof(f));
printf("\nSize of d = %d", sizeof(d));
printf("\nSize of l = %d", sizeof(l));
}

Program for Character Data Types:


#include<stdio.h>

Sourabha Malve : 8605400907 https://www.intelliseit.com 6


INTELLISE IT C Programming Language

void main()
{
char ch = 'b';
printf("\nch = %c", ch);
printf("\nsizeof(ch) = %d", sizeof(ch));
printf("\nASCII code of ch = %d", ch);
ch = '6';
printf("\nch = %c", ch);
printf("\nASCII code of ch = %d", ch);
}

Program to print default initial values and to accept input from the user:
#include<stdio.h>
void main()
{
int i;
char c;
float f;
printf("\nDefault initial value of integer i = %d", i); // Garbage value
printf("\nDefault initial value of character c = %c", c); // Blank value
printf("\nDefault initial value of floating-point variable f = %f", f); // 0.000000
printf("\nEnter an integer value:");
scanf("%d", &i);
printf("\nEnter a character value:");
fflush(stdin);
scanf("%c", &c);
printf("\nEnter a floating point value:");
scanf("%f", &f);
printf("\nInteger input value is = %d", i);
printf("\nCharacter input value is = %c", c);
printf("\nFloating point input value is = %f", f);
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 7


INTELLISE IT C Programming Language

Compilation process in C:

Sourabha Malve : 8605400907 https://www.intelliseit.com 8


INTELLISE IT C Programming Language

Operators in C:
An operator is a symbol that informs the compiler to perform a specific mathematical or logical operation. C
language is rich in built-in operators and proves the following types of operators:
● Arithmetic operators:

Program:
#include<stdio.h>
void main()
{
int no1, no2, result;
printf("\nEnter 2 numbers:");
scanf("%d %d", &no1, &no2);
result = no1 + no2;
printf("\nAddition = %d", result);
result = no1 - no2;
printf("\nSubtraction = %d", result);
result = no1 * no2;
printf("\nMultiplication of %d and %d = %d", no1, no2, result);
result = no1 / no2;
printf("\nDivision of %d and %d = %d", no1, no2, result);
printf("\nReminder of division of %d and %d = %d", no1, no2, (no1 % no2));
}

● Relational operators/Comparison operators:


In the C programming language all non-zero and non-null values are considered as TRUE.
On the other hand, zero (0) or NULL is considered as FALSE.
0 = 0000 0000 0000 0000 (FALSE)
8 = 0000 0000 0000 1000 (TRUE)
1 = 0000 0000 0000 0001 (TRUE)
-5= 1000 0000 0000 0101 (TRUE)
1. Equality operator: (==)
Checks if the values of two operands are equal or not. If yes, then the condition becomes TRUE (1), otherwise
FALSE (0).
2. Not-equal operator: (!=)
Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes
TRUE (1) otherwise FALSE (0).
3. Greater than: (>)
4. Smaller than: (<)
5. Greater than or equal to: (>=)
6. Smaller than or equal to: (<=)
Program:
#include<stdio.h>
void main()
{
int n1, n2;
printf("\nEnter 2 numbers:");
scanf("%d %d", &n1, &n2);

Sourabha Malve : 8605400907 https://www.intelliseit.com 9


INTELLISE IT C Programming Language

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


printf("\n%d != %d = %d", n1, n2, (n1 != n2));
printf("\n%d > %d = %d", n1, n2, (n1 > n2));
printf("\n%d < %d = %d", n1, n2, (n1 < n2));
printf("\n%d >= %d = %d", n1, n2, (n1 >= n2));
printf("\n%d <= %d = %d", n1, n2, (n1 <= n2));
}

● Logical operators
Logical operators perform logical operations on operands and produce output in the form of TRUE or FALSE.
In C Programming Language all non-zero and non-NULL values are TRUE. Zero or NULL is FALSE.
1. Logical AND (&&) - Logical AND operator performs AND operation among the given 2 operands.
A B A && B
0 0 0
0 1 0
1 0 0
1 1 1
1. Logical OR operator: (||)
A B A || B
0 0 0
0 1 1
1 0 1
1 1 1
2. Logical NOT operator: ( ! )
A !A
0 1
1 0
Program:
#include<stdio.h>
void main( )
{
int a = 0, b = 1, c = 1;
printf("\n%d && %d = %d", a, b, (a && b));
printf("\n%d && %d = %d", c, b, (c && b));
printf("\n%d || %d = %d", a, a, (a || a));
printf("\n%d || %d = %d", a, b, (a || b));
printf("\n%d || %d = %d", c, b, (c || b));
printf("\n!%d = %d", a, (!a));
printf("\n!%d = %d", b, (!b));
}

● Bitwise operators:
Bitwise operators perform operations on the binary bits of the given operands. That is, it works on bits and
performs bit-by-bit operation.
Example:
int a = 60, b = 13;
1. Bitwise AND (&) - Bitwise AND operator performs AND operation bit-by-bit on the input operands.

Sourabha Malve : 8605400907 https://www.intelliseit.com 10


INTELLISE IT C Programming Language

a = 60 = 0000 0000 0011 1100


b = 13 = 0000 0000 0000 1101
a & b = 0000 0000 0000 1100 = 12
2. Bitwise OR (|)-Bitwise OR operator performs OR operation bit-by-bit on the input operands.
a = 60 = 0000 0000 0011 1100
b = 13 = 0000 0000 0000 1101
a | b = 0000 0000 0011 1101 = 61
3. Bitwise ExOR (^)-Bitwise ExOR operator performs ExOR operation bit-by-bit on the input operands.
a = 60 = 0000 0000 0011 1100
b = 13 = 0000 0000 0000 1101
a ^ b = 0000 0000 0011 0001 = 49
4. Bitwise NOT (~)- Bitwise NOT operator performs One's complement of the given operand. It is an unary
operator.
Example:
b = ~a; //~60 = -(60+1) = -61
a = -34;
b =~a; //~(-34) = -(-34+1) = -(-33) = 33
5. Left shift operator (<<) - The left shift operator moves the binary bits of left operand by the number of
bits specified by the right operand.
Syntax:
result = op1 << 3;
Example:
int op1 = 28;
op1 << 3; //0 0000 0001 1100 000
6. Right shift operator (>>) - It moves the binary bits of the left operand by the number of bits specified by
the right operand.
Syntax:
result = op2 >> 3;
Example:
int op2 = 31;
op2 >> 2; //00 0000 0000 0001 11
Example:
#include<stdio.h>
void main()
{
int op1 = 60, op2 = 13, result;
printf("\nop1 = %d, op2 = %d", op1, op2);
result = op1 & op2;
printf("\nop1 & op2 = %d", result);
result = op1 | op2;
printf("\nop1 | op2 = %d", result);
result = op1 ^ op2;
printf("\nop1 ^ op2 = %d", result);
result = ~op1;

Sourabha Malve : 8605400907 https://www.intelliseit.com 11


INTELLISE IT C Programming Language

printf("\n~op1 = %d", result);


op2 = -34; //-(-34 + 1) = -(-33) = 33
result = ~op2;
printf("\n~op2 = %d", result);
result = op1 << 3;
printf("\nop1 << 3 = %d", result);
op2 = 31;
result = op2 >> 2;
printf("\nop2 >> 2 = %d", result);
}

● Increment/Decrement operator:
Increment Operator: (++)
Increment operator increases the integer value by one.
Syntax:
var++;
Decrement Operator: (--)
Decrement operator decreases the integer value by one.
Syntax:
var--;

Program:
#include<stdio.h>
void main()
{
int no1 = 25, no2 = 17;
printf("\nno1 = %d", no1);
printf("\nno2 = %d", no2);
no1++;
no2--;
printf("\nAfter increment, no1 = %d", no1);
printf("\nAfter decrement, no2 = %d", no2);
}
Types of Increment:
1. Pre-increment
If the increment operator is placed before the variable, then the value of the variable is increased first and
then it is assigned to another variable (if any).
Syntax:
++var;
2. Post-increment
If the increment operator is placed after the variable, then the value of the variable is assigned as it is to
another variable (if any), and then its own value is increased.
Syntax:
var++;

Program:
#include<stdio.h>
void main()
{
int no1 = 25, no2 = 17, no3, no4;
printf("\nno1 = %d", no1);
printf("\nno2 = %d", no2);
no1++;
no2--;

Sourabha Malve : 8605400907 https://www.intelliseit.com 12


INTELLISE IT C Programming Language

printf("\nAfter increment, no1 = %d", no1); //26


printf("\nAfter decrement, no2 = %d", no2); //16

no3 = ++no1;
printf("\nAfter pre-increment, no1 = %d, no3 = %d", no1, no3);
no4 = no2++;
printf("\nAfter post-increment, no2 = %d, no4 = %d", no2, no4);

no3 = --no1;
printf("\nAfter pre-decrement, no1 = %d, no3 = %d", no1, no3);
no4 = no2--;
printf("\nAfter post-decrement, no2 = %d, no4 = %d", no2, no4);
}

● Assignment operators:
1. Assignment operator ( = ) :
It assigns the right hand side value to the left hand side variable. We can also define an expression at the
right hand side and then the assignment operator evaluates the right hand side expression and assigns the
outcome to the left hand side variable.
Syntax:
var = value;
OR
var = expression;

Program:
#include<stdio.h>
void main()
{
int no = 25, i;
char ch = 'A', c; //ASCII
float fl = 35.5, f;
printf("\nInteger value = %d", no);
printf("\nCharacter value = %c", ch);
printf("\nFloating point value = %f", fl);

printf("\nInteger value = %d", i); //Garbage value


printf("\nCharacter value = %c", c); //Blank value
printf("\nFloating point value = %f", f); //0.000000
printf("\n\nEnter an integer value:");
scanf("%d", &i);
printf("\nEnter a letter:");
fflush(stdin);
scanf("%c", &c);
printf("\nEnter a floating point value:");
scanf("%f", &f);

printf("\nInteger value = %d", i);


printf("\nCharacter value = %c", c);
printf("\nFloating point value = %f", f);

no = i;
ch = c;
fl = f;
printf("\nInteger value = %d", no);
printf("\nCharacter value = %c", ch);

Sourabha Malve : 8605400907 https://www.intelliseit.com 13


INTELLISE IT C Programming Language

printf("\nFloating point value = %f", fl);


}

2. Compound Assignment Operators:


Compound Assignment Operators perform 2 operations. First it performs operation of left side and right side
operands and then assigns the outcome of the operation to the left side operand.
Arithmetic Assignment
a. Addition Assignment operator: ( += ):
It performs addition of left and right side operands and the sum value is assigned to the left side operand.
Syntax:
op1 += op2; // op1 = op1 + op2;
b. Subtraction Assignment operator: ( -= ):
It performs subtraction of left and right side operands and the difference value is assigned to the left side
operand.
Syntax:
op1 -= op2; // op1 = op1 - op2;
c. Multiplication Assignment operator: ( *= ):
It performs multiplication of left and right side operands and the resultant value is assigned to the left side
operand.
Syntax:
op1 *= op2; // op1 = op1 * op2;
d. Division Assignment operator: ( /= ):
It performs division of left and right side operands and the quotient value is assigned to the left side operand.
Syntax:
op1 /= op2; // op1 = op1 / op2;
e. Modulus Assignment operator: ( %= ):
It performs division of left and right side operands and the remainder value is assigned to the left side
operand.
Syntax:
op1 %= op2; // op1 = op1 % op2;

Program:
#include<stdio.h>
void main()
{
int n1, n2;
printf("\nEnter 2 numbers:");
scanf("%d %d", &n1, &n2); //15, 8
n1 += n2;
printf("\nAfter n1 += n2, n1 = %d, n2 = %d", n1, n2);
n1 -= n2;
printf("\nAfter n1 -= n2, n1 = %d, n2 = %d", n1, n2);
n2 *= n1;
printf("\nAfter n2 *= n1, n1 = %d, n2 = %d", n1, n2);
n2 /= n1;
printf("\nAfter n2 /= n1, n1 = %d, n2 = %d", n1, n2);
n1 %= n2;
printf("\nAfter n1 %%= n2, n1 = %d, n2 = %d", n1, n2);
}

Bitwise compound assignment operator:


f. Bitwise AND Assignment operator: ( &= ):
It performs Bitwise AND operation of left and right side operands and the result is assigned to the left side
operand.
Sourabha Malve : 8605400907 https://www.intelliseit.com 14
INTELLISE IT C Programming Language

Syntax:
op1 &= op2; // op1 = op1 & op2;
g. Bitwise OR Assignment operator: ( |= ):
It performs Bitwise OR operation of left and right side operands and the result is assigned to the left side
operand.
Syntax:
op1 |= op2; // op1 = op1 | op2;
h. Bitwise ExOR Assignment operator: ( ^= ):
It performs Bitwise ExOR operation of left and right side operands and the result is assigned to the left side
operand.
Syntax:
op1 ^= op2; // op1 = op1 ^ op2;
i. Left shift Assignment operator: ( <<= ):
It performs Bitwise Left shift operation of left and right side operands and the result is assigned to the left
side operand.
Syntax:
op1 <<= op2; // op1 = op1 << op2;
j. Right shift Assignment operator: ( >>= ):
It performs Bitwise Right shift operation of left and right side operands and the result is assigned to the left
side operand.
Syntax:
op1 >>= op2; // op1 = op1 >> op2;

Program:
#include<stdio.h>
void main()
{
int a, b;
printf("\nEnter 2 numbers:");
scanf("%d %d", &a, &b);
a &= b;
printf("\nAfter a &= b, a = %d, b = %d", a, b);
a |= b;
printf("\nAfter a |= b, a = %d, b = %d", a, b);
b ^= a;
printf("\nAfter b ^= a, a = %d, b = %d", a, b);
a <<= 2;
printf("\nAfter a <<= 2, a = %d, b = %d", a, b);
a >>= 2;
printf("\nAfter a >>= 2, a = %d, b = %d", a, b);
}

● Misc Operators:
1. sizeof( ) :
It returns an integer value indicating the size of the given variable or constant in bytes.
2. Address of operator (&) :
It returns the actual memory location (address) of the given variable.
3. Pointer operator (indirection operator) (*) :
It is a pointer to a variable.
4. Conditional expression (ternary operator)/if-then-else operator ( ? : ) :
Syntax:
expression ? TRUE : FALSE

Program:
Sourabha Malve : 8605400907 https://www.intelliseit.com 15
INTELLISE IT C Programming Language

#include<stdio.h>
void main()
{
int no1 = 25, no2 = 50;
char ch = 'F';
float f = 3.14;
int size;
size = sizeof(no1);
printf("\nSize of integer variable : %d bytes", size);
size = sizeof(ch);
printf("\nSize of character variable : %d bytes", size);
printf("\nSize of floating point variable : %d bytes", sizeof(f));
ch = 'R';
printf("\nSize of character value %c is : %d bytes", ch, sizeof(ch));
no1 = 17;
printf("\nSize of integer value %d is : %d bytes", no1, sizeof(no1));
f = 1.5;
printf("\nSize of floating point value %f is : %d bytes", f, sizeof(f));
printf("\nAddress of character variable : %x ", &ch);
printf("\nAddress of integer variable : %x ", &no1);
printf("\nAddress of float variable : %x ", &f);
size = (no1 < no2) ? no1 : no2;
printf("\n\nif-then-else operator:");
printf("\nno1 = %d, no2 = %d, smaller value = %d", no1, no2, size);
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 16


INTELLISE IT C Programming Language

Escape Sequences in C:
An escape sequence is a sequence of characters that does not represent itself when used inside string literal
or character. It is composed of two or more characters starting with backslash (\). For example: \n represents
a new line.
List of Escape Sequences in C:
\a : Alarm or Beep
\b : Backspace
\f : Form feed
\n : new line
\r : carriage return
\t : tab (horizontal)
\v : vertical tab
\\ : Backslash
\' : Single Quote
\" : Double Quote
\? : Question mark
\onn : octal number
\xhh : hexadecimal number
\0 : NULL
Example:
#include<stdio.h>
void main()
{
int no = 25;
printf("\nEscape sequence characters in C");
printf("\n\a : Alarm or Beep");
printf("\n\b : Backspace");
printf("\n\f : Form feed");
printf("\n\n : new line");
printf("\n\r : carriage return");
printf("\n\t : tab (horizontal)");
printf("\n\v : vertical tab");
printf("\n\\ : Backslash");
printf("\n\' : Single Quote");
printf("\n\" : Double Quote");
printf("\n\? : Question mark");
printf("\n\o26 : octal number", no);
printf("\n\xb : hexadecimal number");
printf("\n\0 : NULL");
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 17


INTELLISE IT C Programming Language

Control Statement:
Control statements are the statements in the C programming language that control the flow of a program.
Decision Making:
Decision making structures require that the programmer specify one or more conditions to be evaluated or
tested by the program, along with a statement or group of statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to be
false.
C Programming Language assumes all NON-ZERO and NON-NULL values as TRUE, and if the value is ZERO
or NULL then it is assumed as FALSE.
1. The if statement:
An if statement consists of a Boolean expression followed by one or more statements. If the boolean
expression evaluates to TRUE, then the block of code inside the if statement will be executed. If the boolean
expression evaluates to FALSE, then the first set of code after the end of the if statement will be executed.
Syntax:
if ( booleanExpression )
{
block of statements to be executed is the booleanExpression evaluates to TRUE
}

Example:
#include<stdio.h>
void main()
{
int age;
printf("\nEnter your age:");
scanf("%d", &age);
if(age > 17)
{
printf("\nYou are an Adult.");
}
printf("\nThank You.");
}

2. The if...else statement:


An if statement can be followed by an optional else statement, which executes when the boolean expression
evaluates to FALSE. If the boolean expression evaluates to TRUE, then the block of code inside the if
statement will be executed. If the boolean expression evaluates to FALSE, then the block of code inside the
else statement will be executed.
Syntax:
if ( booleanExpression )
{
block of statements to be executed if the booleanExpression evaluates to TRUE
}
else
{
block of statements to be executed if the booleanExpression evaluates to FALSE
}

Note that: In any case, C compiler will execute only one block, that is either if block or else block.
Example:
#include<stdio.h>
void main()

Sourabha Malve : 8605400907 https://www.intelliseit.com 18


INTELLISE IT C Programming Language

{
int age;
printf("\nEnter your age:");
scanf("%d", &age);
if(age > 17)
{
printf("\nYou are an Adult.");
printf("\nYou are eligible for voting.");
}
else
{
printf("\nYou are a Child.");
printf("\nPlease wait. You cannot vote now.");
}
printf("\nThank You.");
}

Example 2:
#include<stdio.h>
void main()
{
int no;
printf("\nEnter a number:");
scanf("%d", &no);
if(no % 2)
printf("\nNumber %d is an ODD number.", no);
else
printf("\nNumber %d is an EVEN number.", no);
printf("\nExiting program.");
}

The if… else if… statement:


An if statement can be followed by an optional else if... else statement, which is very useful to test various
conditions using single if..else if statement. When using if...else if...else statements, there are few points to
keep in mind:
● An if can have zero or one else statement and it must come after any else if.
● An if can have zero to many else if statements and they must come after the if statement and before
the else statement.
● Once an else if statement succeeds, none of the remaining else if or else will be tested

Syntax:
if(expression1)
{
block of statements to be executed if the expression1 evaluates to TRUE
}
else if(expression2)
{
block of statements to be executed if the expression1 evaluates to FALSE, and
expression2 evaluates to TRUE
}
else
{
block of statements to be executed if the expression1 and expression2, both evaluates
to FALSE

Sourabha Malve : 8605400907 https://www.intelliseit.com 19


INTELLISE IT C Programming Language

Note that: In any case, C compiler will execute only one block, that is either if block or else if, or else block.
Example:
#include<stdio.h>
void main()
{
float tem;
printf("\nEnter current temperature:");
scanf("%f", &tem);
if(tem > 0.0)
{
printf("\nTemperature is positive.");
printf("\nIts a good sunny day.");
}
else if(tem < 0.0)
{
printf("\nTemperature is negative.");
printf("\nIts too cold out there. Take care.");
}
else
{
printf("\nTemperature is exact 0.0.");
printf("\nIts a cold day.");
}
printf("\nThank you");
}

Example 2:
#include<stdio.h>
void main()
{
int age;
printf("\nEnter your age:");
scanf("%d", &age);
if(age < 0)
printf("\nInvalid age.");
else if(age < 18)
printf("\nYou are a Child. Your age is %d. You should not drive any vehicle.", age);
else
printf("\nYou are an Adult. Your age is %d. You are free to drive any vehicle.",
age);
}

The if...else if... ladder statements:


The if...else if... ladder statement is an extension to the if...else if... statement.
It is used in the scenario where there are multiple cases to be performed for different conditions.
Syntax:
if(expression1)
{
block of statements to be executed if the expression1 evaluates to TRUE
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 20


INTELLISE IT C Programming Language

else if(expression2)
{
block of statements to be executed if the expression1 evaluates to FALSE, and
expression2 evaluates to TRUE
}
else if(expression3)
{
block of statements to be executed if the expression1 and expression2 evaluates to
FALSE, and expression3 evaluates to TRUE
}
else if(expression4)
{
block of statements to be executed if the expression1, expression2 and expression3
evaluates to FALSE, and expression4 evaluates to TRUE
}
else if(...)
...
else
{
block of statements to be executed if all the expressions of if and all else if
evaluates to FALSE
}

Note that: In any case, C compiler will execute only one block, that is either if block or else if, or else block.
Example:
#include<stdio.h>
void main()
{
int age;
printf("\nEnter your age:");
scanf("%d", &age);
if(age < 0)
printf("\nInvalid age");
else if(age < 4)
printf("\nYou are an Infant");
else if(age < 13)
printf("\nYou are a Child");
else if(age < 18)
printf("\nYou are a Teen Ager");
else if(age < 60)
printf("\nYou are an Adult");
else
printf("\nYou are a Sr. Citizen");
printf("\nThank you");
}

Nested if...else statement


C Program allows us to place an if...else statement inside another if, else if, or else block. This is known as
nesting of if...else statements.
Syntax:
if(expression1)
{

Sourabha Malve : 8605400907 https://www.intelliseit.com 21


INTELLISE IT C Programming Language

if(expression2)
{

}
else ...
}
else if(expression3)
{

if(expression4)
{

}
else ...
}
else
{
if(expression5)
{

}
else...
}

Example:
#include<stdio.h>
void main()
{
int age;
printf("\nEnter your age:");
scanf("%d", &age);
if(age < 0 || age > 120)
{
printf("\nInvalid age");
}
else
{
if(age < 4)
printf("\nYou are an Infant");
else if(age < 13)
printf("\nYou are a Child");
else if(age < 18)
printf("\nYou are a Teen Ager");
else if(age < 60)
printf("\nYou are an Adult");
else
printf("\nYou are a Sr. Citizen");
}
}

Example 2:
#include<stdio.h>
void main()
{
float per;

Sourabha Malve : 8605400907 https://www.intelliseit.com 22


INTELLISE IT C Programming Language

printf("\nEnter your percentage:");


scanf("%f", &per);
if(per >= 0.0 && per <= 100.0)
{
if(per >= 0.0 && per < 40.0)
printf("\nSorry! Please try again.");
else if(per >= 40.0 && per < 50.0)
printf("\nCongratulations! You have secured PASS Class");
else if(per >= 50.0 && per < 60.0)
printf("\nCongratulations! You have secured SECOND Class");
else if(per >= 60.0 && per < 70.0)
printf("\nCongratulations! You have secured FIRST Class");
else
printf("\nCongratulations! You have secured FIRST Class with Distinction.");
}
else
printf("\nInvalid percentage.");
}

The switch case statement:


The switch statement in C is an alternative to the if-else ladder statement which allows us to execute multiple
operations for the different possible values of a single variable.
Syntax:
switch(expression)
{
case Value1:
code to be executed if the expression evaluates to value1
break;
case Value2:
code to be executed if the expression evaluates to value2
break;
case Value3:
code to be executed if the expression evaluates to value3
break;

default:
code to be executed if the expression evaluation value does not match with any
case's value
}

Example:
#include<stdio.h>
void main()
{
int weekDayNo;
printf("\nEnter week day no:");
scanf("%d", &weekDayNo);
switch(weekDayNo)
{
case 1:
printf("\nIts Monday");
break;
case 2:
printf("\nIts Tuesday");
break;

Sourabha Malve : 8605400907 https://www.intelliseit.com 23


INTELLISE IT C Programming Language

case 3:
printf("\nIts Wednesday");
break;
case 4:
printf("\nIts Thursday");
break;
case 5:
printf("\nIts Friday");
break;
case 6:
printf("\nIts Saturday");
printf("\nIts weekend. Enjoy the holiday.");
break;
case 7:
printf("\nIts Sunday");
printf("\nIts weekend. Enjoy the holiday.");
break;
default:
printf("\nInvalid weekday no");
}
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 24


INTELLISE IT C Programming Language

Loops in C:
You may encounter situations when a block of code needs to be executed several number times.
In general statements are executed sequentially. The first statement in a function or block of code is executed
first, followed by the second, then the third one, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A looping statement allows us to execute a statement or group of statements multiple times.
The while loop:
A while loop in C programming language repeatedly executes a target statement(s) as long as a given condition
is TRUE.
Syntax:
while (condition)
{
statement(s);

}

Here, statement(s) may be a single statement or block of statements. The condition may be any expression,
and TRUE is any non-zero, non-NULL value. The loop iterates while the condition is TRUE.
When the condition becomes FALSE, the program control passes to the statement immediately following the
loop.
Program:
#include<stdio.h>
void main()
{
int no = 1;
printf("\nNumbers from 1 to 10, using while loop : ");
while(no <= 10)
{
printf("%d ", no);
++no;
}
printf("\nThank you.");
}

Program:
#include<stdio.h>
void main()
{
int no, cnt, ans;
printf("\nEnter a number : ");
scanf("%d", &no);
printf("\nTable of number %d is :", no);
cnt = 1;
while(cnt <= 10)
{
ans = no * cnt;
printf("\n%d X %d = %d", no, cnt, ans);
++cnt;
}
printf("\nThank you.");
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 25


INTELLISE IT C Programming Language

While loop is also known as a pre-tested loop.


The do-while loop:
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of a block of
statements. The do-while loop is mainly used in the case where we need to execute the loop at least once.
Syntax:
do
{
statement(s);

} while(condition);

Program:
#include<stdio.h>
void main()
{
int no = 1;
printf("\nNumbers from 1 to 10, using do-while loop : ");
do
{
printf("%d ", no);
++no;
} while(no <= 10);
printf("\nThank you.");
}

The for loop:


The for loop in C Programming Language is used to iterate a block of statements several times. It is frequently
used to traverse the data structures like the array and linked list.
Syntax:
for (initialization; condition; iteration)
{
statement(s)

}

Execution:
for (initialization(0); condition(1); incr/decr(3))
{
statement(s)(2)

}
(4)

Program:
#include<stdio.h>
void main()
{
int no;
printf("\nNumbers from 1 to 10, using while loop : ");
for(no = 1; no <= 10; ++no)
{
printf("%d ", no);

Sourabha Malve : 8605400907 https://www.intelliseit.com 26


INTELLISE IT C Programming Language

}
printf("\nThank you.");
}

Program 2:
#include<stdio.h>
void main()
{
int no, cnt, ans;
printf("\nEnter a number : ");
scanf("%d", &no);
printf("\nTable of number %d is :", no);
for(cnt = 1; cnt <= 10; ++cnt)
{
ans = no * cnt;
printf("\n%d X %d = %d", no, cnt, ans);
}
printf("\nThank you.");
}

Variations in while loops:


You can set a while/do-while loop to always TRUE. Doing so will infinitely execute the loop.
Example:
while(1)
{
Loop body…

}

Program:
#include<stdio.h>
void main()
{
int no = 1;
while(1)
{
printf(" %d ", no);
++no;
}
}

Variations in for loop:


You can specify 0 or more number of assignment/input statement(s) in the initialization part of the for loop.
Example:
for(scanf(...); … ; …)
{
Loop body…

}

Program:
#include<stdio.h>
void main()

Sourabha Malve : 8605400907 https://www.intelliseit.com 27


INTELLISE IT C Programming Language

{
int no, cnt = 1, ans;
printf("\nEnter a number : ");
for(scanf("%d", &no); cnt <= 10; ++cnt)
{
ans = no * cnt;
printf("\n%d X %d = %d", no, cnt, ans);
}
printf("\nThank you.");
}

You can perform multiple initializations in the for loop.


Example:
for(scanf("%d", &no), cnt = 1; cnt <= 10; ++cnt)
{
Loop body…

}

You can eliminate any expression from the for loop.


Example:
for ( ; condition; iteration)
{
statement(s)

}
OR
for (initialization ; ; iteration)
{
statement(s)

}

OR
for (initialization ; condition ; )
{
statement(s)

}

OR
for ( ; condition ; )
{
statement(s)

}

OR
for ( ; ; )
{
statement(s)

}

Sourabha Malve : 8605400907 https://www.intelliseit.com 28


INTELLISE IT C Programming Language

Program:
#include<stdio.h>
void main()
{
int no, cnt = 1, ans;
printf("\nEnter a number : ");
scanf("%d", &no);
printf("\nTable of %d is : ", no);
for( ; cnt <= 10; )
{
ans = no * cnt;
printf("\n%d X %d = %d", no, cnt, ans);
++cnt;
}
printf("\nThank you.");
}

The break statement:


The break statement in C programming has 2 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.

Program 1:
#include<stdio.h>
void main()
{
int no = 1;
printf("\nEven numbers from 1 to 20 are:");
for(no = 1; ; ++no)
{
if(no % 2 == 0)
printf(" %d", no);
if(no == 20)
break;
}
printf("\nThank you");
}

Program 2:
#include<stdio.h>
void main()
{
int no, cnt = 1, ans;
printf("\nEnter a number : ");
scanf("%d", &no);
printf("\nTable of %d is : ", no);
for( ; ; )
{
ans = no * cnt;
printf("\n%d X %d = %d", no, cnt, ans);
if(cnt == 10)
break;
++cnt;
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 29


INTELLISE IT C Programming Language

printf("\nThank you.");
}

The continue statement:


The continue statement in C Programming works somewhat like the break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, the continue statement causes the increment portions and conditional test of the loop to
execute. FFor the while and do-while loops, the continue statement causes the program control to pass to the
conditional tests.
Program 1:
#include<stdio.h>
void main()
{
int no;
printf("\nEven numbers from 1 to 20 are:");
for(no = 1; no <= 20; ++no)
{
if(no % 2)
{
continue;
}
printf(" %d", no);
}
printf("\nThank you");
}

1. WAP to check whether the input number is even or odd.


#include<stdio.h>
void main()
{
int no;
printf("\nEnter a number:");
scanf("%d", &no);
if(no % 2)
printf("\nNumber %d is Odd", no);
else
printf("\nNumber %d is Even", no);
}

2. WAP to print Odd numbers from 1 to 30.


#include<stdio.h>
void main()
{
int no;
printf("\nOdd numbers from 1 to 30 are : ");
for(no = 1; no <= 30; ++no)
if(no % 2)
printf(" %d ", no);
}

3. WAP to check whether the input number is Prime or not.


#include<stdio.h>

Sourabha Malve : 8605400907 https://www.intelliseit.com 30


INTELLISE IT C Programming Language

void main()
{
int no, i;
printf("\nEnter a number:");
scanf("%d", &no);
for(i = 2; i < no; ++i)
{
if(no % i == 0)
{
printf("\nNumber %d is Not Prime", no);
break;
}
}
if(i == no)
printf("\nNumber %d is Prime", no);
}

4. WAP to print fibonacci series from 0 to 200


0 1 1 2 3 5 8 13 21 34 55 89 …
#include<stdio.h>
void main()
{
int a = 0, b = 1, c;
printf("\nFibonacci series from 0 to 200 : \n");
printf("%d %d", a, b);
do
{
c = a + b;
if(c > 200)
break;
printf(" %d", c);
a = b;
b = c;
}while(1);
}

5. WAP to print numbers divisible by 7 from 1 to 100.


#include<stdio.h>
void main()
{
int cnt;
printf("\nNumbers divisible by 7 from 1 to 100 are :\n");
for(cnt = 1; cnt <= 100; ++cnt)
{
if(cnt % 7 == 0)
printf(" %d", cnt);
}
}

Nested Loops:
C Programming language allows one loop inside another loop. This is known as nesting of loops.
Syntax:
for(initialization; condition; increment/decrement) OR while(expression)
{

Sourabha Malve : 8605400907 https://www.intelliseit.com 31


INTELLISE IT C Programming Language


for(initialization; condition; increment/decrement) OR while(expression)
{

statement(s);

}
statement(s)

}

A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a
"for" loop can be inside a "while" or vice-versa
Note: While execution of nested loops, whenever the outer loop is iterated once, the inner loop iterates to the
fullest, that is till it exhausts.
Program:
#include<stdio.h>
void main()
{
int i, j;
printf("\nNested loop:");
for(i = 1; i < 5; ++i)
{
printf("\n");
for(j = 1; j < 5; ++j)
{
printf(" %d ", (i + j));
}
}
}

Program 2:
#include<stdio.h>
void main()
{
int i, j;
printf("\nNested loop:");
//for(i = 1; i < 5; ++i)
i = 1;
while(i < 5)
{
printf("\n");
//for(j = 1; j <= i; ++j)
j = 1;
while(j <= i)
{
printf(" %d ", (i + j));
++j;
}
++i;
}
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 32


INTELLISE IT C Programming Language

1. WAP to print the tables from 1 to 10 numbers using a nested loop.


#include<stdio.h>
void main()
{
int no = 1, cnt, ans;

for(no = 1; no <= 10; ++no)


{
printf("\n\n Table of number %d :", no);
for(cnt = 1; cnt <= 10; ++cnt)
{
ans = no * cnt;
printf("\n %d X %d = %d", no, cnt, ans);
}
}
}

2. WAP to print the following pattern:


*
* *
* * *
* * * *
* * * * *
#include<stdio.h>
void main()
{
int i, j;
printf("\n Pattern : \n");
for(i = 1; i < 6; ++i)
{
for(j = 1; j <= i; ++j)
{
printf(" * ");
}
printf("\n");
}
}

3. WAP to print the following pattern:


a
a b
a b c
a b c d
a b c d e
#include<stdio.h>
void main()
{
int i, j;
char ch;
printf("\n Pattern : \n");
for(i = 1; i < 6; ++i)
{

Sourabha Malve : 8605400907 https://www.intelliseit.com 33


INTELLISE IT C Programming Language

for(ch = 'a', j = 1; j <= i; ++j, ++ch)


{
printf(" %c ", ch);
}
printf("\n");
}
}

4. WAP to print the following pattern:


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
#include<stdio.h>
void main()
{
int i, j;
printf("\n Pattern : \n");
for(i = 1; i < 6; ++i)
{
for(j = 1; j <= i; ++j)
{
printf(" %d ", i);
}
printf("\n");
}
}

5. WAP to print the following pattern:


10
9 8
7 6 5
4 3 2 1
#include<stdio.h>
void main()
{
int i, j, no = 10;
printf("\n Pattern : \n");
for(i = 1; i < 5; ++i)
{
for(j = 1; j <= i; ++j)
{
printf(" %d ", no);
--no;
}
printf("\n");
}
}

6. WAP to print the following pattern:

Sourabha Malve : 8605400907 https://www.intelliseit.com 34


INTELLISE IT C Programming Language

*
* *
* * *
* * * *
* * * * *
#include<stdio.h>
void main()
{
int n, i, j, k, t;
printf("\n Pattern:\n");
for(i = 0; i < 5; ++i)
{
for(k = 0; k < (5 - i); ++k)
{
printf(" ");
}
for(j = 0; j <= i; ++j)
{
printf(" *");
}
printf("\n");
}
}

The goto statement:


A goto statement in C programming provides an unconditional jump from the goto statement to a labeled
statement in the same function.
Syntax:
goto label;

Program:
#include<stdio.h>
void main()
{
printf("\nmain() function started.");
goto myLabel;
printf("\nThis statement will not execute.");
printf("\nThis will also not execute.");
myLabel:
printf("\nThis statement is after myLabel");
printf("\nExiting from main() function.");
}

Program 2:
#include<stdio.h>
void main()
{
int no = 1;
printf("\nNumbers from 1 to 10 are:");
jumpHere:
printf(" %d ", no);
++no;

Sourabha Malve : 8605400907 https://www.intelliseit.com 35


INTELLISE IT C Programming Language

if(no < 11)


goto jumpHere;
printf("\nThank you");
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 36


INTELLISE IT C Programming Language

Arrays:
Array is a variable with a sequence of elements having the same data type. Array is 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.
Instead of declaring individual variables, such as no1, no2, no3, and so on, you can declare one array variable
in which multiple values can be stored.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and
the highest address to the last element.
A specific element in an array is accessed by an index. Index is just like the position number of the elements
present in an array. Index always starts from 0, where the first element will be stored/assigned/accessed and
goes upto (array size-1), where the last element will be stored/assigned/accessed.
Declaring Arrays:
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array.
Syntax:
dataType arrayName[arraySize];

Example:
int marks[5];
float fl[10];

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and
dataType can be any valid C data type.
In the above array declaration example, we can store 5 integer elements/values in array marks.
Assigning values to array:
An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array.
Syntax:
arrayName[index] = value;

Example:
marks[0] = 91;
marks[1] = 95;

Program. Assigning values to an array, using individual array index:


#include<stdio.h>
void main()
{
int marks[5];
float tot, per;
marks[0] = 91;
marks[1] = 92;
marks[2] = 93;
marks[3] = 94;
marks[4] = 95;
tot = marks[0] + marks[1] + marks[2] + marks[3] + marks[4];
per = (tot/500) * 100;
printf("\nPercentage : %f", per);

Sourabha Malve : 8605400907 https://www.intelliseit.com 37


INTELLISE IT C Programming Language

Program 2. Accepting input from user into an array, using individual array index :
#include<stdio.h>
void main()
{
int marks[5];
float tot, per;
printf("\nEnter 5 subject marks:");
scanf("%d", &marks[0]);
scanf("%d", &marks[1]);
scanf("%d %d %d", &marks[2], &marks[3], &marks[4]);
tot = marks[0] + marks[1] + marks[2] + marks[3] + marks[4];
per = (tot/500) * 100;
printf("\nPercentage : %f", per);
}

Program 3. Accepting input from user into an array, using loop (most efficient way):
#include<stdio.h>
void main()
{
int marks[5], i;
float tot = 0, per;
printf("\nEnter 5 subject marks:");
for(i = 0; i < 5; ++i)
{
scanf("%d", &marks[i]);
}
for(i = 0; i < 5; ++i)
{
tot += marks[i];
}
per = (tot/500) * 100;
printf("\nPercentage : %f", per);
}

Memory Allocation:
Memory allocation to an array depends on the size of the array and size of its data type. The product of the
size of array and size of array’s data type is the total size of memory, in bytes, allocated to an array.
Example:
int a[5];

The memory allocated to the above declared array is equal to the product of its size, that is 5, and size of its
data type, that is 2 (for TurboC)/4 (for GCC Compiler). That is, a total 10 (TurboC)/20 (GCC Compiler) bytes
of memory is allocated to the above declared array.
Example:
char str[50]; //Total 50 bytes of memory will be allocated
float f[10]; //Total 40 bytes of memory will be allocated

Program:
#include<stdio.h>

Sourabha Malve : 8605400907 https://www.intelliseit.com 38


INTELLISE IT C Programming Language

void main()
{
int a[5];
float f[10];
char c[50];
printf("\nSize of array a = %d", sizeof(a));
printf("\nSize of array f = %d", sizeof(f));
printf("\nSize of array c = %d", sizeof(c));
}

Initialization of array:
Initialize is the process of assigning values to variables at the time of their declaration.
We can initialize arrays just like other variables in C Programming.
To initialize an array we need to enclose the comma separated values in curly brackets { } and assign these
values to the array in its declaration.
Syntax:
dataType arrayName[size] = {value1, value2, value3, …};

Example:
int a[5] = {10, 20, 30, 40, 50};

Program:
#include<stdio.h>
void main()
{
int a[5] = {10, 20, 30, 40, 50};
int i;
float f[5] = {2.5, 3.6, 4.7, 25.50, 24.2021};
printf("\nDefault values in an integer array:\n");
for(i = 0; i < 5; ++i)
printf(" %d ", a[i]);
printf("\nDefault values in a float array:\n");
for(i = 0; i < 5; ++i)
printf(" %f ", f[i]);
}

Note that: We cannot assign values more than the size of an array. Doing so will result in an error.
Example:
int a[5] = {10, 20, 30, 40, 50, 60}; // Error!

We can definitely assign less values than the size of an array. Doing so will by default assign value zero (0) to
the unassigned indexes.
Example:
int a[5] = {10, 20};

In the above example, array a will get values as 10, 20, 0, 0, 0.


To initialize the entire array to value 0, we can use the following example:
Example:
int a[10] = {0};
OR
int a[10] = {};

Sourabha Malve : 8605400907 https://www.intelliseit.com 39


INTELLISE IT C Programming Language

Program:
#include<stdio.h>
void main()
{
int a[10] = {0}; // OR int a[10] = {};
int i;
float f[5] = {0.0}; // OR float f[5] = {};
printf("\nDefault values in an integer array:\n");
for(i = 0; i < 10; ++i)
printf(" %d ", a[i]);
printf("\nDefault values in a float array:\n");
for(i = 0; i < 5; ++i)
printf(" %f ", f[i]);
}

Coping the elements of 1 array into another.


#include<stdio.h>
void main()
{
int a1[5], a2[5];
int i;
printf("\nEnter 5 elements an array:");
for(i = 0; i < 5; ++i)
scanf("%d", &a1[i]);
for(i = 0; i < 5; ++i)
a2[i] = a1[i];
printf("\n\nElements of 1st array:");
for(i = 0; i < 5; ++i)
printf(" %d ", a1[i]);
printf("\nCopy of 1st array:");
for(i = 0; i < 5; ++i)
printf(" %d ", a2[i]);
}

1. WAP to accept 10 numbers from the user into an array and find the smallest value among them.
2. WAP to accept 10 numbers from the user into an array and find the largest value among them.
3. WAP to accept 10 numbers from the user and print all even numbers among them.
4. WAP to accept 10 numbers from the user and print all negative numbers among them.
Q. Declare an array of size 5 and store 10 values in it. What will be its output?

Sourabha Malve : 8605400907 https://www.intelliseit.com 40


INTELLISE IT C Programming Language

Types of Array:
There are 3 types of array:
1. One-dimensional array
2. Two-dimensional array
3. Multi-dimensional array
One-dimensional array:
One-dimensional arrays are also known as 1-D arrays. The examples of arrays that we have seen up till now
belong to this one-dimensional array. So now we shall learn Two-dimensional arrays.
Two-dimensional array:
The two-dimensional array can be defined as an array of arrays. It is also known as a 2-D array.
The 2-D array is organized as matrices which can be represented as the collection of rows and columns. It
provides ease of holding the bulk of data at once which can be passed to any number of functions wherever
required.
Declaration of a 2D array:
Syntax:
dataType arrayName[size1][size2];
OR
dataType arrayName[rowSize][columnSize];

Example:
int a2d[3][4];

The above example creates a 2D array with 3 rows and 4 columns.

Assigning values:
As this is a 2D array, we need to specify 2 dimensions (indexes) to assign value to a particular position.
Syntax:
arrayName[rowIndex][columnIndex];
Example:
a2d[0][0] = 10;
a2d[0][1] = 20;
a2d[0][2] = 30;
a2d[0][3] = 40;
a2d[1][0] = 50;
a2d[1][1] = 60;
a2d[1][2] = 70;
a2d[1][3] = 80;
a2d[2][0] = 90;
a2d[2][1] = 100;
a2d[2][2] = 110;
a2d[2][3] = 120;

Program:

Sourabha Malve : 8605400907 https://www.intelliseit.com 41


INTELLISE IT C Programming Language

#include<stdio.h>
void main()
{
int a2d[3][4];
int row, col;
a2d[0][0] = 10;
a2d[0][1] = 20;
a2d[0][2] = 30;
a2d[0][3] = 40;
a2d[1][0] = 50;
a2d[1][1] = 60;
a2d[1][2] = 70;
a2d[1][3] = 80;
a2d[2][0] = 90;
a2d[2][1] = 100;
a2d[2][2] = 110;
a2d[2][3] = 120;
printf("\n Elements in a 2 Dimensional array are :");
for(row = 0; row < 3; ++row)
{
printf("\n");
for(col = 0; col < 4; ++col)
{
printf(" %d ", a2d[row][col]);
}
}
}

Accepting input:
#include<stdio.h>
void main()
{
int a2d[3][3];
int row, col;
printf("\n Enter elements for a 3x3 matrix : ");
for(row = 0; row < 3; ++row)
{
for(col = 0; col < 3; ++col)
{
scanf("%d", &a2d[row][col]);
}
}
printf("\n Elements in the 3x3 matrix are :");
for(row = 0; row < 3; ++row)
{
printf("\n");
for(col = 0; col < 3; ++col)
{
printf(" %d ", a2d[row][col]);
}
}
}

Matrix Addition and Subtraction:


#include<stdio.h>

Sourabha Malve : 8605400907 https://www.intelliseit.com 42


INTELLISE IT C Programming Language

void main()
{
int m1[2][4], m2[2][4], m3[2][4];
int row, col;
printf("\n Enter elements for first 2x4 matrix : ");
for(row = 0; row < 2; ++row)
{
for(col = 0; col < 4; ++col)
{
scanf("%d", &m1[row][col]);
}
}
printf("\n Enter elements for second 2x4 matrix : ");
for(row = 0; row < 2; ++row)
{
for(col = 0; col < 4; ++col)
{
scanf("%d", &m2[row][col]);
}
}
for(row = 0; row < 2; ++row)
{
for(col = 0; col < 4; ++col)
{
m3[row][col] = m1[row][col] + m2[row][col];
}
}
printf("\n Addition of 2 matrices :");
for(row = 0; row < 2; ++row)
{
printf("\n");
for(col = 0; col < 4; ++col)
{
printf(" %d ", m3[row][col]);
}
}
for(row = 0; row < 2; ++row)
{
for(col = 0; col < 4; ++col)
{
m3[row][col] = m1[row][col] - m2[row][col];
}
}
printf("\n Subtraction of 2 matrices :");
for(row = 0; row < 2; ++row)
{
printf("\n");
for(col = 0; col < 4; ++col)
{
printf(" %d ", m3[row][col]);
}
}
}

Matrix Multiplication:
Sourabha Malve : 8605400907 https://www.intelliseit.com 43
INTELLISE IT C Programming Language

Rule 1. Number of columns of the first matrix should be equal to the number of rows of the second matrix.
Rule 2. The resultant matrix will be of size; the number of rows of the first matrix will be equal to the number
of rows of the resultant matrix, and the number of columns of the second matrix will be the number of
columns of the resultant matrix.
Consider 2 matrices:
m1[2][3]
m2[3][2]
m3[2][2]
Example:

Program for Multiplication of 2 matrices:


#include<stdio.h>
void main()
{
int m1[2][3], m2[3][2], m3[2][2] = {0};
int row, col, var;
printf("\n Enter elements for first 2x3 matrix : ");
for(row = 0; row < 2; ++row)
{
for(col = 0; col < 3; ++col)
{
scanf("%d", &m1[row][col]);
}
}
printf("\n Enter elements for second 3x2 matrix : ");
for(row = 0; row < 3; ++row)
{
for(col = 0; col < 2; ++col)
{
scanf("%d", &m2[row][col]);
}
}
for(row = 0; row < 2; ++row)
{
for(col = 0; col < 2; ++col)
{
m3[row][col] = 0;
for(var = 0; var < 3; ++var)

Sourabha Malve : 8605400907 https://www.intelliseit.com 44


INTELLISE IT C Programming Language

{
m3[row][col] += m1[row][var] * m2[var][col];
}
}
}
printf("\n Multiplication of 2 matrices : \n");
for(row = 0; row < 2; ++row)
{
for(col = 0; col < 2; ++col)
{
printf(" %d ", m3[row][col]);
}
printf("\n");
}
}

WAP to find the Transpose of a given matrix.


#include<stdio.h>
void main()
{
int m[2][3], t[3][2];
int i, j;
printf("\nEnter elements for a 2x3 matrix:");
for(i = 0; i < 2; ++i)
for(j = 0; j < 3; ++j)
scanf("%d", &m[i][j]);
for(i = 0; i < 2; ++i)
for(j = 0; j < 3; ++j)
t[j][i] = m[i][j];
printf("\nElements of 2x3 matrix are:");
for(i = 0; i < 2; ++i)
{
printf("\n");
for(j = 0; j < 3; ++j)
printf(" %d ", m[i][j]);
}
printf("\nElements of transpose of the above matrix are:");
for(i = 0; i < 3; ++i)
{
printf("\n");
for(j = 0; j < 2; ++j)
printf(" %d ", t[i][j]);
}
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 45


INTELLISE IT C Programming Language

String/Character Array:
The string can be defined as the one-dimensional array of characters terminated by a null character ('\0').
Thus a null-terminated string contains the characters that comprise the string followed by a null.
Declaration of String:
Syntax:
char stringName[size];

Example:
char name[20];

Assigning value to a string:


Instead of assigning a value to character array using its index number, we can directly initialize the string.
Initialization character-by-character:
Syntax:
char stringName[size] = {'char1', 'char2', … , '\0'};

Example:
char name[20] = {'P', 'r', 'i', 't', 'i', '\0'};
char name2[] = {'R', 'a', 'j', ' ', 'P', 'a', 't', 'i', 'l', '\0'};

Observe that we have given a last character as '\0', that is nothing but the null character to terminate the
string.
Strings can also be initialized directly:
Syntax:
char stringName[size] = "String";

Example:
char name[20] = "Priti";
char name2[] = "Raj Patil";

Observe that when we initialize a string using the double quotes, there is no need of specifying the null
character at the end of the string.
Program:
#include<stdio.h>
void main()
{
char a[20] = {'P', 'r', 'i', 't', 'i', '\0'};
char b[20] = "Vedika";
char c[] = "INTELLISE IT";
int i;
printf("\nCharacter array 1 contents are:\n");
for(i = 0; i < 20; ++i)
{
printf("%c", a[i]);
}
printf("\nCharacter array 2 contents are:\n");
for(i = 0; i < 20; ++i)
{
printf("%c", b[i]);
}
printf("\nCharacter array 3 contents are:\n");

Sourabha Malve : 8605400907 https://www.intelliseit.com 46


INTELLISE IT C Programming Language

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


{
printf("%c", c[i]);
}
}

Printing string on output screen:


C Programming Language provides us with a format specifier (%s) to print string values.
Syntax:
printf("%s", stringName);

Example:
printf("%s", name);

Program:
#include<stdio.h>
void main()
{
char a[20] = {'P', 'r', 'i', 't', 'i', '\0'};
char b[20] = "Vedika";
char c[] = "INTELLISE IT";
printf("\nContents of a : ");
printf("%s", a);
printf("\nContents of b : %s", b);
printf("\nContents of c : %s", c);
}

Accepting input in strings:


To accept input into a string/character array the same, %s, format specifier is used.
Syntax:
scanf("%s", stringName);

Example:
scanf("%s", name);

Program:
#include<stdio.h>
void main()
{
char str[20];
printf("\nEnter a string : ");
scanf("%s", str);
printf("\nEntered string = %s", str);
}

Program that accepts multiple words in a string:


#include<stdio.h>
void main()
{
char str[20];
printf("\nEnter a string : ");
scanf("%[^\n]s", str);
printf("\nEntered string = %s", str);

Sourabha Malve : 8605400907 https://www.intelliseit.com 47


INTELLISE IT C Programming Language

String functions to accept input and print output:


C Programming Language provides gets( ) and puts( ), input and output functions for strings (character
array), respectively. These functions are present in the stdio.h header file.
The gets( ) function:
The gets( ) function is present in the C programming language that can be used to accept string input from
the user. This function does accept input until the user presses enter key.
Syntax:
gets(stringName);

The puts( ) function:


The puts( ) function is another function provided by the C programming language to print the string value on
the output screen.
Syntax:
puts(stringName);

Program:
#include<stdio.h>
void main()
{
char str[20];
puts("\nEnter a string : ");
gets(str);
printf("\nEntered string = ");
puts(str);
}

String functions:
The C programming language provides some of the string functions to perform operations on strings. These
string functions are present inside the string.h header file.
The strlen( ) function : String length :
The strlen( ) function is the string length function that returns an integer value indicating the length of the
string. That is, the strlen( ) function gives us the count of characters from index 0 to the previous index of
null-character ('\0').
Syntax:
strlen(string);

Program:
#include<stdio.h>
#include<string.h>
void main()
{
char name[20];
int l;
printf("\nEnter a string : ");
gets(name);
l = strlen(name);
printf("\nInput string is \"%s\", its length is %d", name, l);
}

Calculating string length without using built-in function:


#include<stdio.h>

Sourabha Malve : 8605400907 https://www.intelliseit.com 48


INTELLISE IT C Programming Language

void main()
{
char str[20];
int len;
printf("\nEnter your name :");
gets(str);
for(len = 0; str[len] != '\0'; ++len);
printf("\nHello \"%s\". Your name's length is %d.", str, len);
}

The strcpy( ) function : String copy :


The strcpy( ) function is the string copy function that copies one string into another. To the strcpy( ) function
you need to pass 2 parameters, first the destination string and second the source string.
Syntax:
strcpy(stringDestination, stringSource);

Program:
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20], s2[20];
int i;
printf("\nEnter a string :");
gets(s1);
strcpy(s2, s1);
printf("\nOriginal string is %s", s1);
printf("\nCopy of the original string is %s", s2);
}

Copying one string into another using our own logic:


#include<stdio.h>
void main()
{
char s1[20], s2[20];
int i;
printf("\nEnter a string :");
gets(s1);
for(i = 0; s1[i] != '\0'; ++i)
s2[i] = s1[i];
s2[i] = '\0';
printf("\nEntered string is %s", s1);
printf("\nCopy of entered string is %s", s2);
}

The strcat( ) function : String concatenation :


Appending a string at the end of another string is known as string concatenation. C programming language
provides strcat( ) function from the string.h header file to do this string concatenation operation.
Syntax:
strcat(string1, string2);

String Concatenation
S1 = "Good";
Sourabha Malve : 8605400907 https://www.intelliseit.com 49
INTELLISE IT C Programming Language

S2 = "Evening";
Concatenation of S1 and S2
S1 = "GoodEvening"
S2 = "Evening"
Program:
#include<stdio.h>
#include<string.h>
void main()
{
char s1[100], s2[50];
int i;
printf("\nEnter a string :");
gets(s1);
printf("Enter another string :");
gets(s2);
strcat(s1, s2);
printf("\nAfter strcat(s1, s2), string 1 = %s", s1);
printf("\nString 2 = %s", s2);
}

String concatenation using our own logic:


#include<stdio.h>
void main()
{
char s1[100], s2[50];
int i, j;
printf("\nEnter a string :");
gets(s1);
printf("Enter another string :");
gets(s2);
for(i = 0; s1[i] != '\0'; ++i);
for(j = 0; s2[j] != '\0'; ++j, ++i)
s1[i] = s2[j];
s1[i] = '\0';
printf("\nAfter string concatenation\nString 1 = %s", s1);
printf("\nString 2 = %s", s2);
}

Array of Strings:
String array is nothing but array of character array. That means, it is a two-dimensional array of characters.
Syntax:
char arrStr[stringIndex][stringSize];

Example:
char str[5][20];

Program:
#include<stdio.h>
void main()
{
char str[5][20];
int i;

Sourabha Malve : 8605400907 https://www.intelliseit.com 50


INTELLISE IT C Programming Language

printf("Enter 5 strings:");
for(i = 0; i < 5; ++i)
gets(str[i]);
printf("\n5 strings entered are :\n");
for(i = 0; i < 5; ++i)
puts(str[i]);
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 51


INTELLISE IT C Programming Language

Structure:
Arrays allow to define types of variables that can hold several data items of the same kind. Similarly
structure is another user defined data type available in C Programming Language that allows combining data
items of different kinds.
Structures are used to represent a record of an entity. An entity is nothing but a real world object, that can be
a living thing or non-living thing. The attributes/characteristics of an entity can be collectively stored in one
single structure variable.
Defining a Structure:
To define a structure, you must use the struct keyword. The struct keyword defines a new data type, with
more than one member.
Syntax:
struct structureTag/Name
{
dataType memberName1;
dataType memberName2;
...
}[zero or more structure variables];

Example:
struct Student
{
int roll;
char name[20];
float per;
};

Declaring structure variable/object:


To declare a variable/object of a structure you first need to define the structure. The structure is declared just
like any other variable/object is declared in C Programming Language.
Syntax:
struct structureTag/Name variableName;

Example:
struct Student s1;

Structure variables/objects can be declared at the time of defining a structure also.


Example:
struct Student
{
int roll;
char name[20];
float per;
} s1;

Accessing structure members:


To access any member of a structure, you use the member access operator (.), that is the dot operator. The
member access operator is coded as a period between the structure variable/object name and the structure
member that you wish to access. You would use the keyword struct to define variables of structure type.
Example:
s1.roll = 101;
s1.name = "Pramod";
s1.per = 98.5;

Sourabha Malve : 8605400907 https://www.intelliseit.com 52


INTELLISE IT C Programming Language

Program:
#include<stdio.h>
#include<string.h>
void main()
{
struct Student
{
int roll;
char name[20];
float per;
};
struct Student s1;
s1.roll = 101;
strcpy(s1.name ,"Pramod");
s1.per = 98.5;
printf("\nStudent details are:");
printf("\nRoll No : %d", s1.roll);
printf("\nName : ");
puts(s1.name);
printf("Percentage : %f%", s1.per);
}

Accepting input into the structure members:


Program:
#include<stdio.h>
#include<string.h>
void main()
{
struct Student
{
int roll;
char name[20];
float per;
}s1;
s1.roll = 101;
strcpy(s1.name ,"Pramod");
s1.per = 98.5;
printf("\nStudent details are:");
printf("\nRoll No : %d", s1.roll);
printf("\nName : ");
puts(s1.name);
printf("Percentage : %f%", s1.per);
printf("\nEnter your Roll No:");
scanf("%d", &s1.roll);
fflush(stdin);
printf("\nEnter Name:");
gets(s1.name);
printf("\nEnter Percentage:");
scanf("%f", &s1.per);
printf("\nStudent details entered by user are:");
printf("\nRoll No : %d", s1.roll);
printf("\nName : ");
puts(s1.name);

Sourabha Malve : 8605400907 https://www.intelliseit.com 53


INTELLISE IT C Programming Language

printf("Percentage : %f%", s1.per);


}

Memory allocation:
The memory that is allocated to the structure variable/object is the sum of memories of each individual
member of the structure. This sum of memories is allocated to the structure variable/object, that is in the
above shown example, memory is allocated to the structure object "s1" and not to the "struct Student". The
"struct Student" is actually the name of the structure data type.
The sum of all the members of "struct Student" structure data type is 28 bytes.
int roll - 4 bytes
char name[20] - 20 bytes
float per - 4 bytes
Total 28 bytes.
This 28 bytes of memory is allocated to each and every object that you declare of the "struct Student" data
type. These 28 bytes are on the consecutive memory locations.
Program:
#include<stdio.h>
void main()
{
struct Student
{
int roll;
char name[20];
float per;
}s1;
printf("\nSize of \"struct Student\" = %d bytes.", sizeof(struct Student));
printf("\nSize of variable \"s1\" = %d bytes.", sizeof(s1));
}

Declaring multiple objects/variables of a Structure:


You can declare and use multiple objects of the structure data type, just like any other data type.
Syntax:
struct StructureTag var1;
struct StructureTag var2, var3, ...;

Program:
#include<stdio.h>
#include<string.h>
struct Laptop
{
char model[20];
char pro[20];
int ram;
float rom;
float mrp;
};
void main()
{
struct Laptop l1;
struct Laptop l2, l3;
printf("\nEnter details for 1st laptop :");
printf("\nLaptop Company & Model :");
gets(l1.model);

Sourabha Malve : 8605400907 https://www.intelliseit.com 54


INTELLISE IT C Programming Language

printf("Processor Company & Model :");


gets(l1.pro);
fflush(stdin);
printf("RAM :");
scanf("%d", &l1.ram);
printf("ROM (HDD/SSD) :");
scanf("%f", &l1.rom);
printf("MRP (in Rs) :");
scanf("%f", &l1.mrp);
printf("\nEnter details for 2nd laptop :");
printf("\nLaptop Company & Model :");
gets(l2.model);
printf("Processor Company & Model :");
gets(l2.pro);
fflush(stdin);
printf("RAM :");
scanf("%d", &l2.ram);
printf("ROM (HDD/SSD) :");
scanf("%f", &l2.rom);
printf("MRP (in Rs) :");
scanf("%f", &l2.mrp);
printf("\nEnter details for 3rd laptop :");
printf("\nLaptop Company & Model :");
gets(l3.model);
printf("Processor Company & Model :");
gets(l3.pro);
fflush(stdin);
printf("RAM :");
scanf("%d", &l3.ram);
printf("ROM (HDD/SSD) :");
scanf("%f", &l3.rom);
printf("MRP (in Rs) :");
scanf("%f", &l3.mrp);
fflush(stdin);
printf("\nLaptop details :");
printf("\n1st Laptop");
printf("\nLaptop Company & Model :");
puts(l1.model);
printf("Laptop Processor: ");
puts(l1.pro);
printf("RAM : %d GB", l1.ram);
printf("\nROM (HDD/SSD) : %f GB", l1.rom);
printf("\nMRP Rs. %f ", l1.mrp);
printf("\n\n2nd Laptop");
printf("\nLaptop Company & Model :");
puts(l2.model);
printf("Laptop Processor: ");
puts(l2.pro);
printf("RAM : %d GB", l2.ram);
printf("\nROM (HDD/SSD) : %f GB", l2.rom);
printf("\nMRP Rs. %f ", l2.mrp);
printf("\n\n3rd Laptop");
printf("\nLaptop Company & Model :");
puts(l3.model);
printf("Laptop Processor: ");

Sourabha Malve : 8605400907 https://www.intelliseit.com 55


INTELLISE IT C Programming Language

puts(l3.pro);
printf("RAM : %d GB", l3.ram);
printf("\nROM (HDD/SSD) : %f GB", l3.rom);
printf("\nMRP Rs. %f ", l3.mrp);
}

Initialization of structure objects:


A structure object can be initialized. The initialization can be done using the curly braces.
Syntax:
struct structureName var = {val1, val2, val3, ...};

Note that while initializing a structure object, the values that we specify in curly braces should follow the
sequence and data type of the members belonging to the structure data type.
Example:
#include<stdio.h>
struct Distance
{
int feet;
float inches;
};
void main()
{
struct Distance d1 = {10, 5.6};
struct Distance d2 = {8, 6.0};
printf("\nDistance 1 = %d feet and %f inches.", d1.feet, d1.inches);
printf("\nDistance 2 = %d feet and %f inches.", d2.feet, d2.inches);
}

The typedef keyword:


The typedef is a keyword used in C Programming Language to provide some meaningful names to the existing
types, or variables in the C program. It behaves similarly as we define the alias for the commands. In short,
we can say that the typedef keyword is used to redefine the name of an existing data type/variable.
Syntax:
typedef existingType/Variable aliasName;

Example:
typedef int i;
i d;

In the above example, we have given the alias name to the "int" data type as "i". So now in the further
program integer data type "int" can be referred as "i".
Program:
#include<stdio.h>
struct Vehicle
{
char name[20];
int cc;
float price;
};
void main()
{
typedef struct Vehicle car;

Sourabha Malve : 8605400907 https://www.intelliseit.com 56


INTELLISE IT C Programming Language

//struct Vehicle c1 = {"Audi A8", 1500, 2.5};


car c1 = {"Audi A8", 1500, 2.5};
car c2;
printf("\nMy Car details:");
printf("\nName = ");
puts(c1.name);
printf("Cubic Capacity = %dCC", c1.cc);
printf("\nPrice Rs = %f", c1.price);
printf("\n\nEnter details for your next car:");
printf("\nName = ");
gets(c2.name);
fflush(stdin);
printf("Cubic Capacity = ");
scanf("%d", &c2.cc);
printf("Price Rs = ");
scanf("%f", &c2.price);
printf("\nMy 2nd Car details:");
printf("\nName = ");
puts(c2.name);
printf("Cubic Capacity = %dCC", c2.cc);
printf("\nPrice Rs = %f", c2.price);
}

Assigning values of one object to another that belong to same structure:


Example:
#include<stdio.h>
struct Vehicle
{
char name[20];
int cc;
float price;
};
void main()
{
struct Vehicle v1;
struct Vehicle v2 = {"Pulsar", 150, 1.0};
v1 = v2;
printf("\nVehicle name : %s", v1.name);
printf("\nEngine Cubic Capacity : %d", v1.cc);
printf("\nPrice in Rs : %f", v1.price);
}

The anonymous structure:


Example:
#include<stdio.h>
struct
{
char name[20];
char author[20];
float price;
}b1, b2, b3;
void main()
{
printf("\nEnter a book name:");
gets(b1.name);

Sourabha Malve : 8605400907 https://www.intelliseit.com 57


INTELLISE IT C Programming Language

printf("Enter author name:");


gets(b1.author);
printf("Price MRP:");
scanf("%f", &b1.price);
fflush(stdin);
printf("\nEnter another book name:");
gets(b2.name);
printf("Enter author name:");
gets(b2.author);
printf("Price MRP:");
scanf("%f", &b2.price);
b3 = b2;
printf("\n\nFirst book name:");
puts(b1.name);
printf("Author name:");
puts(b1.author);
printf("MRP Rs:%f", b1.price);
printf("\n\nSecond book name:");
puts(b2.name);
printf("Author name:");
puts(b2.author);
printf("MRP Rs:%f", b2.price);
printf("\n\nThird book name:");
puts(b3.name);
printf("Author name:");
puts(b3.author);
printf("MRP Rs:%f", b3.price);
}

Array within structure:


Example:
#include<stdio.h>
struct Stud
{
int rollNo;
char name[20];
float marks[5];
float per;
};
void main()
{
typedef struct Stud s;
s s1;
int i;
float tot = 0.0;
printf("\nEnter your Roll No:");
scanf("%d", &s1.rollNo);
fflush(stdin);
printf("Enter your name:");
gets(s1.name);
printf("Enter 5 subject marks:");
for(i = 0; i < 5; i++)
{
scanf("%f", &s1.marks[i]);
tot += s1.marks[i];

Sourabha Malve : 8605400907 https://www.intelliseit.com 58


INTELLISE IT C Programming Language

}
s1.per = (tot/500)*100;
printf("\nStudent details are:");
printf("\nRoll No : %d", s1.rollNo);
printf("\nName : ");
puts(s1.name);
printf("5 subject marks : ");
for(i = 0; i < 5; ++i)
printf(" %f ", s1.marks[i]);
printf("\nPercentage : %f", s1.per);
}

Array of a structure:
Example:
#include<stdio.h>
struct Vehicle
{
char name[20];
int cc;
float price;
};
void main()
{
struct Vehicle v[5];
int i;
printf("\nEnter details of 5 vehicles:");
for(i = 0; i < 5; ++i)
{
printf("\nDetails of vehicle %d", (i + 1));
printf("\nVehicle name : ");
gets(v[i].name);
fflush(stdin);
printf("\nEngine Cubic Capacity : ");
scanf("%d", &v[i].cc);
printf("\nPrice in Rs : ");
scanf("%f", &v[i].price);
fflush(stdin);
}
printf("\nDetails of 5 vehicles:");
for(i = 0; i < 5; ++i)
{
printf("\n\nDetails of vehicle %d", (i + 1));
printf("\nVehicle name : %s", v[i].name);
printf("\nEngine Cubic Capacity : %d", v[i].cc);
printf("\nPrice in Rs : %f", v[i].price);
}
}

Structure within structure:


Program:
#include<stdio.h>
struct Dist
{
int feet;

Sourabha Malve : 8605400907 https://www.intelliseit.com 59


INTELLISE IT C Programming Language

float inches;
};
struct Room
{
struct Dist length;
struct Dist width;
};
void main()
{
float ll, wl, lk, wk, al, ak;
struct Room living = {{16, 8.0}, {20, 5.5}};
struct Room kitchen;
printf("\nEnter length of kitchen in feet and inches:");
scanf("%d %f", &kitchen.length.feet, &kitchen.length.inches);
printf("\nEnter width of kitchen in feet and inches:");
scanf("%d %f", &kitchen.width.feet, &kitchen.width.inches);
ll = living.length.feet + living.length.inches/12.0;
wl = living.width.feet + living.width.inches/12.0;
printf("\nTotal Length of Living room %f", ll);
printf("\nTotal Width of Living room %f", wl);
al = ll * wl;
printf("\nArea of Living room %f", al);
lk = kitchen.length.feet + kitchen.length.inches/12.0;
wk = kitchen.width.feet + kitchen.width.inches/12.0;
printf("\nTotal Length of Kitchen room %f", lk);
printf("\nTotal Width of Kitchen room %f", wk);
ak = lk * wk;
printf("\nArea of Kitchen room %f", ak);
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 60


INTELLISE IT C Programming Language

Union:
Union can be defined as a user-defined data type which is a collection of different variables of same or
different data types in the same memory location. The union can also be defined as many members, but only
one member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location.
Syntax:
union unionTag/Name
{
dataType member1;
dataType member2;
...
};

Example:
#include<stdio.h>
union Demo
{
int a;
char b;
float c;
};
void main()
{
union Demo var;
var.a = 15;
printf("\nInteger value in union : %d", var.a);
var.b = 'P';
printf("\nCharacter value in union : %c", var.b);
var.c = 2.5;
printf("\nFloating point value in union : %f", var.c);
}

Structure versus Union:


Program:
#include<stdio.h>
struct DemoS
{
int a;
char b;
float c;
};
union DemoU
{
int a;
char b;
float c;
};
void main()
{
struct DemoS varS;
union DemoU varU;
printf("\nSize of structure variable varS : %d", sizeof(varS));
printf("\nSize of union variable varU : %d", sizeof(varU));
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 61


INTELLISE IT C Programming Language

Program 2:
#include<stdio.h>
struct DemoS
{
int a;
char b;
float c;
};
union DemoU
{
int a;
char b;
float c;
};
void main()
{
struct DemoS varS;
union DemoU varU;
varS.a = 25;
varS.b = 'A';
varS.c = 22.6;
printf("\nStructure variable values.\na : %d", varS.a);
printf("\nb : %c", varS.b);
printf("\nc : %f", varS.c);
varU.a = 25;
varU.b = 'A';
varU.c = 22.6;
printf("\nUnion variable values.\na : %d", varU.a);
printf("\nb : %c", varU.b);
printf("\nc : %f", varU.c);
}

Program 3:
#include<stdio.h>
union DemoU
{
int a;
char b;
float c;
};
void main()
{
union DemoU varU;
varU.a = 25;
printf("\nUnion variable values.\na : %d", varU.a);
varU.b = 'A';
printf("\nb : %c", varU.b);
varU.c = 22.6;
printf("\nc : %f", varU.c);
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 62


INTELLISE IT C Programming Language

Enumeration Type (enum):


Example 1:
#include<stdio.h>
enum Colours {Red, Green, Blue};
void main()
{
enum Colours c1, c2;
int d;
c1 = Red;
c2 = Green;
printf("\nc1 = %d", c1);
printf("\nc2 = %d", c2);
c1 = Blue;
printf("\nc2 - c1 = %d", c2-c1);
}

Example 2:
#include<stdio.h>
enum WeekDays {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
void main()
{
enum WeekDays w1, w2;
int d;
w1 = Thursday;
w2 = Monday;
printf("\nw1 = %d", w1);
printf("\nw2 = %d", w2);
printf("\nThursday - Monday = %d", w1 - w2);
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 63


INTELLISE IT C Programming Language

Pointer:
As you know, every variable is a memory location and every memory location has its address defined which
can be accessed using ampersand (&) operator, which denotes an address in memory.
To know the address/location of a variable, which may belong to any data type, we can use the address of
operator (&).
Program that prints the memory location of variables:
Example:
#include<stdio.h>
void main()
{
int i = 25;
float f = 3.14;
char c = 'A';
printf("\nInteger value of i = %d", i);
printf("\nAddress/location of i = %x", &i);
printf("\nFloating-point value of f = %f", f);
printf("\nAddress/location of f = %x", &f);
printf("\nCharacter value of c = %c", c);
printf("\nAddress/location of c = %x", &c);
}

The pointer in C language is a variable which stores the address of another variable. This pointer variable can
be of type int, char, array, function, structure or any other type of 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’s
address.
Some C Programming tasks are performed more easily with pointers, and other tasks, such as dynamic
memory allocation, cannot be performed without using pointers.
Declaring a pointer variable.
Syntax:
dataType *pointerName;

Example:
int *ptrI;

Allocating address(value) of a variable to a pointer:


Syntax:
pointerName = &variableName;

Example:
ptrI = &i;

Program:
#include<stdio.h>
void main()
{
int i = 25;
int *ptrI;
ptrI = &i;
printf("\nInteger value of i = %d", i);
printf("\nAddress/location of i = %x", &i);
printf("\nAddress/location of i in ptrI = %x", ptrI);
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 64


INTELLISE IT C Programming Language

Accessing value of variable using pointer:


By the help of * (indirection/value at/pointer) operator, we can access the value of the variable to which the
pointer is pointing.
Syntax:
*pointerName;

Example:
#include<stdio.h>
void main()
{
int i = 25;
int *ptrI;
float f = 3.14;
float *ptrF;
char c = 'A';
char *ptrC;
ptrI = &i;
ptrF = &f;
ptrC = &c;
printf("\nInteger value of i = %d", i);
printf("\nInteger value of i using *ptrI = %d", *ptrI);
printf("\nAddress/location of i = %x", &i);
printf("\nAddress/location of i in ptrI = %x", ptrI);
printf("\n\nFloating-point value of f = %f", f);
printf("\nFloating-point value of f using *ptrF = %f", *ptrF);
printf("\nAddress/location of f = %x", &f);
printf("\nAddress/location of f in ptrF = %x", ptrF);
printf("\n\nCharacter value of c = %c", c);
printf("\nCharacter value of c using *ptrC = %c", *ptrC);
printf("\nAddress/location of c = %x", &c);
printf("\nAddress/location of c in ptrC = %x", ptrC);
}

Assigning value to variables using pointers:


To assign value to the variable we can use a pointer with an indirection operator.
Syntax:
*pointerName = value;

The above syntax will set value to the variable without actually using the variable.
Program:
#include<stdio.h>
void main()
{
int i = 28;
float f = 6.2021;
char c = 'P';
int *pI;
float *pF;
char *pC;
pI = &i;

Sourabha Malve : 8605400907 https://www.intelliseit.com 65


INTELLISE IT C Programming Language

pF = &f;
pC = &c;
printf("\n i = %d", i);
printf("\n f = %f", f);
printf("\n c = %c", c);
*pI = 7;
*pF = 2.50;
*pC = 'C';
printf("\n\nAssigning new values to variables using pointer.");
printf("\n i = %d", i);
printf("\n f = %f", f);
printf("\n c = %c", c);
}

Accepting input into variables using pointers:


Program:
#include<stdio.h>
void main()
{
int i = 29;
float f = 6.2021;
char c = 'S';
int *r;
float *s;
char *t;
r = &i;
s = &f;
t = &c;
printf("\n i = %d", *r);
printf("\n f = %f", *s);
printf("\n c = %c", *t);
printf("\nEnter an integer value : ");
scanf("%d", r); //scanf("%d", &i);
printf("\nEnter a floating point value : ");
scanf("%f", s); //scanf("%f", &f);
fflush(stdin);
printf("\nEnter character value : ");
scanf("%c", t); //scanf("%d", &c);
printf("\nValues of variable inputted by user stored using pointer.");
printf("\n i = %d", i);
printf("\n f = %f", f);
printf("\n c = %c", c);
}

Program 2:
#include<stdio.h>
void main()
{
int i = 29;
float f = 6.2021;
char c = 'S';
int *ip;
float *fp;
char *cp;
ip = &i;

Sourabha Malve : 8605400907 https://www.intelliseit.com 66


INTELLISE IT C Programming Language

fp = &f;
cp = &c;
printf("\nEnter a numbers:");
scanf("%d", ip); //scanf("%d", &i);
printf("\nEnter a floating point value : ");
scanf("%f", fp); //scanf("%f", &f);
fflush(stdin);
printf("\nEnter character value : ");
scanf("%c", cp); //scanf("%d", &c);
printf("\nValues of variable inputted by user stored using pointer.");
printf("\n i = %d", *(&i)); //printf("\n i = %d", i);
printf("\n f = %f", *(&f)); //printf("\n f = %f", f);
printf("\n c = %c", *(&c)); //printf("\n c = %c", c);
}

Arithmetic operations using pointer:


Program:
#include<stdio.h>
void main()
{
int no1, no2, result;
int *p1, *p2, *pr;
p1 = &no1;
p2 = &no2;
pr = &result;
printf("\nEnter 2 numbers:");
scanf("%d %d", p1, p2);
*pr = *p1+*p2;
printf("\nAddition of %d and %d is %d", no1, no2, result);
*pr = *p1-*p2;
printf("\nSubtraction of %d and %d is %d", no1, no2, result);
*pr = *p1**p2;
printf("\nMultiplication of %d and %d is %d", no1, no2, result);
*pr = *p1 / *p2;
printf("\nDivision of %d and %d is %d", no1, no2, result);
*pr = *p1%*p2;
printf("\nReminder of %d divided %d is %d", no1, no2, result);
}

Note that:
The data type of the pointer variable should always be the same as of its pointing variable.
The size of the pointer is always of 2/4 bytes irrespective of its data type, this is because a pointer stores
address in it, and memory addresses are of 2 bytes for a 16 bit or 4 bytes for a 32 bit or 8 bytes for a 64 bit
compiler.
Program to display size of pointers, belonging to any type:
#include<stdio.h>
void main()
{
int i = 30, *ptrI;
float f = 6.2021, *ptrF;
char c = 'S', *ptrC;
ptrI = &i;
ptrF = &f;
ptrC = &c;

Sourabha Malve : 8605400907 https://www.intelliseit.com 67


INTELLISE IT C Programming Language

printf("\nValues of variable using indirection and address of operators on variables.");


printf("\n i = %d", *(&i)); //printf("\n i = %d", i);
printf("\n f = %f", *(&f)); //printf("\n f = %f", f);
printf("\n c = %c", *(&c)); //printf("\n c = %c", c);
printf("\n\nSize of variables:");
printf("\ni = %d", sizeof(i));
printf("\nf = %d", sizeof(f));
printf("\nc = %d", sizeof(c));
printf("\n\nSize of pointers:");
printf("\nptrI = %d", sizeof(ptrI));
printf("\nptrF = %d", sizeof(ptrF));
printf("\nptrC = %d", sizeof(ptrC));
}

Swapping of 2 numbers using pointers:


Program:
#include<stdio.h>
void main()
{
int a, b, c, *ptrA, *ptrB, *ptrC;
ptrA = &a;
ptrB = &b;
ptrC = &c;
printf("\nEnter 2 numbers:");
scanf("%d %d", ptrA, ptrB);
printf("\nValues before swapping:");
printf("\na = %d", a);
printf("\nb = %d", b);
*ptrC = *ptrA;
*ptrA = *ptrB;
*ptrB = *ptrC;
printf("\nValues after swapping:");
printf("\na = %d", a);
printf("\nb = %d", b);
}

Array of Pointer:
C Programming language allows us to create an array of pointers. Doing so we are now able to store addresses
of more than 1 variable in 1 pointer.
Syntax:
dataType *pointerName[size];

Program:
#include<stdio.h>
void main()
{
int i, j, k;
int *ptr[3];
ptr[0] = &i;
ptr[1] = &j;
ptr[2] = &k;
printf("\nEnter 2 numbers:");
scanf("%d %d", ptr[0], ptr[1]);
/*if(*ptr[0] > *ptr[1])
*ptr[2] = *ptr[0];

Sourabha Malve : 8605400907 https://www.intelliseit.com 68


INTELLISE IT C Programming Language

else
*ptr[2] = *ptr[1];*/
*ptr[2] = *ptr[0] > *ptr[1] ? *ptr[0] : *ptr[1];
printf("\nGreater value among %d and %d is %d", i, j, k);
}

Swapping of 2 numbers, using Pointer Array (Array of Pointer).


Program:
#include<stdio.h>
void main()
{
int i, j, k;
int *ptr[3];
ptr[0] = &i;
ptr[1] = &j;
ptr[2] = &k;
printf("\nEnter 2 numbers:");
scanf("%d %d", ptr[0], ptr[1]);
printf("\nBefore swapping. no1 = %d, no2 = %d", i, j);
*ptr[2] = *ptr[0];
*ptr[0] = *ptr[1];
*ptr[1] = *ptr[2];
printf("\nAfter swapping. no1 = %d, no2 = %d", i, j);
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 69


INTELLISE IT C Programming Language

Pointer to the Array:


C programming allows us to point a pointer to an array. When a pointer points to an array the starting
address of array, that is the address of the first element (&array[0]), is stored in the pointer. As the pointer
has the starting address of the array, from there the pointer can access the entire array.
Syntax:
dataType array[size];
dataType *pointer;
pointer = array; OR pointer = &array[0];

Program:
#include<stdio.h>
void main()
{
int a[5] = {2, 4, 6, 8, 10}, i;
int *ptr;
ptr = a; // OR ptr = &a[0];
printf("\nArray elements are:");
for(i = 0; i < 5; ++i)
printf("\na[%d] = %d", i, *(ptr + i));
}

Output and Tracing of Memory

Program 2:
#include<stdio.h>
void main()
{
int a[5], i;
int *ptr;
ptr = a; // OR ptr = &a[0];

printf("\nMemory location of array a, using &a[0] = %x", &a[0]);


printf("\nMemory location of array a, using a = %x", a);
printf("\nMemory location of array a, using ptr = %x", ptr);

printf("\n\nMemory locations of elements of array a:");


for(i = 0; i < 5; ++i)
printf("\n&a[%d] = %x", i, &a[i]);

Sourabha Malve : 8605400907 https://www.intelliseit.com 70


INTELLISE IT C Programming Language

printf("\n\nMemory locations of elements of array a, using ptr:");


for(i = 0; i < 5; ++i)
printf("\n&a[%d] = %x", i, (ptr + i));
}

Using array name as pointer:


Program:
#include<stdio.h>
void main()
{
int a[5] = {1, 3, 5, 7, 9}, i;
int *ptr;
ptr = a; // OR ptr = &a[0];
printf("\nArray elements are:");
for(i = 0; i < 5; ++i)
{
printf("\na[%d] = %d", i, a[i]);
printf("\na[%d] = %d", i, *(ptr + i));
printf("\na[%d] = %d", i, *(a + i));
}
}

Accepting input in an array using pointer to the array:


Program:
#include<stdio.h>
void main()
{
int arr[5], i, *p;
p = arr;
printf("\nEnter 5 values :");
for(i = 0; i < 5; ++i)
scanf("%d", (p + i));
printf("\n5 elements in array are : ");
for(i = 0; i < 5; ++i)
printf(" %d ", arr[i]);
}

Program 2:
#include<stdio.h>
void main()
{
int arr[5], i, *p;
p = arr;
printf("\nEnter 5 values :");
for(i = 0; i < 5; ++i)
scanf("%d", (p++));
printf("\n5 elements in array are : ");
for(i = 0, p = arr; i < 5; ++i)
printf(" %d ", *(p++));
}

Pointer to the string:


As a pointer can point to the memory location of any variable, or array, it can also point to string, that is the
character array. When a pointer points to a string, it works in the same way as a string works.

Sourabha Malve : 8605400907 https://www.intelliseit.com 71


INTELLISE IT C Programming Language

Syntax:
char str[size];
char *ptr;
...
ptr = str;
OR
ptr = &str[0];

Program:
#include<stdio.h>
void main()
{
char str[20], *ptr;
ptr = str; // OR ptr = &str[0];
printf("\nEnter your name:");
scanf("%s", ptr);
printf("\nHello %s", ptr);
}

Program 2:
#include<stdio.h>
void main()
{
char str[20], *ptr;
ptr = str; // OR ptr = &str[0];
printf("\nEnter your name:");
gets(ptr);
printf("\nHello ");
puts(ptr);
}

Printing string value character by character using pointer:


Program:
#include<stdio.h>
void main()
{
char s[20], *p;
int i;
p = s; // OR p = &s[0];
printf("\nEnter your name:");
gets(p);
printf("\nHello ");
for(i = 0; s[i] != '\0'; ++i)
printf("%c", *(p + i));
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 72


INTELLISE IT C Programming Language

Functions in C:
Functions are groups of statements logically arranged together to perform a task.
In C, we can divide a large program into the basic building blocks known as functions.
Types of functions:
1. Built-in/library functions
The functions that are predefined that we can directly call/invoke into our program and use them are the
built-in functions.
The C standard library provides numerous built-in functions that your program can call. For example, strcat()
to concatenate two strings, memcpy( ) to copy one memory location to another location, and many more
functions.
Eg: printf( ), scanf( ), gets( ), puts( ), strlen( ), strcpy( ), etc.
2. User-defined functions
The functions that we developers design and write statements in them to execute and perform a task is
known as user-defined function.
A function is a group of statements that together perform a task. Every C program has at least one function,
which is main( ), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions
is up to you, but logically the division is such that each function performs a specific task.
A function can also be referred to as a method or a subroutine or a procedure, etc.
Advantage of functions in C:
● By using functions, we can avoid rewriting the same logic/code again and again in a program.
● We can call C functions any number of times in a program and from any place in a program.
● We can track a large C program easily when it is divided into multiple functions.
● Reusability is the main achievement of C functions.
Disadvantage
● However, function calling is always overhead in a C program.

Aspects of functions in C:
1. Function declaration/function prototype
2. Function definition
3. Function call/invoke
1. Function declaration/function prototype
A function must be declared globally in a C program to inform the compiler about the function name,
parameters/arguments, and return type.
Note that, a function can return minimum 0 to maximum 1 value, and the list of parameters that we pass to a
function can be minimum 0 to maximum N (no limit).
A function declaration tells the compiler about a function's name, return type, and parameters.
Function declaration has to be done before the definition of main( ) function.
It is optional in case we define the function directly, before the main( ) function.
Syntax:
returnType functionName([listOfParameters]);

Example:
void print();
void square(int i);

Sourabha Malve : 8605400907 https://www.intelliseit.com 73


INTELLISE IT C Programming Language

void mangesh(float f);


int sum(int no1, int no2);
float shubham(float, float);
char yash(int, float);

2. Function definition/function body


It contains the actual statements which are to be executed. It is the most important aspect to which the
control comes when the function is called. Here, we must notice that only one value can be returned from the
function.
A function definition provides the actual body of the function.
Syntax:
returnType functionName([listOfParameters])
{
code to be executed on function call
}
Example:
void print()
{
printf("\nHello from function");
return; //optional, in case of void return type
}
int sum(int no1, int no2)
{
int s;
s = no1 + no2;
return s; // This function returns value of variable s
}
void square(int n)
{
int s;
s = n * n;
printf("\nSquare of %d is %d", n, s);
}

3. Function call/Function invoke:


Function can be called from anywhere in the program. The parameter list must not differ in function call and
function declaration/definition.
Syntax:
functionName([listOfParameter]);

Example:
print( );
no = sum(25, 30);
square(no);

Program:
#include<stdio.h>
void print();
void main()
{
print();
}
void print()
{

Sourabha Malve : 8605400907 https://www.intelliseit.com 74


INTELLISE IT C Programming Language

printf("\nHello from function");


return; //optional, in case of void return type
}

Program 2:
#include<stdio.h>
void add();
void sub();
void mul();
void div();
void mod();
void main()
{
printf("Arithmetic Operations:");
add();
sub();
mul();
div();
mod();
printf("\nThank You");
}
void add()
{
int no1, no2, a;
printf("\n\nEnter 2 numbers for addition:");
scanf("%d %d", &no1, &no2);
a = no1 + no2;
printf("Addition of %d and %d is %d", no1, no2, a);
return;
}
void sub()
{
int no1, no2, s;
printf("\n\nEnter 2 numbers for subtraction:");
scanf("%d %d", &no1, &no2);
s = no1 - no2;
printf("Subtraction of %d and %d is %d", no1, no2, s);
return;
}
void mul()
{
int a, b;
printf("\n\nEnter 2 numbers for multiplication:");
scanf("%d %d", &a, &b);
printf("Multiplication of %d and %d is %d", a, b, (a * b));
}
void div()
{
int x, y;
printf("\n\nEnter 2 numbers for division:");
scanf("%d %d", &x, &y);
printf("Division of %d and %d is %d", x, y, (x / y));
}
void mod()
{

Sourabha Malve : 8605400907 https://www.intelliseit.com 75


INTELLISE IT C Programming Language

int i, j;
printf("\n\nEnter 2 numbers for reminder of a division:");
scanf("%d %d", &i, &j);
printf("Reminder of division of %d and %d is %d", i, j, (i % j));
}

Program 3:
#include<stdio.h>
#include<stdlib.h>
void square();
void rectangle();
void circle()
{
float r, area;
printf("\nEnter radius of a circle:");
scanf("%f", &r);
area = 3.14 * r * r;
printf("Area of circle with radius %f is %f", r, area);
return;
}
void triangle()
{
float b, h, area;
printf("\nEnter base and height of a triangle:");
scanf("%f %f", &b, &h);
area = 0.5 * b * h;
printf("Area of triangle with base %f and height %f is %f", b, h, area);
}
void main()
{
int option;
do
{
printf("\n\nPress 1 to get area of circle.\nPress 2 to get area of triangle.");
printf("\nPress 3 to get area of rectangle.\nPress 4 to get area of square.");
printf("\nPress 0 to EXIT:");
scanf("%d", &option);
switch(option)
{
case 1:
circle();
break;
case 2:
triangle();
break;
case 3:
rectangle();
break;
case 4:
square();
break;
case 0:
exit(1);
default:
printf("\nInvalid option number.");

Sourabha Malve : 8605400907 https://www.intelliseit.com 76


INTELLISE IT C Programming Language

}
}while(option != 0);
}
void square()
{
float side;
printf("\nEnter side of a square:");
scanf("%f", &side);
printf("Area of square with side %f is %f", side, (side * side));
}
void rectangle()
{
float len, bre;
printf("\nEnter length and breadth of a rectangle:");
scanf("%f %f", &len, &bre);
printf("Area of rectangle with length %f and breadth %f is %f", len, bre, (len * bre));
}

Types of functions:
1. Function without arguments and without return value.
The function that returns no value and accepts no arguments comes under this type. Here the function's
definition has void as its return type, and the argument list is empty.
General Form:
void functionName()
{
function body...
}

Program:
#include<stdio.h>
void prime()
{
int no, cnt;
printf("\nEnter a number:");
scanf("%d", &no);
for(cnt = 2; cnt < no; ++cnt)
{
if((no % cnt) == 0)
{
printf("\nNumber %d is NOT PRIME", no);
return;
}
}
printf("\nNumber %d is PRIME", no);
}
void main()
{
printf("\nPrime number program:");
prime();
}

2. Function without arguments, but with return value.

Sourabha Malve : 8605400907 https://www.intelliseit.com 77


INTELLISE IT C Programming Language

Functions can return either 0 or only 1 value. When a function returns a value, we need to specify the data
type (return type) of the value that the function is going to return, in function declaration/definition.
This type of function does not accept any arguments, thus its argument list should be empty.
General Form:
returnType functionName()
{
function body...
...
return value/expression;
}

Program:
#include<stdio.h>
int square()
{
int no, sq;
printf("\nEnter a number:");
scanf("%d", &no);
sq = no * no;
return sq;
}
void main()
{
int s;
printf("\nSquare of a number:");
s = square();
printf("\nSquare = %d", s);
}

Program 2:
#include<stdio.h>
float square()
{
float no, sq;
printf("\nEnter a value:");
scanf("%f", &no);
sq = no * no;
return sq;
}
float circle()
{
float area;
area = 3.14 * square();
return area;
}
float triangle()
{
float b, h;
printf("\nEnter 2 values:");
scanf("%f %f", &b, &h);
return (0.5 * b * h);
}
void main()
{

Sourabha Malve : 8605400907 https://www.intelliseit.com 78


INTELLISE IT C Programming Language

float a;
printf("\nArea of a Square:");
a = square();
printf("%f", a);
printf("\n\nArea of a circle:");
printf("%f", circle());
printf("\n\nArea of a triangle:");
printf("%f", triangle());
}

3. Function with arguments, but without return value:


Functions can have minimum 0 and maximum N number of arguments. These arguments are defined in the
argument list. This type has no return value. Thus the return type of this type of function should be void.
General Form:
void functionName(type name1, type name2, ...)
{
function body...
...
}

Program:
#include<stdio.h>
void square(int no);
void main()
{
int n;
printf("\nEnter a number:");
scanf("%d", &n);
square(n);
square(5);
}
void square(int no)
{
int sq;
sq = no * no;
printf("\nSquare of %d is %d", no, sq);
return;
}

Program 2:
#include<stdio.h>
void circle(float r);
void rectangle(float l, float b);
void triangle(float, float);
void main()
{
float var1, var2;
printf("\nEnter radius of a circle:");
scanf("%f", &var1);
circle(var1);
printf("\nEnter length and breadth of a rectangle:");
scanf("%f %f", &var1, &var2);
rectangle(var1, var2);
printf("\nEnter base and height of a triangle:");

Sourabha Malve : 8605400907 https://www.intelliseit.com 79


INTELLISE IT C Programming Language

scanf("%f %f", &var1, &var2);


triangle(var1, var2);
}
void circle(float r)
{
float area;
area = 3.14 * r * r;
printf("Area of circle : %f", area);
return;
}
void rectangle(float len, float bre) // Inline function
{
printf("Area of rectangle : %f", (len * bre));
}
void triangle(float base, float height) // Inline function
{
printf("Area of triangle : %f", (0.5 * base * height));
}

Program 3:
#include<stdio.h>
void studentDetails(int rn, char name[], float per)
{
printf("\nStudent details are : ");
printf("\nRoll No : %d", rn);
printf("\nName : %s", name);
printf("\nPercentage : %f", per);
}
void main()
{
int r = 102;
char n[20] = "Shubham";
float p = 97.5;
studentDetails(101, "Shivanand", 95.6);
studentDetails(r, n, p);
}

4. Function with arguments and return value


Functions have 0 to N number of arguments and can return 0 or only 1 value. Here in this type function
accepts arguments and returns a value.
General Form:
returnType functionName(argument1, argument2, ...)
{
function body...
...
return ...;
}

Program:
#include<stdio.h>
int max(int no1, int no2)
{
int m;
if(no1 > no2)

Sourabha Malve : 8605400907 https://www.intelliseit.com 80


INTELLISE IT C Programming Language

m = no1;
else
m = no2;
return m;
}
int min(int n1, int n2)
{
if(n1 < n2)
return n1;
else
return n2;
}
int avg(int v1, int v2)
{
return ((v1 + v2) / 2); // Inline Function
}
void main()
{
printf("\nMinimum value among 10 and 12 : %d", min(10, 12));
printf("\nMaximum value among 10 and 12 : %d", max(10, 12));
printf("\nAverage of values 10 and 12 : %d", avg(10, 12));
}

Program 2:
#include<stdio.h>
int prime(int no)
{
int cnt;
for(cnt = 2; cnt <= (no/2); ++cnt)
{
if(no % cnt == 0)
return 0;
}
return 1;
}
void main()
{
int n;
printf("\nEnter a number:");
scanf("%d", &n);
if(prime(n))
printf("\nNumber %d is PRIME", n);
else
printf("\nNumber %d is NOT PRIME", n);
}

Inline Function:
The inline function can be substituted at the place where the function call is happening. Function
substitution is always the compiler’s choice.
In an inline function, a function call is replaced by the actual function code.
Most of the Inline functions are used for small computations. They are not suitable for large computing.
An inline function is similar to a normal function.
Program: Refer to the above program.

Sourabha Malve : 8605400907 https://www.intelliseit.com 81


INTELLISE IT C Programming Language

Passing array as argument to the function:


We can pass an array to a function as an argument. Using arrays it is possible to pass multiple values at once
inside a single array variable.
Program:
#include<stdio.h>
float sum(float a[])
{
float tot = 0;
int i;
for(i = 0; i < 5; ++i)
tot += a[i];
return tot;
}
void main()
{
int i;
float m[5], total, per;
printf("\nEnter 5 subject marks:");
for(i = 0; i < 5; ++i)
scanf("%f", &m[i]);
total = sum(m);
per = total * 100 / 500;
printf("\nPercentage = %f", per);
}

Program 2:
#include<stdio.h>
int min(int a[], int size)
{
int i, m, var;
var = a[0];
for(i = 1; i < size; ++i)
{
if(a[i] < var)
var = a[i];
}
return var;
}
int max(int a[], int size)
{
int i, m, var;
var = a[0];
for(i = 1; i < size; ++i)
{
if(a[i] > var)
var = a[i];
}
return var;
}
void main()
{
int i, a[10], size;

Sourabha Malve : 8605400907 https://www.intelliseit.com 82


INTELLISE IT C Programming Language

printf("\nEnter the number values:");


scanf("%d", &size);
printf("\nEnter %d values:", size);
for(i = 0; i < size; ++i)
scanf("%d", &a[i]);
printf("\nMinimum value among the entered values is %d.", min(a, size));
printf("\nMaximum value among the entered values is %d.", max(a, size));
}

Passing character array (string) as argument to the function:


Program:
#include<stdio.h>
int stringLen(char str[])
{
int i;
for(i = 0; str[i] != '\0'; ++i);
return i;
}
void main()
{
char str[20];
printf("\nEnter your name:");
gets(str);
printf("\nNumber of characters in your name are %d", stringLen(str));
}

Returning array from a function:


C programming does not allow returning an entire array as an argument to a function. However, you can
return a pointer to an array by specifying the array's name without an index.
Returning pointer from a function:
Program 1:
Fibonacci
0 1 1 2 3 5 8 13 21 34 55 89 ....
#include<stdio.h>
int* fibonacciSeries(int t, int fibo[])
{
int a = 0, b = 1, c, cnt;
fibo[0] = a;
fibo[1] = b;
for(cnt = 2; cnt < t; ++cnt)
{
c = a + b;
fibo[cnt] = c;
a = b;
b = c;
}
return fibo;
}
void main()
{

Sourabha Malve : 8605400907 https://www.intelliseit.com 83


INTELLISE IT C Programming Language

int *fibo, i, terms, series[20];


printf("\nEnter number of terms to print of Fibonacci series:");
scanf("%d", &terms);
fibo = fibonacciSeries(terms, series);
printf("\n Fibonacci Series : \n");
for(i = 0; i < terms; ++i)
printf(" %d", *(fibo + i));
}

Program 2:
#include<stdio.h>
char* concat(char s1[], char s2[])
{
int len1, len2;
for(len1 = 0; s1[len1] != '\0'; ++len1);
for(len2 = 0; s2[len2] != '\0'; ++len2, ++len1)
{
s1[len1] = s2[len2];
}
s1[len1] = '\0';
return s1;
}
void main()
{
char str1[20], str2[20], *str3;
printf("\nEnter a string:");
gets(str1);
printf("\nEnter another string:");
gets(str2);
str3 = concat(str1, str2);
printf("\nString 1 = %s", str1);
printf("\nString 2 = %s", str2);
printf("\nConcatenation of 2 Strings = %s", str3);
}

Passing Structure object to a function as argument:


Program:
#include<stdio.h>
struct DOB
{
int date;
char month[20];
int year;
};
void display(struct DOB d)
{
printf("%d-%s-%d", d.date, d.month, d.year); //Inline Function
}
void main()
{
struct DOB d1, d2;
printf("\nEnter your date of birth, in dd,mmm,yyyy format :");
scanf("%d", &d1.date);
scanf("%s", &d1.month);

Sourabha Malve : 8605400907 https://www.intelliseit.com 84


INTELLISE IT C Programming Language

scanf("%d", &d1.year);
printf("\nEnter current date, in dd,mmm,yyyy format :");
scanf("%d", &d2.date);
scanf("%s", &d2.month);
scanf("%d", &d2.year);
printf("\nCurrent date = ");
display(d2);
printf("\nYour birth date = ");
display(d1);
}

Program 2:
#include<stdio.h>
struct DOB
{
int date;
char month[20];
int year;
};
void display(struct DOB d)
{
printf("%d-%s-%d", d.date, d.month, d.year); //Inline Function
}
int age(struct DOB dob1, struct DOB dob2)
{
return (dob2.year - dob1.year);
}
void main()
{
struct DOB d1, d2;
printf("\nEnter your date of birth, in dd,mmm,yyyy format :");
scanf("%d", &d1.date);
scanf("%s", &d1.month);
scanf("%d", &d1.year);
printf("\nEnter current date, in dd,mmm,yyyy format :");
scanf("%d", &d2.date);
scanf("%s", &d2.month);
scanf("%d", &d2.year);
printf("\nCurrent date = ");
display(d2);
printf("\nYour birth date = ");
display(d1);
printf("\nYour current age = %d", age(d1, d2));
}

Returning Structure object from a function:


Program:
#include<stdio.h>
struct dist
{
int feet;
float inches;
};
void showDist(struct dist d)

Sourabha Malve : 8605400907 https://www.intelliseit.com 85


INTELLISE IT C Programming Language

{
printf("\nDistance = %d\'-%f\"", d.feet, d.inches);
}
struct dist addDist(struct dist d1, struct dist d2)
{
struct dist d3;
d3.feet = d1.feet + d2.feet;
d3.inches = d1.inches + d2.inches;
if(d3.inches >= 12.0)
{
d3.feet++;
d3.inches -= 12.0;
}
return d3;
}
void main()
{
struct dist dist1, dist2, dist3;
printf("\nEnter feet and inches for 1st distance : ");
scanf("%d %f", &dist1.feet, &dist1.inches);
printf("\nEnter feet and inches for 2nd distance : ");
scanf("%d %f", &dist2.feet, &dist2.inches);
printf("\nFirst ");
showDist(dist1);
printf("\nSecond ");
showDist(dist2);
dist3 = addDist(dist1, dist2);
printf("\nSum of 2 distances ");
showDist(dist3);
return;
}

Passing Pointer to a function as argument:


Types of functions:
1. Function call by value
Up till now the programs that we have seen, in which we have passed arguments to function, were of type
function call by value. This is because when we call a function and pass an argument, the value of argument
is passed, not the original variable.
2. Function call by reference (pointer)
Now we are going to study "function call by reference". Here we pass reference of the variables
(address/pointer) to the function as argument. This will give the access to the variables of caller function to
the calle function.
Example of Function call by value:
Swapping of 2 numbers using function:
#include<stdio.h>
void swap(int n1, int n2)
{
int temp;
temp = n1;
n1 = n2;
n2 = temp;

Sourabha Malve : 8605400907 https://www.intelliseit.com 86


INTELLISE IT C Programming Language

}
void main()
{
int no1, no2;
printf("\nEnter 2 numbers:");
scanf("%d %d", &no1, &no2);
printf("\nValues before swapping:");
printf("\nNo1 = %d, No2 = %d", no1, no2);
swap(no1, no2);
printf("\n\nValues after swapping:");
printf("\nNo1 = %d, No2 = %d", no1, no2);
}

Example of Function call by reference:


Swapping of 2 numbers using function:
#include<stdio.h>
void swap(int *n1, int *n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
void main()
{
int no1, no2;
printf("\nEnter 2 numbers:");
scanf("%d %d", &no1, &no2);
printf("\nValues before swapping:");
printf("\nNo1 = %d, No2 = %d", no1, no2);
swap(&no1, &no2);
printf("\n\nValues after swapping:");
printf("\nNo1 = %d, No2 = %d", no1, no2);
}

Returning pointer (reference) from a function:


Program:
#include<stdio.h>
int* max(int *, int*);
void main()
{
int a, b, *p;
printf("\nEnter 2 numbers:");
scanf("%d %d", &a, &b);
p = max(&a, &b);
printf("\nMax value = %d", *p);
}
int* max(int *p1, int *p2)
{
if(*p1 > *p2)
return p1;
else
return p2;
}

Sourabha Malve : 8605400907 https://www.intelliseit.com 87


INTELLISE IT C Programming Language

Recursion:
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.
General Form:
returnType functionName([lisOfParameters])
{
...
functionName([listOfParameters]); //Function calls itself
...
}
void main( )
{
...
functionName([listOfParameters]);
...
}

Program:Factorial of a number, without recursion:


#include<stdio.h>
int factorial(int no)
{
int i, fact = 1;
for(i = no; i > 0; --i)
{
fact = fact * i;
}
return fact;
}
void main()
{
int n, fact;
printf("\nEnter a number:");
scanf("%d", &n);
fact = factorial(n);
printf("\nFactorial of %d is %d", n, fact);
}

Program: Factorial of a number, using recursion:


#include<stdio.h>
int factorial(int no)
{
if(no == 1 || no == 0)
return 1;
else
return (no * factorial(no - 1));
}
void main()
{
int n, fact;
printf("\nEnter a number:");
scanf("%d", &n);
fact = factorial(n);
printf("\nFactorial of %d is %d", n, fact);

Sourabha Malve : 8605400907 https://www.intelliseit.com 88


INTELLISE IT C Programming Language

End of Syllabus.

Sourabha Malve : 8605400907 https://www.intelliseit.com 89

You might also like