Professional Documents
Culture Documents
Introduction
C is the middle level procedure oriented structured computer programming language developed by
Dennis Ritchie in the 1972 at AT & T Bell Laboratory of USA. C is the middle level computer programming
language because it supports both of the features of high level and low level computer programming
languages.
The different structured programming languages are like: PASCAL, Ada, Java, C++, C,
Modula -2, etc. where as some unstructured languages are like: FORTRAN, BASIC,
COBOL etc.
History of C Language:
In the year 1960 the programming language has developed by international comity called ALGOL –
60.
In the year 1963 the programming language has developed by Cambridge University called CPL
(Combined Programming Language).
In the year 1967 the programming language has developed by Martin Richard at Cambridge
University called BCPL (Basic Combined Programming Language).
In the year 1969 the programming language has developed by Ken Thompson at AT & T Bell
laboratory called B.
In the year 1972 C has developed.
C Compilers and Editors:
There are several C Compilers and editors are available in market such are:
1. Borland C Compiler: earlier used in DOS environment
2. Turbo C Compiler: These days used in DOS environment. It comes with different versions such are:
Turbo C 2.0, Turbo C 3.0, Turbo C 4.5 (used in Windows environment).
3. ANSI C Compiler: used in both DOS and Unix environment.
4. GCC Compiler: GNOME C Compiler only meant for UNIX and LINUX environment.
5. Tiny C Compiler: used in UNIX environment
6. Ciz Win Compiler: Unix flavor windows environment.
7. Visual C / C++ Compiler: only meant for windows environment.
Turbo C 3.0:
This is the Compiler cum editor environment where we can create or develop the C or C++
programs. Turbo means adding extra features.
How to open Turbo C++ IDE (IDE refers to Integrated development environment)
Procedure1:
Double click over the turbo C++ IDE over the desktop screen.
Procedure2:
Open DOS prompt
Change the directory to the root drive. Cd\
Search for the file TC.EXE
o If found then change the directory to the target(cd TC\BIN ), Type TC press enter
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 2
o If not found then change the drive (drivename: ) and follow step2
Skeleton of C Program:
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 3
#include <headerfilename.h>
global variable declaration;
main() {
local variable declaration;
statement1;
statement2;
…………………
statementn;
}
Comment:
Comment is a phrase of word given to any subject or object, which specify something about it.
The comments in a C program can be added in two different ways such are:
1. Single line Comment can be preceded by double forwarded slash as // Comment Line
2. Multi line Comment can be enclosed by /* and */ as
/* Comment Line 1
Comment Line 2
“””””””””””””””
Comment Line n */
# include<headerfilename.h>
# is the pre processor sign, which specify that the followed statement must be processed before
executing the main().
Include is the inclusion directive use to include the enclosed header file to the current program
so that the programmer can use the belonging statements or the facilities provided by the particular
header file.
< > angular bracket use to search the enclosed file in the include directory specified in the
option menu of directory option. Instead of < > we can use double quote “ ” because the “ ” will search
for the file in the include directory as well as in the current working directory.
.h is the extension name of the header file.
Variable
Variable is the namely location at memory can capable to contain the value, the value of the
variable is changes or varies through out the program. The variable is otherwise called as identifier
because it identify the value from the memory through a symbolical name. Variable is the reference
name of the value in the memory. The variables are of two types:
1. Local variable: The variables, which are declared inside a block and can be used or accessed
inside that block only is called as local variable. It has the local scope.
2. Global variable: These variables are declared at the global area that is just after the header file
declaration and before the main() block. These variable has the global scope and can use or
accessed inside any block in the program.
Rules for declaring a variable
The variablename can be any name but should follow the following rules:
1. The first character of the variablename must be alphabetic.
2. The variablename should not exceed more than 31 characters.
e.g. student_roll is the variable name having 12 characters this like there should not be
more than 31 characters in variable name.
3. The variablename should not contain any space between it, for the space we can use
underscore sign ( _ ) instead of any other symbol. e.g. student_name
4. The same variablename can’t be declared more than once in a same scope.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 4
1. Integer: These type variables can capable to contain the whole number values. It is of two types
such are:
a. Signed Integer: These type variables can capable to contain numerical whole number
values. E.g. 23, 452, 98, 60 etc. It is of three types such are:
i. signed short int
ii. signed int
iii. signed long int
b. Unsigned Integer: These type variables can capable to contain alpha numerical whole
number values. E.g. 0x27, A4, etc It is of three types such are:
i. unsigned short int
ii. unsigned int
iii. unsigned long int
Note: These are categorized according to their size and range.
2. Character: These type variables can contain character type value. This is of two types:
c. signed char : alphabetical values e.g. ‘Q’, ‘D’, ‘S’, etc
d. unsigned char: alphanumerical values. E.g. ‘0X27’, ‘0X32’, etc.
3. Float: These type variable can capable to contain the real numbers or floating type or decimal
point values. e.g. 12.765, 78.5213, etc. It is of three types.
e. float
f. double
g. long double
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 5
C Tokens
There are certain symbols or keywords used for better communication that are called as Tokens, C also
uses certain Tokens are like:
1. Identifiers
2. Datatype
3. KeyWords
4. Constants
5. Type Specifiers
6. Escape Sequences
7. Operators
1. Identifiers: The
2. Datatype
3. KeyWords
4. Constants: These are the identifiers, whose value will not change throughout the program.
a. Numerical Constants
i. Integer Constants: whole number values e.g. 234, 78, 45 etc
ii. Real Constants: floating type values e.g. pi=3.142 etc
b. Character Constants
i. Single Character Constants: e.g. ‘T’, ‘P’, ‘Z’, etc.
ii. String Constants: “Ashok”, “Berhampur”, “23-Jan-1986”, etc.
5. Type Specifiers: These are otherwise called as format descriptors, because it specify or describes
about the type or the format of the both input and output values. It is used with both I/O
statements. These are preceded by modulus sign. The different format descriptors are:
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 6
6. Escape Sequences: These are the characters preceded by back slash ( \ ) character, used with
output statements, generally escaped from the compiler to be interpret. These has their own
meaning to the compiler. The different escape sequences are:
\a Beep the speaker once
\b Back space
\n Create a new line
\t Create a horizontal tab
\r Carriage return
\\ Print \
\? Print ?
\’ Print ‘
\” Print “
7. Operators: These are the symbols used with one or more operands to do operation over them.
The different operators are like:
a. Arithmetic Operator: used for math calculations, e.g. +, -, *, / and %(modulus: it
retrieves the reminder).
b. Relational Operators: used with conditional statements, e.g. <, >, <=, >=, == (equals), !=
(not equal to).
c. Assignment Operators: used to assign the right expression result to the left operand,
e.g. =, +=, -=, *=, /=, %=.
e.g. a=5;
a+=6; (i.e. a=a+6;)
print a; 11
d. Increment / decrement Operators: These can be of two types use to increase or
decrease the value of the operand by one.
i. Pre increment / decrement operators:
e.g. a=5;
print ++a; 6
print a;6
ii. Post increment / decrement operators:
e.g. a=5;
print a++;5
print a;6
e. Logical Operators: The logical operators are used in Boolean algebra or in logics or in
discrete mathematics.
e.g. && - logical AND
|| - logical OR
! – logical NOT
f. Bitwise Operators: These operators are used for bit level manipulations.
>> right shift operator. it will remove a Zero (0) from the right side of the binary
equivalent of the given number according to the given number. a=64; b=a>>1;
print b; 32
<< left shift operator . it will add a Zero (0) at the right side of the binary
equivalent of the given number according to the given number. a=64;
b=a<<1; print b; 128
g. Conditional Operators: ? and : are the two different conditional operators used together
for conditional statements, these are otherwise called as ternary operator.
Syntax: (condition)? Statement1: statement2;
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 7
Stdio.h
For the standard input and output operations we need of stdio.h header file. Stdio stands for standard
input and output (I/O). The different statements are belonging to this header file are :
1. printf(): This is the formatted output statement use to send the given message to the standard
output screen.
Syntax: printf(“Output Message”);
if we require to display the value of any variable then
printf(“typespecifier with Output Message”, variablename);
if we require to display more than one variable values then
printf(“typeSpecifier1 ts2 … tsn”,varname1, vnm2, …, vnmn);
The number of type specifiers and variable names must correspondent, i.e. identically same to the
sequence as well as numbers.
Q> WAP to display “Hello World”.
#include ”stdio.h”
main() {
printf(“\nHello World”);
}
Q> WAP to print “Hello World” with double quote.
}
main() {
int a, b; int a=7, b;
a=7;
b=a*a;
printf(“\nThe Number is : %d”,a);
printf(“\nThe Square is : %d\nThe Cube is : %d”, b, (a*a*a));
}
Q> WAP to assign the radius of a circle, calculate and display it’s area.
Q> WAP to assign two values to two variables, calculate and display it’s multiplication result.
Q> WAP to assign two values to two variables, calculate and display it’s addition, subtraction,
multiplication and division result.
2. scanf(): is the input statement use to input the value to the program variable during run time.
Synatax:
scanf(“typeSpecifier”, &variablename);
if we require to input more than one variable values then
scanf(“ts1 ts2 . . . tsn”, &varname1, &varnm2, . . . , &variablenamen);
e.g.
Q1> WAP to input two numbers, calculate and display the addition result.
#include “stdio.h”
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 8
main() {
int a, b, c=0;
printf(“\nEnter Two Numbers : ”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“\nThe Addition Result is : %d”, c);
}
Q2> WAP to input the principal amount, rate and time; calculate and display the simple interest.
Hint: SI=(PRT)/100
Q3> WAP to input the radios of a circle, calculate and display the area and perimeter.
Q4> WAP to input the year of birth, calculate and display the age.
Q5> WAP to input the five marks of a student, calculate and display the total and Percentage.
Q6> WAP to input two numbers, calculate and display the addition, subtraction, multiplication and
division result.
conio.h
conio stands for console input and output. The different statements belongs to this header file
are:
1. clrscr(); use to clear the output user screen.
2. getche(); use to wait to get a character during run time.
3. getch(); use to wait to get a character during run time, where as the entered character will not
prompt or shown to the user while entering.
e.g. WAP to input an alphabet print it’s ASCII value.
#include “stdio.h”
#include “conio.h”
main() {
char ch;
clrscr();
printf(“\nEnter an Alphabet : ”);
ch=getche(); // scanf(“%c”, &ch);
printf(“\nThe ASCII value is : %d”, ch);
getch();
}
4. textmode(mode); It will set the text mode of the console output.
5. textcolor(color); It will set the text color of the console output.
6. textbackground(color); It will set the text background color of the console output.
The text modes can be C40, C80, BW40, BW80.
Text colors can be 0 to 15 that are 0 BLACK, 1 BLUE, .. , 15 WHITE.
These can be applied to cprintf() statement as like the printf() statement.
e.g. WAP to display the “Hello World”.
#include “stdio.h”
#include “conio.h”
main() {
clrscr();
textmode(C40);
textcolor(BLUE);
textbackground(15);
cprintf(“Hello World”);
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 9
getch();
}
Type Casting:
Caste or change the type of the value according to the user requirement is called as type casting
or type conversion. The type casting can be of two different types such are:
1. Implicit type casting
2. Explicit type casting
1. Implicit type casting: By using implicit type casting we can change the type of the value
internally that is mostly by using type specifiers.
e.g. int num=65;
printf(“\nThe character value is : %c”,num); i.e. it will print ‘A’
like the same way each every characters has an ASCII value that is from 0 to 255.
65 – 90 A to Z
97 – 122 a to z
e.g. float num=45.8979;
printf(“The Number is : %d”,num); i.e. it will print 45
2. Explicit type casting: can be performed externally as:
e.g. int a=65, b=90;
float c;
c=(float)(a+b)/2;
printf(“The Middle Value is : %f”, c);
Constructs
There are certain keywords use to control the data flow in the program and called as Control Statements
or Decision making and Branching Statements or decision control statements or constructs.
There are two different types of constructs such are :
1. Selection Constructs
2. Iteration Constructs
1. Selection Constructs: These are the decision making statements or the keywords used to
select a block of statements to execute if the condition is true. The different selection constructs
are :
a. If condition: This is the selection construct use to execute a block of statements if
the condition is true.
Syntax: if (condition){
statement 1;
statement 2;
||||||
statement n;
}
e.g. Q> WAP to input a number check for greater than 100 or not.
#include “stdio.h”
#include “conio.h”
main() {
int num;
clrscr();
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 10
#include “stdio.h”
#include “conio.h”
main() {
int n;
clrscr();
printf(“\nEnter a Number from 5 to 9 :”);
scanf(“%d”,&n);
if((n>=5) && (n<=9)) {
if(n==5)
printf(“\n Five”);
else
if(n==6)
printf(“\n Six”);
else
if(n==7)
printf(“\n Seven”);
else
if(n==8)
printf(“\n Eight”);
else
printf(“\n Nine”);
}
else{
printf(“\n Invalid Number : The Entered Number Must between 5 to 9”);
}
getch();
}
Q> WAP to input three numbers, display the greater one.
#include “stdio.h”
#include “conio.h”
main() {
int a, b, c;
clrscr();
printf(“\nEnter three Numbers : ”);
scanf(“%d%d%d”, &a, &b, &c);
if(a>b){
if(a>c)
printf(“\n %d is Greater ”, a);
else
printf(“\n %d id Greater”, c);
}
else{
if(b>c)
printf(“\n %d is Greater”, b);
else
printf(“\n %d is Greater”, c);
}
getch();
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 12
Jumping Statement: goto is the jumping statement use to jump the program control to a specified
label to execute from there.
Syntax: goto labelname;
The labelName can be any name but should follows the rules for declaring a variable name. the label
name can be declared as
labelName:
e.g. Q> WAP to print your name 10 times using goto statement.
#include “stdio.h”
#include “conio.h”
main() {
int i=1;
clrscr();
hhLabel:
printf(“\nLokanath”);
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 13
if ((++i)<=10)
goto hhLabel;
getch();
}
Iteration Constructs: Iteration means repetition. These are otherwise called as looping statements
or looping constructs, use to execute a block of statements repeatedly again and again till the condition
is true. The different iteration constructs are for loop, while loop and do while loop are used in C
language.
e. For loop: This is the simplest iteration construct used in C language use to execute a
block of statements repeatedly again and again till the condition is true, it has three
different parameters as :
Syntax:
for(initialization; condition; increment/decrement) {
statement 1;
statement 2;
|||||||||||
statement n;
}
Note : The initialization statement will execute once throughout the continuity, where as the condition
and increment / decrement will execute each time of continuity.
e.g. Q> Write a program to print your name 10 times with the serial number.
#include “stdio.h”
#include “conio.h”
main() {
int i;
clrscr();
for(i=1; i<=10; i++){
printf(“\n%d. Lokanath”, i);
}
getch();
}
Q> WAP to input a number, print 1 to that number.
Q> WAP to input two numbers, print the range.
Q> WAP to print all the even numbers from 20 to 50.
Q> WAP to input a number, print the jar table of that number.
Q> WAP to print all the even and odd numbers between 1 to 50 as
Even Odd
1
2 3
4 5
6 7
- -
- -
48 49
50
f. Nested for loop: When a for loop is placed inside another for loop that is called as
nested for loop. In this case the inner loop will execute full time by executing the outer
loop once.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 14
1 2 3 4 5
11111 12345 1 1 1
22222 12345 12 22 23
33333 12345 123 333 456
44444 12345 1234 4444 7 8 9 10
55555 12345 12345 55555
9 10 11
6 7 8
* * * ***** ***** * * * *
*
** ** ** **** **** ****
*** *** *** *** *** ***
**** **** **** ** ** **
***** ***** ***** * * *
12
*****
****
***
**
*
**
***
****
*****
Answer
1>
#include “stdio.h”
#include “conio.h”
main (){
int i, j;
clrscr();
for(i=1; i<=5; i++){
for(j=1; j<=5; j++)
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 15
printf(“%d ”, i);
printf(“\n”);
}
getch();
}
6>
#include “stdio.h”
#include “conio.h”
main (){
int i, j;
clrscr();
for(i=1; i<=5; i++){
for(j=1; j<=i; j++)
printf(“* ”);
printf(“\n”);
}
getch();
}
g. While loop: This is the iteration construct use to execute a block of statements
repeatedly again and again till the condition is true. The basic difference between the
for loop and while loop is : in case of for loop the programmer is well known about the
time of repetition, where as in case of while loop the programmer may unknown about
the time of repetition.
syntax:
while(condition) {
statement1;
statement2;
~~~~~~~~~~
statementn;
}
e.g. Q> WAP to input a number, print from that number to 1.
#include “stdio.h”
#include “conio.h”
main(){
int n;
clrscr();
printf(“\nEnter a Number :”);
scanf(“%d”,&n);
while(n>=1){
printf(“\n%d”,n);
n--;
}
getch();
}
Q> WAP to input a number, check for prime or not. (the number is only divisible by 1 and itself)
Q> WAP to input a number, print it’s each digit in one – one line.
Q> WAP to input a number, calculate and display the sum digit value.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 16
Q> WAP to input a number, check for Armstrong or not. (the number is equal to sum of it’s each digit
cube like 153=13 + 53 + 33 1*1*1 + 5*5*5 + 3*3*3 1+125+27 153)
Q> WAP to input a number, check for palindrome or not (the number is equal to it’s reverse like 131,
898, 77, 969, 12321 etc).
Q> WAP to print all the palindrome numbers between 1 to 100.
Q> WAP to print all the Armstrong numbers from 10000 to 1.
h. Do while loop: This is as like the while loop, the difference is In case of while loop
the program controller first check the condition and if true then only will enter into the
loop and execute the block, where as in case of do while loop first it will execute the
block, then check the condition for next execution.
syntax:
do{
statement1;
statement2;
””””””””””
statement;
}while(condition);
e.g. Q> WAP to input two numbers and print the sum, continue the whole process upto user desire.
#include “stdio.h”
#include “conio.h”
main(){
int a, b;
char ch;
clrscr();
do{
printf(“\nEnter two Numbers : ”);
scanf(“%d%d”,&a,&b);
printf(“\nThe Addition Result is : %d”, (a+b));
printf(“\nDo U Want to Continue (y/n): ”);
ch=getche();
}while(ch== ‘y’ || ch== ‘Y’);
getch();
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 17
ctype.h
ctype stands for character type, this header file facilitate different statements like:
1. isdigit (char): Use to check the given character for digit or not.
2. isalpha(char): Use to check the given character for alphabet or not.
3. isupper(char): Use to check the given character for upper case or not.
4. islower(char): Use to check the given character for lower case or not.
5. isspace(char) : Use to check the given character for space or not.
These all statements or pre defined functions are used with conditional operators or tertiary operators
as:
main() {
char ch;
printf(“\nEnter a Character : ”);
getche(ch);
isalpha(ch)? printf(“\n Alphabet :”): printf(“\nNot an Alphabet”);
getch();
}
Q> Write two programs to input a character, check for digit or alphabet or space or non of these, if
alphabet then check for upper case or not using ctype.h and with out using ctype.h.
Answer1: Using ctype.h
#include “stdio.h”
#include “conio.h”
#include “ctype.h”
void main() {
char ch;
clrscr();
printf(“Enter a Character : ”);
ch=getche();
isdigit(ch)? printf(“\nDigit”): isspace(ch)? printf(“\nSpace”): isalpha(ch)? isupper(ch)?
printf(“\nAlphabet in UPPER CASE”): printf(“\nAlphabet in lower case”): printf(“\nNot an Alphabet, Not
a Space and Not even a Digit”);
getch();
}
Answer2: Without Using ctype.h
#include “stdio.h”
#include “conio.h”
void main() {
char ch;
clrscr();
printf(“Enter a Character : ”);
ch=getche();
((ch>=48) && (ch<=57))? printf(“\nDigit”): (ch==32)? printf(“\nSpace”): (((ch>=65) && (ch<=90))
||((ch>=97) &&(ch<=122)))? ((ch>=97) &&(ch<=122))? printf(“\nAlphabet in UPPER CASE”):
printf(“\nAlphabet in lower case”): printf(“\nNot an Alphabet, Not a Space and Not even a Digit”);
getch();
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 18
STRING
The combination of multiple characters is called as string. The string is otherwise called as
character array. It is the character type. The string variable must have a size that is the
maximum number of characters can be contained by string variable.
e.g.
char varName[size];
%s and %[^\n] are used for string output and input purpose.
#include “stdio.h”
#include “conio.h”
main(){
char name[50];
clrscr();
printf(“\nEnter Your Name : ”);
scanf(“%[^\n]”,&name);
printf(“\nYour Name is : %s”,name);
getch();
}
The string is ended with NULL (‘\0’) character, each and every character of the string has an index value
that starts from 0 (Zero) as:
name[0]= ‘W’;
name[1]= ‘E’;
name[2]= ‘L’;
name[3]= ‘C’;
name[4]= ‘O’;
name[5]= ‘M’;
name[6]= ‘E’;
name[7]= ‘\0’;
printf(“%c”, name[3]); C
Q> WAP to input your name and print each character in a separate line.
#include “stdio.h”
#include “conio.h”
main(){
char name[50];
int i;
clrscr();
printf(“\nEnter Your Name : ”);
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 19
scanf(“%[^\n]”,&name);
for(i=0; name[i]!= ‘\0’; i++);
printf(“\n%c”,name[i]);
printf(“\nThe Length is : %d”, i);
getch();
}
Q> WAP to find out the length of an entered string, length specify the number of characters contained
by the string including space.
Q> WAP to input a string, copy it to another.
Q> WAP to input two strings and concatenate them or merge them into another.
Q> WAP to input a string print it’s reverse.
Q> WAP to input a string check for palindrome or not.
Q> WAP to input a paragraph, calculate and display the number of character including space, number of
characters excluding space, number of words, number of sentence contained by paragraph, change the
character case according to user chosen option, the different character cases are Sentence case, UPPER
CASE, lower case, Title Case, tOGGLE cASE.
Q> WAP to input a paragraph, find a particular character or word and replace it.
string.h
This header file provides different statements to manipulate the string easily inside the program. The
different statements are like: strlen(), strcat(), strlwr(), strupr(), strcpy() etc.
strlen(string);
It will return the length of the given string that is the number of characters contained by the string
including space.
e.g. WAP to input a string, display the length.
#include “stdio.h”
#include “conio.h”
#include “string.h”
main(){
int Ln;
char name[100];
clrscr();
printf(“\nEnter The String : ”);
scanf(“%[^\n]”,&name);
Ln=strlen(name);
printf(“\nThe Length of the given String is : %d”,Ln);
getch();
}
strcpy(string1, string2);
Use to copy the string2 to string1
e.g.
#include “stdio.h”
#include “conio.h”
#include “string.h”
main(){
char name[100], name2[100];
clrscr();
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 20
Array:
Array is a type of variable can capable to contain a group of homogeneous data elements. Array
must have a size i.e. the maximum number of elements can be contained by the array. Each and every
elements are refers by a single name with having different index number. The array is of two types.
1. Single Dimensional Array
2. Multi Dimensional Array
1. Single Dimensional Array: This stores the elements in a single row format. It has a single
size. Each and every elements has an index number. it is declared as :
datatype arrayVariableName[size];
e.g. int arr[5]={14, 6, 64, 32, 42};
We can’t initialize more values than the size, and it is better to initialize 0 instead of blank if the number
of elements are less than the size.
e.g. int num[10]={45, 7, 79, 123, 56, 78, 0, 0, 0, 0};
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 21
#include “stdio.h”
#include “conio.h”
main(){
int num[10], i;
clrscr();
printf(“\nEnter 10 numbers : ”);
for(i=0; i<10; i++)
scanf(“%d”,&num[i]);
printf(“\nThe Array Elements are : ”);
for(i=0; i<10; i++)
printf(“\nnum[%d] = %d”,i,num[i]);
getch();
}
Q> WAP to input 5 numbers to an array, calculate and display the sum value of all the elements.
#include “stdio.h”
#include “conio.h”
main(){
intr num[5], i, sum=0;
printf(“\nEnter 5 Numbers to an Array : ”);
for(i=0; i<5; i++)
scanf(“%d”,&num[i]);
printf(“\nThe Array Elements or the entered values are : ”);
for(i=0; i<5; i++){
printf(“\nnum[%d] = %d”, i, num[i]);
sum=sum+num[i];
}
printf(“\nThe Sum Value of all the elements is : %d”, sum);
getch();
}
Q> WAP to input 10 numbers, find and display the greater one and smaller one.
Q> WAP to input 10 numbers to an array, display the 2 nd highest value.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 22
Q> WAP to input 10 numbers, arrange them in ascending and in descending order.
2. Multi dimensional Array:
a. Two Dimensional Array: By using two dimensional array we can store the elements in
row and column manner that is in matrix form we can manipulate the elements. we
need to provide the row number and column number, each row having same number of
columns that is as :
datatype arrvarName[rowNo][colNo];
e.g.>
int num[4][3]= { 3, 5, 7,
5, 8, 9,
2, 5, 8,
1, 7, 9
};
The row and column numbers are the index numbers starts with 0 (zero) the columns are increased
towards right and rows are increased towards down i.e.
- 0 1 2
0 3 5 7
1 5 8 9
2 2 5 8
3 1 7 9
Q> WAP to input a matrix of 4:3 and display them as in matrix form.
#include “stdio.h”
#include “conio.h”
main(){
int num[4][3], i, j, row, col;
clrscr();
printf(“\nEnter a 4:3 Matrix :”);
for(row=0; row<4; row++)
for(col=0; col<3; col++)
scanf(“%d”,&num[row][col]);
printf(“\nThe Elements are like\n”);
for(i=0; i<4; i++){
for(j=0; j<3; j++)
printf(“%d ”,num[i][j]);
printf(“\n”);
}
getch();
}
Q> WAP to input a 3:3 matrix, calculate and display the sum of all the elements and each row sum.
Q> WAP to input a 5:5 matrix, calculate the sum and display as they as following:
Left Diagonal Right Diagonal Left Lower Triangle Right Lower triangle
12345 12345 12345 12345
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 23
b. Three Dimensional Array: In three dimensional array we need to provide three different
size, the first size for table number, second one is for row number and third one is the
column number as, each table having same number of rows and columns.
int num[2][3][3]= {
2, 5, 7,
3, 4, 4,
7, 8, 9,
1, 2, 3,
4, 5, 6,
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 24
7, 8, 9
};
num =
0 1
2 5 7 1 2 3
3 4 4 4 5 6
7 8 9 7 8 9
num[0][2][1]
num[1][1][0]
Q> WAP to input a number and print it in word as 986 Nine Hundred Eighty Six
Q> WAP to input two 3:3 matrix, perform the matrix addition, subtraction and multiplication.
Pointer:
Pointer is a special type of variable, can be used as an dynamic array as well as pointer can points to
another variable of the type same.
Pointer Used as Dynamic Array:
int *num;
here num is the pointer variable can be used as an array as much as the size we will specify during run
time. Pointer allocates the memory for each element during run time that’s why pointer is otherwise
called as dynamic memory allocator.
e.g.
#include “stdio.h”
#include “conio.h”
main(){
int *num, i=0, k;
char ch;
clrscr();
do{
printf(“\nEnter a Number : ”);
scanf(“%d”,&num[i++]);
printf(“\nDo U Want to Continue : ”);
ch=getche();
}while((ch== ‘y’) || (ch== ‘Y’));
printf(“\nThe Array Elements are like : ”);
for(k=0; k<i; k++)
printf(“\n%d”,num[k]);
getch();
}
Pointer Used as Reference: Pointer variables can be use to refers to the address another variable of the
type same and both of the variable will use the same memory location, any of them is changing the
value means will affect to other.
e.g.
int *ptr, num;
num=150;
print num; 150
print # 1002// It will print the address of num.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 25
Structure:
Structure is a container type or user defined type can capable to contain non – homogeneous data
items. and all the data items will refers by a same name called as tag name (structure reference name).
the structure is generally declared at global area with the key word struct as :
struct structureName{
data items declaration;
}tagName;
e.g.
struct Student{
int roll;
char name[50];
}std={1001, “Pradyumna”};
all the data items of the structure can be access or manipulate as:
tagName.itemName
e.g.
#include “stdio.h”
#include “conio.h”
struct Student{
int roll;
char name[50];
};
main(){
struct Student std;
clrscr();
printf(“\nEnter the Roll Number and Name : ”);
scanf(“%d%s”, &std.roll, &std.name);
printf(“\nThe Roll Number is : %d\nName is : %s”, std.roll, std.name);
getch();
}
Nested Structure:
When a structure id declared inside another structure that is called as nested structure.
e.g.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 26
#include “stdio.h”
#include “conio.h”
struct College{
struct Student{
int roll;
char name[50];
}std;
struct Teacher{
char empID[10];
char empName[50];
}t;
}col;
main(){
clrscr();
printf(“\nEnter the Roll Number and Name : ”);
scanf(“%d%s”, &col.std.roll, &col.std.name);
printf(“\nEnter the Teacher ID and Name : ”);
scanf(“%s%s”, &col.t.empID, &col.t.empName);
printf(“\nThe Roll Number is : %d\nName is : %s”, col.std.roll, col.std.name);
printf(“\nThe Teacher ID is : %s\nThe Name is : %s”,col.t.empID, col.t.empName);
getch();
}
Structure Array:
#include “stdio.h”
#include “conio.h”
struct student{
int roll;
char name[50];
}std[5];
main(){
int i;
clrscr();
for(i=0; i<5; i++){
printf(“\nEnter a Student Roll Number and Name : ”);
scanf(“%d%s”,&std[i].roll, &std[i].name);
}
printf(“\nAll the Student Details are :\nRoll\tName”);
for(i=0; i<5; i++){
printf(“\n%d\t%s”,std[i].roll, std[i].name);
}
getch();
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 27
Union:
It is just like the structure, but each member of the union share a same memory that is the
maximum memory taken by the any particular member will be share to all. And for this reason each
member of the union must be processed one after another. union is the keyword use to declare an
union. Basically used for registry manipulations.
union UnionName{
members declaration;
}tagname;
e.g.
Q> WAP to input and display the student roll number and name using union.
#include “stdio.h”
#include “conio.h”
union Student{
int roll;
char name[50];
}std;
main(){
clrscr();
printf(“\nEnter the Roll Number : ”);
scanf(“%d”,&std.roll);
printf(“\nThe Roll Number is : %d”,std.roll);
printf(“\nEnter the Name : ”);
scanf(“%[^\n]”,&std.name);
printf(“\nThe Name is : %s”,std.name);
getch();
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 28
Function
Function is a self contained block of statements to execute when it is called. Each and every function has
three different parts such are:
1. Function Declaration
2. Function Calling
3. Function Definition
1. Function Declaration: Generally a function is declared at global area, which specify the
return type, functionName and parameters type if require.
Syntax:
returnType functionName (parameters type if require);
Return type Specify the type of the value return from the function definition to function calling.
if we are not specifying the return type then by default the function return type is int, every
function should return a value unless the return type is void.
FunctionName can be any name but should follows the rules for declaring a variable.
Parameters are the references which receive the values from the function calling to function
definition.
e.g.
int sum(int, int);
2. Function Calling: A function can be call any where in the program but should be inside any
block, a function can directly call only by it’s name and arguments if require as:
functionName(arguments if require);
e.g.
s=sum(a,b);
printf(“\nThe Sum result is : %d”,sum(a,10));
The values or the references passes through the function calling are called as arguments.
3. Function Definition: A function must and should define outside of the block, It contains
the block of statements to execute when the particular function is called, it is otherwise called
as body of the function. It defines what a function will do when it will call. the functions are
defined as:
returnType functionName(parameters with type if require){
statement 1;
statement 2;
””””””””””
statement n;
}
e.g.
int sum(int x, int y){
return (x+y);
}
return is a keyword use to return the value or the reference from the function definition to function
calling.
e.g.
#include “stdio.h”
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 29
#include “conio.h”
void main(){
int a, b;
clrscr();
printf(“\nEnter two Numbers : ”);
scanf(“%d%d”, &a, &b);
printf(“\nThe Addition Result is : %d”, sum(a,b));
getch();
}
Types of Functions
According to function calling the functions are of three types such are:
1. Call by Value Function: Here the values are passes through the function calling.
e.g. sum(a,10); sum(20, 30); sum(a, b);
2. Call by Reference Function: Here the references or the addresses are passes through the
function calling and receives with pointer variable in function definition. by using call by
reference function, it increases the speed of execution and decreases the memory due to
pointer.
e.g.
#include “stdio.h”
#include “conio.h”
void main(){
int a, b, c;
clrscr();
printf(“\nEnter two Numbers : ”);
scanf(“%d%d”, &a, &b);
c= sum(&a,&b);
printf(“\nThe Addition Result is : %d”,c);
getch();
}
3. Recursion Function: When a function is called by itself, or when a function is called inside
it’s own definition.
e.g.
Q> WAP to input a number, print it’s factorial, by using recursion function.
#include “stdio.h”
#include “conio.h”
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 30
int factorial(int);
int factorial(int x){
static int r=1;
r=r*x--;
if(x<=1)
return r;
else
factorial(x);
}
void main(){
int n;
clrscr();
printf(“\nEnter a Number :”);
scanf(“%d”,&n);
printf(“\nThe Factorial is : %d”,factorial(n));
getch();
}
static is the keyword use to initialize the value to the variable once through out the continuity.
According to Passing Arguments and Return type the functions are of four types:
1. With Arguments With Return Value: int sum(int, int);
2. With Arguments no Return Value:
void sum(int x, int y){
printf(“\nThe Addition Result is: %s”,(x+y));
}
3. With No Argument with Return Value: ch=getche();
4. With No Argument no Return Value:
void display(){
printf(“\nHello World”);
}
void main(){
display();
}
Q> Write all the previous programs by using appropriate function.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 31
File Management
File is the namely location at memory can capable to contain a group of related data and information. A
file must have a name. The different file operations are like:
1. Creating and Naming and Opening a file
2. Insert or write Data to the file
3. Retrieve or read data from the file
4. Close the file
For file operation in C program we must require a file pointer, can be declared as :
FILE *filePointerName;
ch=getche();
}while(ch=='y' || ch=='Y');
fclose(fp);
getch();
}
ftell(), fseek(), etc. are other functions are used in File pointer location get and set.
Macro
Macro are the small powerful # followed statements are used in C or C++ language to have certain
operations made easy and faster. These are otherwise called as pre processors directives. There are
three different pre processor directives are available in C as :
1. File Inclusion Directive
2. Definition directive
3. Conditional Directive
File Inclusion Directive:
# include “FileName” : as earlier we have used for including the header files.
Definition Directive:
# define num 50
# define my int
Now we can use my instead of int inside the same program.
Conditional Directives:
#ifdef, #if, #ifndef, #else, #elif, #endif are the conditional directives.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 33
Introduction
C++ is one of the object oriented computer programming language developed by B.Jarne StrouStrop at
AT & T Bell laboratory of Murray Hill of USA in the year 1980. C++ extracted the Class and Construct
features from C and added the object oriented features of Simula 67. Simula 67 was the pure object
oriented programming language of that period. The C was previously named as C with Classes.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 34
global declaration;
void main() {
statement1;
statement2;
|||||||
statementn;
}
C++ Tokens
1. Identifier
2. Data Type
3. Constants
4. Keywords
5. Escape Sequences
6. Operators
Identifier:
Identifiers are the namely location at memory can capable to contain the values or the references. The
variables or the references or any symbolical names are called as identifiers.
Data Type:
These are the keywords use to specify the type of the data can be contained by the variable. There are 3
different types of data type such are:
1. Fundamental Datatype
2. Derived Datatype
3. User Defined Datatype
1. Fundamental Datatype: There are four different fundamental data types are used in C++
program such are:
a. Integer
b. Character
c. Float
d. Void: This is used as return type that implies that the function block will not return any
value to the function calling.
2. Derived Datatype: These can be created of the fundamental types. The different derived types
are: Array, Pointer, Reference
3. User defined Datatype: These types are defined by the user to contain one or more values of
different types or as the same types. The different user defined datatypes are like:
struct, union, enum, typedef, class
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 35
Keywords:
There are certain reserve words reserve by the C++ compilers, which has their own meaning to the
compiler and called as keyword. In general there are 46 different keywords are used in C++ such are :
auto
Break, case, catch, char, class, const, continue, default, delete, do, double, else, enum, extern, float, for,
friend, goto, if, int, long, mutable, new, operator, private, protected, public, register, return, short,
signed, sizeof, static, struct, switch, template, this, throw, typedef, union, unsigned, virtual, void,
volatile, while.
And some other compilers has some other extended keywords.
Operators:
These are the symbols used with one or more operands to do operation over them. C++ includes all the
operators of C and some other different operators are like:
Scope Resolution: Multiplicative: Logical:
Scope resolution: :: Multiplication: * Logical AND: &&
Postfix: Division: / Logical OR: ||
Subscript: [ ] Modulus: % Assignment:
Function call: ( ) Additive: Assignment: =
Cast: () Addition: + Addition Assignment: +=
Member access: . and –> Subtraction: – Subtraction Assignment: –=
Postfix increment: ++ Shift: Multiplication Assignment: *=
Postfix decrement: –– Left shift: << () Division Assignment: /=
Unary: Right shift: >> Modulus Assignment: %=
Indirection: * Relational & Equality: Left shift assignment: <<=
Address-of: & Less than: < Right shift assignment: >>=
Logical Negation: ! Less than or equal to: <= Bitwise AND Assignment: &=
One's Complement: ~ Greater than: > Bitwise exclusive OR Assignment: ^=
Prefix increment: ++ Greater than or equal to: >= Bitwise inclusive OR Assignment: |=
Prefix decrement: -- Equality: == Conditional:
sizeof Not equal: != Conditional: ? :
new Bitwise: Pointer to Member:
delete Bitwise AND: & Pointer-to-member: .* or –>
Comma: , Bitwise exclusive OR: ^ Reference:
throw Bitwise inclusive OR: | Reference: &
For standard input and output operation we can use iostream.h header file in C++. The input and output
statements are like cout and cin.
cout:
This is the output statement use to send the output message to the standard output device as:
cout<< “Output Message with Escape Sequences”;
e.g. cout<< “\nHello World”;
Q> WAP to display Hello World.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 36
#include “iostram.h”
#include “conio.h”
void main() {
clrscr();
cout<< “\nHello World”;
getch();
}
cin:
cin is the input statement use to input the value to the program variable as:
cin>>variableName;
if we want to input more than one variable values then:
cin>>variableName1>>varName2>>…>>varnmn;
Q> WAP to input two numbers and print the addition result.
#include “iostream.h”
#include “conio.h”
void main() {
int a, b;
clrscr();
cout<< “\nEnter Two Numbers : ”;
cin>>a>>b;
cout<< “\nA = ”<<a<< “\nB = ”<<b<< “\nThe Addition Result is : ”<< (a+b);
getch();
}
The constructs, array, string, pointer, structure, union, functions are same to the C.
Encapsulation
The wrapping up of data and methods into a single protected unit called as class and the mechanism is
called as Encapsulation. That is the capsulation or binding together of data and functions into a single
protected unit so that the data can be secured.
Class:
Class is a protected unit, where the data and methods binds together. Or class is a container or a general
form of an object or class is a logical abstraction of an object or a class defines the properties, behavior
or attribute of an object. The class members only can be access outside of the class by it’s object. a class
is consisting of dataMembers, memberFunctions, Constructors and Destructors. Class can be declared or
defined at global area of the program as:
class ClassName;
and can be defined as:
class ClassName {
accessSpecifier:
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 37
e.g.
Q> WAP to input two numbers and display the addition result using class.
#include “iostream.h”
#include “conio.h”
class Addition{
private:
int x, y;
public:
void setValue(int p, int q){
x=p;
y=q;
}
int getAddition(){
return (x+y);
}
}obj1;
void main() {
int a, b;
clrscr();
cout<< “\nEnter Two Numbers : ”;
cin>>a>>b;
obj1.setValue(a,b);
cout<< “\nThe Addition Result is : ”<< obj1.getAddition();
getch();
}
Object:
Object is an instance of a class can capable to contain separate members of the class in a separate
memory location. Each object will create separate memory of the corresponding class. The object can be
declared with the class as:
class ClassName {
-----
}objectName;
If we require to declare the object any where else then:
ClassName objectName;
If we require to declared more than one object then by putting the coma we can declare as:
ClassName objectName1, objName2, …, objNamen;
And the members of the class can be access outside of the class as objectName.memberName;
Access Specifiers can be of three types such are:
1. private: The private members of the class can access inside the class only. And through the
public member function of the class. If we are not specifying any access specifiers then by
default the access specifier is private.
2. protected: The protected members of the class are same to the private but the friends can
access. That is the friend class.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 38
3. public: The public members of the class can be access outside of the class through the objects,
these members are publicly available to any object of the class.
Object Array:
The object also can be declared as an array, in order to create an array of objects.
class ClassName {
member declaration;
}objectName[size];
Here we can access the members as:
objectName[0].memberName;
objectName[1].memberName;
objectName[2].memberName;
Q> WAP to input 5 student details to an object array & display them as:
Roll Name Marks
1001 Ranjan 540
1002 Santosh 390
1003 Pradyumna 553
1004 Goutam 380
1005 Debasis 250
#include “iostream.h”
#include “string.h”
#include “stdio.h”
#include “conio.h”
class Student {
private:
int roll;
char name[50];
int marks;
public:
void setDetails(int r, char *nm, int m) {
roll = r;
strcpy(name, nm);
marks = m;
}
int getRoll() { return roll; }
char * getName() { return name; }
int getMarks() { return marks; }
};
void main() {
int r1, m1;
char name1[50];
clrscr();
Student s[5];
for(int i=0; i<5; i++) {
cout<< “\nEnter the Roll Number : ”;
cin>>r1;
cout<< “\nEnter the Name : ”;
gets(name1);
cout<< “\nEnter the Marks : ”;
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 39
cin>>m1;
s[i].setDetails(r1, name1, m1);
}
cout<< “\nRoll\tName\t\tMarks”;
for (i=0; i<5; i++) {
cout<<endl<<s[i].getRoll()<< “\t”<< s[i].getName()<< “\t”<<s[i].getMarks();
}
getch();
}
dataMember: The variables, which are declared inside the class are called as data members.
memberFunction: The user defined functions which are used inside the class are called as member
functions. There are three different new functions are additionally used in C++ such are inline function,
virtual function and friend function. virtual function and friend function we will study later.
inline function:
To avoid the function declaration, definition, calling and returning back to the calling part,
passing arguments and extra time we uses macros in C, but there is a drawback to use the macro
because macros are not really functions and for this reason these are not compiled during compilation.
To eradicate this problem inline functions are used in C++. The inline functions are small functions,
which increases the execution speed. The inline function is declared and defined with the keyword inline
as:
inline returntype functionName (parameters with type if require){
statement;
}
Defining member function outside of the class:
If we require to define the member function outside of the class then first we must have to declare the
member function inside the class in order to get the accessibility. And then after only we can define
member function outside of the class by using scope resolution operator as:
Returntype ClassName :: memberFunctionName (parameters if require) {
body statements;
}
e.g.
#include “iostream.h”
#include “conio.h”
class Sample {
public:
Sample(){ // default constructor
}
void display();
};
void Sample :: display () {
cout<< “\nHello World”;
}
void main(){
Sample s1;
clrscr();
s1.display();
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 40
getch();
}
Polymorphism:
Poly means many morph means forms, polymorphism is the mechanism of using multiple forms of a
same object. The different real life examples are like: The same paper can be used for printing the news
paper, books, notes etc. The same person is differently acting in front of his parents, friends, relatives or
even in front of the teacher where as the person is same. That’s the different behavior of a same object
in different instance or in different time called as polymorphism.
The polymorphism includes:
1. Function Overloading
2. Constructor Overloading
3. Operator Overloading
Function Overloading:
When a same function can have multiple use, i.e. When a same function is used differently in different
instance by passing different arguments or types called as function overloading.
e.g.
#include “iostream.h”
#include “conio.h”
class FunctionOverLoad {
public:
int sum (int x, int y){
return (x+y);
}
float sum(float x, float y){
return (x+y);
}
};
void main() {
int a, b;
float p, q;
clrscr();
cout<< “\nEnter Two Interger Number : ”;
cin>>a>>b;
FunctionOverLoad f1;
cout<< “\nThe Addition Result is : ”<<f1.sum(a,b);
cout<< “\nEnter Two Float Number : ”;
cin>>p>>q;
cout<< “\nThe Addition Result is : ”<<f1.sum(p,q);
getch();
}
Constructor overloading:
Constructor: Constructor is a public method or public function of the class, the constructor name is same
to the class name, it don’t have any return value not even void, the constructor is automatically
executed when the object of the class is created or during the object creation the constructor is
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 41
automatically executed. Basically the constructor is useful to initialize an object properties (i.e. from the
very beginning of the object creation what are the default values to be kept by the particular object).
When two or more constructors are defined for a same class then that is called as constructor
overloading, according to passing arguments during object creation, it will automatically select the
corresponding constructor of the class. The different types of constructors are like:
1. Default Constructor:
This is the simple constructor having no parameters and no body statement. This constructor is defined
to decrease the compiler overhead. If there is no constructor is defined then compiler create a default
constructor during run time while creating the object. This can be defined as:
ConstructorName () {
}
e.g.
#include “iostream.h”
#include “conio.h”
class Sample{
public:
Sample(){ // default constructor
}
void display(){
cout<< “\nHello World”;
}
};
void main(){
Sample s1;
clrscr();
s1.display();
getch();
}
2. Non Parameterize Constructor:
This is as like the default constructor but having the body statements. Use to initialize the object or use
to execute the enclosed statements while creating a normal non parameterized object. This can be
defined as:
ConstructorName(){
Statement1;
Statment2;
”””””””””
Statementn;
}
e.g.
#include “iostream.h”
#include “conio.h”
class Sample{
int num;
public:
Sample(){ // Non Parameterized constructor
num=1001;
cout<< “\nThe Constructor is Executed”;
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 42
Int getNumber(){
return num;
}
};
void main(){
Sample s1;
clrscr();
cout<< “\nThe Number is : ”s1.getNumber();
getch();
}
3. Parameterized Constructor:
These type constructor having arguments during object declaration and according to the passing
arguments the constructor is defined, or according to the parameters defined in the constructor the
arguments are given during object creation. This can be defined as:
#include “iostream.h”
#include “conio.h”
class Sample{
int num;
public:
Sample(int x){ // Parameterized Constructor
num=x;
cout<< “\nThe Constructor has Executed and set the number”;
}
int getNumber(){
return num;
}
};
void main(){
Sample s1(909);
clrscr();
cout<< “\nThe Number is : ”<<s1.getNumber();
getch();
}
4. Copy Constructor:
By using the copy constructor we can copy the properties of one object to another by passing the object
as argument and we need to define the constructor with object as parameter.
#include “iostream.h”
#include “conio.h”
class Sample {
int num;
public:
Sample(int x) {
num=x;
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 43
void main() {
Sample s1(909);
Sample s2(s1);
clrscr();
cout<< “\ns1.num = ”<<s1.getNumber()<<endl<< “s2.num = ”<<s2.getNumber();
getch();
}
this is a keyword or a pointer can be used inside a class to retrieve the members of the same object for
which currently the class is working.
5. Constructor Overloading:
The previous example of copy constructor, the class has defined two different types of constructor is
called as constructor overloading as it is given we can define any n number of different types of
constructor inside a same class and according to the passing argument it will execute the corresponding
constructor.
Operator Overloading
When a same operator can have multiple use or we can extend the use of the operator with out
changing it’s original meaning called as operator overloading. There are certain operators can’t be over
load such as:
. (dot) member access operator (e.g. a.b (b is the member of a object))
.* (dot asterisk) pointer member access operator(e.g. a.*b(b is the pointer member of a object))
? and : (ternary operator)
:: (scope resolution)
sizeof
Overloading of Binary Operator:
#include “iostream.h”
#include “conio.h”
class Sample{
int num;
public:
Sample(){}
Sample(int x){
num=x;
}
Sample operator + (Sample &s){
Sample temp;
temp.num=num+s.num;
return temp;
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 44
int getNum(){
return num;
}
};
void main() {
Sample s1(25);
Sample s2(50);
Sample s3;
s3=s1+s2;
cout<< “\ns1.num = ”<<s1.getNum()<< “\ns2.num = ”<<s2.getNum();
cout<< “\ns2.num = ”<<s3.getNum();
getch();
}
Inheritance
The method of inheriting or deriving the properties of one object or class to another called as
inheritance, as in general:
Birds having two legs
Birds are of two types 1. Flying Birds(having wings) and 2. Non Flying Birds (having no wings)
Here Flying Birds or Non Flying Birds both having the same properties as having two legs derived the
property from the super object that is Bird.
In C++ there are five different types of inheritance such as:
1. Single Inheritance
2. Multiple Inheritance
3. Multi Level Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
1. Single Inheritance A
When a single class is derived from another single class, called as single inheritance. Here B
is the child class or derived class inherited from the base class or super class A.
Syntax : B
class ChildClassName : accessSpecifier BaseClassName{
defining the class;
};
According to the accessSpecifier the different properties of the base class will be inherited to the child
class i.e. as:
Inheritance Access Specifier Public Members Private Members Protected Members
Private private private Private
Protected protected private Private
Public public private Protected
2. Multiple Inheritance
When a same class is derived from multiple base class called as Multiple Inheritance.
here B is the child class derived from the base classes A and A1.
A A1
B
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 45
4. Hierarchical inheritance
When two or more child classes are derived from a same base class called as hierarchical inheritance.
Here B and C are derived from A.
A
B C
5. Hybrid inheritance
When two or more inheritance types are seen called as hybrid inheritance. A
Here B and C are derived from A and D is derived from B and C.
B C
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 46
Virtual Function:
When a function is defined or redefined in the child class and declared or defined in the base class (with
the keyword virtual) called as virtual function. This is otherwise called as function overriding i.e.
redefining the properties of the base class. The virtual function can be redefined in each sub classes. If a
class is derived from a base class and a non virtual function is over ridden then the base class function
will be called where as if the base class function is defined as the virtual then each sub class can be
redefined the same and the function will be called from the child class if exist.
e.g.
#include "iostream.h"
#include "string.h"
#include "conio.h"
class College{
private:
char name[100];
public:
College(){
strcpy(name, "WEBLINE Computer Education");
}
virtual char * getName(){
return name;
}
};
void main () {
Student s1("MohanDas KarmChand Gandhi");
College c1;
College *cptr;
clrscr();
cptr=&c1;
cout<<"\nThe Name is : "<<cptr->getName();
cptr=&s1;
cout<<"\nThe Name is : "<<cptr->getName();
getch();
}
As pointing of the pointer the class properties will work. While cptr pointing to c1 then college class will
work and college name will display and when the cptr points to s1 then the student class will work and
display the student name. Exact use of virtual function we have more clarification by using pure virtual
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 47
function that is no body statements in virtual function. If there is no body in the virtual function in the
base class then it will be set to 0(Zero), then the class is called as abstract class and the function is called
as pure virtual function.
Abstract Class: When a base class contains one or more pure virtual functions then that is called as
abstract class. And each sub class needs to redefine the body of the virtual function. An abstract class is
not used to create the objects, only use to act as a base class where every base properties are declared
where the child classes will follow the base instructions.
e.g.
#include "iostream.h"
#include "string.h"
#include "conio.h"
class College{
public:
char name[100];
College(){
strcpy(name, "WEBLINE Computer Education");
}
virtual char * getName()=0;
};
void main () {
Student s1;
clrscr();
cout<<"\nThe Name is : "<<s1.getName();
getch();
}
Friend Function:
Friend function is a special function not belongs to the scope of any class, so can’t be called by
the object of any class, though it is not a member of any class, can access to the protected members of
the class. The Friend function must be declared inside the classes for which the function is going to deal,
it is declared with the keyword friend and defined as the normal functions are defined.
E.g.
#include "iostream.h"
#include "conio.h"
class Demo;
class Sample{
protected:
int num;
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 48
public:
Sample (int x){
num = x;
}
friend int Multiply (Sample, Demo);
};
class Demo{
protected:
int num;
public:
Demo (int x){
num=x;
}
friend int Multiply (Sample, Demo);
};
int Multiply (Sample ss, Demo dd){
return (ss.num*dd.num);
}
void main () {
clrscr();
Sample s(5);
Demo d(7);
cout<<"\nThe Multiplication Result is : "<<Multiply(s, d);
getch();
}
Library
There are several libraries or header file accelerators are used called as library functions or pre defined
functions in C++ called as library classes are also available for performing many different actions.
The different libraries are like:
ctype : Character type library
string : string manipulation library
math library
time library
stdlib : standard library
These all above libraries can be used in both C and C++
ios : incput and output library
STL : Standard Template library
These are used in C++ only
math.h
the different functions belongs to math.h are as follows:
double cos(angle double);
It will return the cosine of the given angle.
double sin(angle double);
It will return the sine of the given angle.
double tan(angle double);
It will return the tangent of the given angle.
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 49
void main() {
time_t t;
time(&t);
printf("Today's date and time: %s\n", ctime(&t));
getch();
}
stdlib.h
div(dividend, divisor)
It will return both quotient and the remainder.
e.g.
#include "stdlib.h"
#include "conio.h"
#include "stdio.h"
div_t x;/*div_t is a structure type used by div. div divides two integers and returns both the
quotient and the remainder as a div_t type.*/
void main() {
x = div(19,5);
printf("19 div 5 = %d and remainder is %d", x.quot, x.rem);
getch();
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 50
void main() {
int number = 12345;
char string[25];
max(num1, num2);
It will return the maximum value between two given values.
random(num);
It will return the random number between zero to given num-1.
ios
This is the super base class for input and output library in C++. ios implies input/output stream.
Stream refers to the temporary memory or a packet of temporary data and information. It’s child classes
are like istream and ostream. istream implies input stream and ostream implies output stream.
fstram.h and iostream.h are the header files which defines ifstream and ofstream these both classes are
derived from istream and ostream correspondingly.
cin and cout are the objects defined in iostream.h, are used for standard input and output operation.
The different methods belongs to these objects are like:
cin.get(char):
cout.put(char);
Use to input a single character.
#include "iostream.h"
#include "conio.h"
void main () {
char ch;
clrscr();
cout.write("\nEnter a Character : ", 20);
cin.get(ch);
cout<<"\nThe Entered Chater is : ";
cout.put(ch);
getch();
}
cin.getline();
Use to input a string upto the end of the line.
#include "iostream.h"
#include "conio.h"
void main () {
char name[50];
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 51
clrscr();
cout<<"\nEnter Your Name : ";
cin.getline(name, 50);
cout<<"\nYour Name is : "<<name;
getch();
}
File Input and Output Operation
fstream is the base class, inherits two child classes for file operation
that are ifstream(input file stream) and ofstream(output file stream).
ifstream provides different functions like open(), get(), getline(), read() etc.
ofstream provides different functions like open(), put(), write() etc.
open() is the method use to open a file.
#include "iostream.h"
#include "fstream.h"
#include "conio.h"
void main () {
char ch;
ifstream ifs;
ifs.open("e:\\loka\\allinone\\c\\cppfile.cpp");
while(!ifs.eof()){
ch=ifs.get();
cout<<ch;
}
getch();
}
#include "iostream.h"
#include "fstream.h"
#include "conio.h"
void main () {
char ch;
ofstream ofs("d:\\rama.txt");
while((ch=getche())!=27)
ofs.put(ch);
getch();
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 52
Data Structure is the mechanism or the logical way of storing and maintaining the data so that the
different data manipulation operations can be made easier. The different data manipulation operations
are like:
The different data structure are like: linear data structure, non linear data structure
Stack:
This is a linear data structure can be implemented by using array or by using the structure, though
mostly uses array to implement the stack. In general a stack is a collection of data and follows LIFO (Last
In First Out) technology to perform the different operations.
#include "stdio.h"
#include "conio.h"
#define max 50
void push();
void peep();
void pop();
int stack[max];
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 53
void main () {
push();
peep();
pop();
peep();
}
void push(){
char ch;
if(last<max) {
do{
printf("\nEnter a Number : ");
scanf("%d", &stack[last++]);
printf("\nDo U Want to Continue Pushing the Elements to the stack
(y/n) :");
ch=getche();
}while((ch=='y') && (last<max));
}
else
printf("Stack is Over Flow.");
}
void peep(){
int i;
printf("\nThe Stack Elements are like :\n");
for(i=last-1; i>=0; i--)
printf("\n%d", stack[i]);
}
void pop(){
char ch;
do{
last--;
printf("\nDo U Want to Continue Deletion (y/n): ");
ch=getche();
}while(ch=='y');
}
Queue:
By using this technology we can create a list which follows FIFO (First In First Out) technology. The queue
also can be implemented by using array as well as structure.
#include"stdio.h "
#include"conio.h"
#define size 10
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 54
int rear=0,front=0,q[size];
int value;
void insert_queue();
void delete_queue();
void display_queue();
void main() {
int k=0;
char ch;
do {
printf("\n1.Insertion\n2.Deletion\n3.Exit");
printf("Enter the Choice :");
ch=getche();
switch(ch) {
case 49:insert_queue();
printf("\nThe Queue After Insertion :");
display_queue();
break;
case 50:delete_queue();
printf("\nThe Queue After Insertion :");
display_queue();
break;
case 51:k=1;
}
}while(k!=1);
}
//
void insert_queue() {
printf("\nInput The Element :");
scanf("%d",&value);
if(rear<size) {
rear++;
q[rear]=value;
if(front==0)
front=1;
}
else
printf("\nQueue is Overflow");
}
//
void delete_queue() {
if(front==0) {
printf("\nQueue is UnderFlow");
return;
}
else {
value=q[front];
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 55
Linked List:
The linked list is the linear data structure. implemented by using structure pointer. There are two
different types of Linked List such are:
1. Single Linked List
2. Double Linked List
1. Single Linked List:
Each unit of the Linked List called as a node. a node contains data and information as well as a pointer to
the next node. The start node is always points to the first node.
void main () {
start=NULL;
node=start;
insertList(node);
node=start->next;
displayList(node);
node=start->next;
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 56
updateList(node);
node=start->next;
displayList(node);
getch();
}
struct Double {
int info;
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 57
int num ;
struct Double start;
void Doubly_link_list (struct Double *);
void display (struct Double *);
while( ch != 'n') {
node->next = (struct Double *) malloc(sizeof(struct Double));
node->next->previous = node;
node = node->next;
printf("\n Input the values of the node : %d: ", (num+1));
scanf("%d", &node->info);
node->next = NULL;
fflush(stdin);
printf("\n Input choice n for break: ");
ch = getchar();
num ++;
}
printf("\n Total nodes = %d", num);
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com
Basic of C Programming in Depth 58
void main() {
struct Double *node = (struct Double *) malloc(sizeof(struct Double));
Doubly_link_list(node);
printf("\n Created doubly linked list is as follows\n");
display(node);
getch();
}
Tree:
By using tree technology we can implement the non linear data structure i.e. in a highrarchically
manner. left and right sub node of the top node.
e.g.
#include"stdio.h"
#include"malloc.h"
struct NODE {
int Info;
struct NODE *Left_Child;
struct NODE *Right_Child;
};
// Output function
// Function main
void main() {
int Info ;
char choice;
struct NODE *T = (struct NODE *) malloc(sizeof(struct NODE *));
T = NULL;
printf("\n Input choice 'b' to break:");
choice = getchar();
while(choice != 'b') {
printf("\n Input information of the node: ");
scanf("%d", &Info);
T = Create_Tree (Info, T);
printf("\n Tree is ");
Output(T, 1);
printf("\n Input choice 'b' to break:");
choice = getchar();
}
}
Odisha Education & Development Center, Brahmapur, GM, Odisha. 9437041710, www.oedci.com