2021 April C Prog
2021 April C Prog
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”);
}
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
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
...
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, …;
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’;
Example:
int no = 30;
float pi = 3.14;
char c = ‘S’;
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));
}
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);
}
Compilation process in C:
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));
}
● 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.
● 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--;
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);
no = i;
ch = c;
fl = f;
printf("\nInteger value = %d", no);
printf("\nCharacter value = %c", ch);
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);
}
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);
}
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");
}
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.");
}
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()
{
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.");
}
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
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);
}
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");
}
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;
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;
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");
}
}
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.");
}
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.");
}
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);
}
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.");
}
Program:
#include<stdio.h>
void main()
{
int no = 1;
while(1)
{
printf(" %d ", no);
++no;
}
}
Program:
#include<stdio.h>
void main()
{
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.");
}
OR
for (initialization ; condition ; )
{
statement(s)
…
}
OR
for ( ; condition ; )
{
statement(s)
…
}
OR
for ( ; ; )
{
statement(s)
…
}
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.");
}
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;
}
printf("\nThank you.");
}
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);
}
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)
{
…
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;
}
}
*
* *
* * *
* * * *
* * * * *
#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");
}
}
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;
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 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>
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};
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]);
}
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?
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];
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:
#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]);
}
}
}
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:
{
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");
}
}
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];
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");
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);
}
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:
#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);
}
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);
}
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);
}
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);
}
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;
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]);
}
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;
};
Example:
struct Student s1;
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);
}
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));
}
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);
puts(l3.pro);
printf("RAM : %d GB", l3.ram);
printf("\nROM (HDD/SSD) : %f GB", l3.rom);
printf("\nMRP Rs. %f ", l3.mrp);
}
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);
}
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;
}
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);
}
}
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);
}
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);
}
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);
}
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);
}
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;
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);
}
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);
}
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;
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);
}
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;
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);
}
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;
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];
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);
}
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));
}
Program 2:
#include<stdio.h>
void main()
{
int a[5], i;
int *ptr;
ptr = a; // OR ptr = &a[0];
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++));
}
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);
}
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);
Example:
print( );
no = sum(25, 30);
square(no);
Program:
#include<stdio.h>
void print();
void main()
{
print();
}
void print()
{
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()
{
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.");
}
}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();
}
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()
{
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());
}
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:");
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);
}
Program:
#include<stdio.h>
int max(int no1, int no2)
{
int m;
if(no1 > no2)
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.
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;
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);
}
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));
}
{
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;
}
}
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);
}
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]);
...
}
End of Syllabus.