Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Report on c and c++
Report on c and c++
TABLE OF CONTENTS
Chapter No. Title Page No.
CHAPTER-1: FUNDAMENTAL OF C
PROGRAMMING
1-Introduction
2-Setting up environment
3-Fundamental concept in C
4-Math Function
5-IO function
6-Decision Making in C
1-7
1
2
3
4
5
7-Repetitive Constructs in C 6
7
CHAPTER-2: ADVANCED C
PROGRAMMING
1-C Standard Library
2-User defined functions 10
3-Single Dimensional Arrays
11
4-Multi-Dimension Arrays 12
5-Dealing with characters 12
126-Strings 14
7-Pointers 14
8-User defined data types 15
9-File handling in C 16
10-Pre-compiler directives 17
8-17
8
CHAPTER-3
CHAPTER-4
INTRODUCTION TO OOP AND
C++
1-C++ Overview 18
2-Object Oriented Programming 18
3-Classes and Objects 19
4-Constructors & Destructors 20
5-Access Control 21
6-Constuctor and Function Overloading
22
ADVANCED C++
PROGRAMMING 23-29
1-Dealing with Inheritance 23
2-Abstract Classes 24
18 - 22
3-Input & Output in C++ 25
4-C++ Standard Library 26
5-Exception Handling 27
6-Namespace 29
C PROGRAMMING 31
C++ PROGRAMMING 36
PROJECT SOLUTION 41-
LIST OF Tables
Table No Title Page No
1.1 MATH FUNCTION 4
1.2 C STANDARD LIBRARY 8
1.3 C++ STANDARD LIBRARY 28
List of Symbols, Abbreviation
ASTERISK *
DIVISION /
MODULO %
AMPERSAND &
INCREMENT++
DECREMENT-
CHAPTER-1
FUNDAMENTALS OF C PROGRAMMING
1. INTRODUCTION
The C language was invented at Bell Labs by Dennis Ritchie in 1972 to allow the writing of
the UNIX operating system, then developed by Ken Thompson and Dennis Ritchie.
The UNIX operating system, born in the late 1960s – early 1970s, was written directly in
assembly language for the machines which it was intended. Born in the late 1960s – early
1970s, was written directly in assembly language for the machines which it was intended. If
the assembly language for writing such a system, it was nevertheless not easy to use. Such
language is in fact a particular type of processor, which makes the whole system should be
rewritten to make it work on a new architecture. This is its main creator, Ken Thompson,
wanted to use a language more quickly evolved to rewrite UNIX.
Among the languages available at the time, BCPL (Basic Combined Programming Language
for, which is a simplification of CPL), created by Martin Richards in 1966, was interesting.
Without going into detailed descriptions, BCPL is a simple language, procedural, and not
typed. Its simplicity makes it easy to create BCPL compilers on machines of the time, when
resources were very limited (the first computer used by Keith Thompson was to launch a
Unix PDP-7, which had a memory of 4000 words 18 bits, or less than 9 KB). Ken Thompson
has evolved to design the B language, which he implemented the first UNIX machines.
However, some limitations of language B were UNIX could be rewritten in this language.
From 1971, Dennis Ritchie B did evolve to address these issues. Like the programmers
increment versions of their programs, Ritchie “Nudge” the letter B to call the new language
C. This evolution is “stabilized” to 1973, from which UNIX and UNIX system utilities have
been rewritten successfully in C.
Subsequently in 1978, Brian W. Kernighan documentation very active language, and finally
publish the book with reference Ritchie The C Programming Language. Often called K &
R C language as specified in the first edition of this book.
In the years that followed, the C language was carried on many other machines. These ports
were often made at the beginning, from the pcc compiler Steve Johnson, but then the original
compilers were developed independently. During these years, every C compiler was written
in accordance with the specifications of K & R, but some added extensions, such as data
types or additional features, or different interpretations of certain parts of the book (not
necessarily very precise). Because of this, it was less easy to write C programs that can run
unchanged on many architectures.
2. SETTING UP ENVIRONMENT
Every C program must have one special function main (). This is the point where execution
begins when the program is running. We will see later that this does not have to be the first
statement in the program, but it must exist as the entry point. The group of statements
defining the main () enclosed in a pair of braces ({}) are executed sequentially. Each
expression statement must end with a semicolon. The closing brace of the main function
signals the end of the program. The main function can be located anywhere in the program
but the general practice is to place it as the first function.
Here is an elementary C program.
Main ()
{
}
There is no way to simplify this program, or to leave anything out. Unluckily, the program
does not do anything. Following the “main” program name is a couple of parentheses, which
are an indication to the compiler that this is a function. The 2 curly brackets { }, properly
called braces, are used to specify the limits of the program itself. The actual program
statements go between the 2 braces and in this case, there are no statements because the
program does absolutely nothing. You will be able to compile and run this program, but since
it has no executable statements, it does nothing. Keep in mind however, that it is a legal C
program.
Main ( ) function should return zero or one.Turbo C accepts both int and void main ( ) and
Turbo C coders use both int and void main ( ) in their programs.But in my belief, void main (
) is not a standard usage. The reason is, whenever a program gets executed it returns an
integer to the OS. If it returns ‘zero’, the program is executed successfully. Otherwise it
means the program has been ended with error. So main ( ) shouldn’t be declared as void.d as
void.
Main( ) should be declared as
int main( )
{
……………..
……………..
……………..
return 0 ;
}
3. FUNDAMENTAL CONCEPTS IN C
1- IDENTIFIERS
Identifiers are the names that are given to various program elements such as variables,
symbolic constants and functions.Variable or function identifier that is called a symbolic
constant name.
Identifier can be freely named, the following restrictions.
~Z , 0~9 ) and half underscore ( _ ) can only be
~Z ) or half
underscore ( _ ) can only be used.
e. That is, word and WORD is recognized as a separate
identifier.
included.
2- KEYWORDS
Keywords are standard identifiers that have standard predefined meaning in C. Keywords
are all lowercase, since uppercase and lowercase characters are not equivalent it's possible
to utilize an uppercase keyword as an identifier but it's not a good programming practice.
Points to remember
Keywords can be used only for their intended purpose. 2. Keywords can't be used as
programmer defined identifier. 3. The keywords can't be used as names for variables.
3- DATA TYPE
C offers a standard, minimal set of basic data types. Sometimes these are called
"primitive" types. A lot of complex data structures can be developed from these basic data
types. The C language defines 4 fundamental data types: character integer floating-point
and double floating-point This data types are declared using the keywords char,int,float
and double respectively
TYPE Bytes Possible Values le
Values
int 2 or 4 -32,767 to 32,767
unsigned int 2 or 4 0 to 65,535
signed int 2 or 4 -32,767 to 32,767
short int 2 -32,767 to 32,767
unsigned short int 2 0 to 65,535
signed short int 2 -32,767 to 32,767
long int 4 -2,147,483,647 to
2,147,483,647
signed long int 4 -2,147,483,647 to
2,147,483,647
unsigned long int 4 0 to 4,294,967,295
4. MATH FUNCTIONS
Function Description
floor ( )
This function returns the nearest integer which is less than or equal to the
argument passed to this function.
round ( )
This function returns the nearest integer value of the float/double/long
double argument passed to this function. If decimal value is from “.1 to .5”,
it returns integer value less than the argument. If decimal value is from “.6
to .9”, it returns the integer value greater than the argument.
ceil ( )
This function returns nearest integer value which is greater than or equal
to the argument passed to this function.
sin ( ) This function is used to calculate sine value.
cos ( ) This function is used to calculate cosine.
cosh ( ) This function is used to calculate hyperbolic cosine.
p ( ) ex This function is used to calculate the exponential “e” to the xth power.
tan ( ) This function is used to calculate tangent.
tanh ( ) This function is used to calculate hyperbolic tangent.
sinh ( ) This function is used to calculate hyperbolic sine.
log ( ) This function is used to calculates natural logarithm.
log10 ( ) This function is used to calculates base 10 logarithm.
sqrt ( )
This function is used to find square root of the argument passed to this
function.
pow ( ) This is used to find the power of the given number.
trunc.(.)
This function truncates the decimal value from floating point value and
returns integer value.
TABLE : 1.1
5. I/O FUNCTION
1- SCANF
The usually used input statement is scanf () function.
Syntax of scanf function is scanf (“format string”, argument list);
The format string must be a text enclosed in double quotes. It contains the information for
interpreting the entire data for connecting it into internal representation in memory.
Example: integer (%d) , float (%f) , character (%c) or string (%s).
The argument list contains a list of variables each preceded by the address list and
separated by comma. The number of argument is not fixed; however corresponding to
each argument there should be a format specifier. Inside the format string the number of
argument should tally with the number of format specifier.
2- GETCHAR
getchar function will accept a character from the console or from a file, displays
immediately while typing and we need to press Enter key for proceeding.
Syntax of getchar() is int getchar(void); It returns the unsigned char that they read.If end-
of-file or an error is encountered getchar() functions return EOF.
For example: char a; a= getchar(); The function "getchar()" reads a single character from
the standard input device, the keyboard being assumed because that is the standard input
device, and assigns it to the variable "a".
3-GETS
It is used to scan a line of text from a standard input device. The gets() function will be
terminated by a newline character. The newline character won't be included as part of the
string. The string may include white space characters.
Syntax : char *gets(char *s);
gets() function is declared in the header file stdio.h. It takes a single argument. The
argument must be a data item representing a string. On successful completion, gets() shall
return a pointer to string s.
4-PRINTF
The usually used output statement is printf (). It is one of the library functions.
Syntax : printf (“format string”, argument list);
Format string may be a collection of escape sequence or/and conversion specification
or/and string constant. The format string directs the printf function to display the entire
text enclosed within the double quotes without any change.
Escape sequence:
Escape sequence is a pair of character. The first letter is a slash followed by a character.
Escape sequence help us to represent within the format string invisible and non-printed
character although there are physically two characters in any escape sequence. It actually
represents only one
6. DECISION MAKING IN C
1. IF STATEMENT
If statement is a conditional branching statement. In conditional branching statement a
condition is evaluated, if it is evaluate true a group of statement is executed. The simple
format of an if statement is as follows:
if (expression) statement;
If the expression is evaluated and found to be true, the single statement following the "if" is
executed. If false, the following statement is skipped. Here a compound statement composed
of several statements bounded by braces can replace the single statement.
2. C SWITCHSTATEMENT
Switch statements simulate the use of multiple if statement.The switch statement is probably
the single most syntactically awkward and error-prone feature of the C language. Syntax of c
switch statement is
switch(expression)
{
case constant1: statements 1; break;
case constant2: statements 2; break;
…………………..
default: statements n; break;
}
3.GOTO STATEMENT
The goto statement is used to alter the normal sequence of program execution by transferring
control to some other part of the program unconditionally. In its general form, the goto
statement is written as
goto label;
where the label is an identifier that is used to label the target statement to which the control is
transferred. Control may be transferred to anywhere within the current function. The target
statement must be labeled, and a colon must follow the label. Thus the target statement will
appear as
label:statement;
7. REPETITIVE CONSTRUCTS IN C
1.FOR LOOP
For loop in C is the most general looping construct. The loop header contains three parts: an
initialization, a continuation condition, and step.
Syntax: for (initialization, condition, step)
{
Statement 1;
Statement 2;
…………...
Statement n;
}
2.WHILE LOOP
The while statement is also a looping statement. The while loop evaluates the test expression
before every loop, so it can execute zero times if the condition is initially false. It has the
following syntax.
while (expression)
{
Statement 1;
Statement 2;
…………...
Statement n;
}
3-DO WHILE LOOP
This construct is also used for looping. In this case the loop condition is tested at the end of
the body of the loop. Hence the loop is executed al least one. The do-while is an unpopular
area of the language, most programmers’ tries to use the straight while if it is possible.
Syntax of do while loop is do { Statement 1; Statement 2; …………... Statement n; }
while(expression);
Here the block of statement following the do is executed without any condition check. After
this expression is evaluated and if it is true the block of statement in the body of the loop is
executed again. Thus the block of statement is repeatedly executed till the expression is
evaluated to false. Do-while construct is not used as often as the while loops or for loops in
normal case of iteration but there are situation where a loop is to be executed at least one, in
such cases this construction is very useful.
CHAPTER - 2
ADVANCED C PROGRAMMING
1. C STANDARD LIBRARY
The C standard library is the standard library for the C programming language, as specified
in the ANSI C standard. It was developed at the same time as the C library POSIX
specification, which is a superset of it. Since ANSI C was adopted by the International
Organization for Standardization, the C standard library is also called the ISO C library.
<assert.h>
Contains the assert macro, used to assist with detecting logical
errors and other types of bug in debugging versions of a program.
<complex.h> C99 A set of functions for manipulating complex numbers.
<ctype.h>
Defines set of functions used to classify characters by their types
or to convert between upper and lower case in a way that is
independent of the used character set (typically ASCII or one of
its extensions, although implementations utilizing EBCDIC are
also known).
<errno.h> For testing error codes reported by library functions.
<fenv.h> C99
Defines a set of functions for controlling floating-
point environment.
<float.h>
Defines macro constants specifying the implementation-specific
properties of the floating-point library.
<inttypes.h> C99 Defines exact-width integer types.
<iso646.h> NA1
Defines several macros that implement alternative ways to
express several standard tokens. For programming in ISO
646 variant character sets.
<limits.h>
Defines macro constants specifying the implementation-specific
properties of the integer types.
<locale.h> Defines localization functions.
<math.h> Defines common mathematical functions.
<setjmp.h>
Declares the macros setjmp and longjmp, which are used for non-
local exits.
<signal.h> Defines signal-handling functions.
<stdalign.h> C11 For querying and specifying the alignment of objects.
<stdarg.h> For accessing a varying number of arguments passed to functions.
<stdatomic.h> C11 For atomic operations on data shared between threads.
<stdbool.h> C99 Defines a boolean data type.
<stddef.h> Defines several useful types and macros.
<stdint.h> C99 Defines exact-width integer types.
<stdio.h> Defines core input and output functions
<stdlib.h>
, memory allocation, process control functions Defines numeric
conversion functions, pseudo-random numbers generation
functions
<stdnoreturn.h> C11 For specifying non-returning functions
<string.h> Defines string-handling functions
<tgmath.h> C99 Defines type-generic mathematical functions.
<threads.h> C11
Defines functions for managing
multiple threads, mutexes and condition variables
<time.h> Defines date- and time-handling functions
<uchar.h> C11 Types and functions for manipulating Unicode characters
<wchar.h> NA1 Defines wide-string-handling functions
<wctype.h> NA1
Defines set of functions used to classify wide characters by their
types or to convert between upper and lower case
TABLE : 1.2
2. USER DEFINED FUNCTION
A function is a block of code that performs a specific task.
C allows you to define functions according to your need. These functions are known as user-
defined functions.
Here is an example to add two integers. To perform this task, we have created an user-
defined addNumbers().
1. #include <stdio.h>
2. int addNumbers(int a, int b); // function prototype
3.
4. int main()
5. {
6. int n1,n2,sum;
7.
8. printf("Enters two numbers: ");
9. scanf("%d %d",&n1,&n2);
10.
11. sum = addNumbers(n1, n2); // function call
12. printf("sum = %d",sum);
13.
14. return 0;
15. }
16.
17. int addNumbers(int a, int b) // function definition
18. {
19. int result;
20. result = a+b;
21. return result; // return statement
3. SINGLE DIMENSIONALARRAYS
Array is a data structure, which provides the facility to store a collection of data of same type
under single variable name. Just like the ordinary variable, the array should also be declared
properly. The declaration of array includes the type of array that is the type of value we are
going to store in it, the array name and maximum number of elements.
The type may be any valid type supported by C. Array names, like other variable names, can
contain only letter, digit and underscore characters. Array names cannot begin with a digit
character. I.e., The rule for giving the array name is same as the ordinary variable. The size
should be an individual constant. To refer to a particular location or element in the array, we
specify the name of the array and the index of the particular element in the array. The index
specifies the location of the element in the array. The array index starts from zero. The
maximum index value will be equal to the size of the array minus one. The array index can be
an integer variable for an integer constant.
The declaration form of one-dimensional array is Data_type array_name [size];
The following declares an array called ‘numbers’ to hold 5 integers and sets the first and last
elements. C arrays are always indexed from 0. So the first integer in ‘numbers’ array is
numbers[0] and the last is numbers[4].
int numbers [5]; numbers [0] = 1; // set first element numbers [4] = 5; // set last element
This array contains 5 elements. Any one of these elements may be referred to by giving the
name of the array followed by the position number of the particular element in square
brackets ([]). The first element in every array is the zeroth element.Thus, the first element of
array ‘numbers’is referred to as numbers[ 0 ], the second element of array ‘numbers’is
referred to as numbers[ 1 ], the fifth element of array ‘numbers’is referred to as numbers[ 4 ],
and, in general, the n-th element of array ‘numbers’is referred to as numbers[ n - 1 ].
It's a very common error to try to refer to non-existent numbers[ 5], element. C does not do
much hand holding. It is invariably up to the programmer to make sure that programs are free
from errors. This is especially true with arrays. C does not complain if you try to write to
elements of an array which do not exist!
For example: If you wrote: numbers[ 5 ], = 6; C would happily try to write 6 at the location
which would have corresponded to the sixth element, had it been declared that way. this
unfortunately would probably be memory taken up by some other variable or perhaps even by
the operating system. The result would be either:
consequences.
The second of these tends to be the result on operating systems with proper memory
protection. Writing over the bounds of an array is a common source of error. Remember that
the array limits run from zero to the size of the array minus one.
4. MULTI-DIMENSIONALARRAY
Two-dimensional array are those type of array, which has finite number of rows and finite
number of columns. The declaration form of 2-dimensional array is
Data_type Array_name [row size][column size];
The type may be any valid type supported by C. The rule for giving the array name is same as
the ordinary variable. The row size and column size should be an individual constant.
The following declares a two-dimensional 3 by 3 array of integers and sets the first and last
elements to be 10. int matrix [3][3]; matrix[0][0] = 10; matrix[2][2] = 10;
The following Figure illustrates a two dimensional array, matrix. The array contains three
rows and tree columns, so it is said to be a 3-by-3 array. In general, an array with m rows and
n columns is called an m-by-n array.
Every element in array matrix is identified by an element name of the form matrix[ i ][ j ];
matrix is the name of the array, and i and j are the subscripts that uniquely identify each
element in matrix . Notice that the names of the elements in the first row all have a first
subscript of 0; the names of the elements in the third column all have a second subscript of 2.
In the case of Two-dimensional array, during declaration the maximum number of rows and
maximum number of column should be specified for processing all array elements.
The implementation of the array stores all the elements in a single contiguous block of
memory. The other possible implementation would be a combination of several distinct one-
dimensional arrays. That’s not how C does it. In memory, the array is arranged with the
elements of the rightmost index next to each other. In other words, matrix[1][1] comes right
before matrix[1][2] in memory.
5. DEALING WITH CHARACTERS
C is widely used for character and string handling applications. This is odd, in some ways,
because the language doesn't really have any built-in string handling features. If you're used
to languages that know about string handling, you will almost certainly find C tedious to
begin with.
The standard library contains lots of functions to help with string processing but the fact
remains that it still feels like hard work. To compare two strings you have to call a function
instead of using an equality operator. There is a bright side to this, though. It means that the
language isn't burdened by having to support string processing directly, which helps to keep it
small and less cluttered. What's more, once you get your string handling programs working in
C, they do tend to run very quickly.
Character handling in C is done by declaring arrays (or allocating them dynamically) and
moving characters in and out of them ‘by hand’. Here is an example of a program which
reads text a line at a time from its standard input. If the line consists of the string of
characters stop, it stops; otherwise it prints the length of the line. It uses a technique which is
invariably used in C programs; it reads the characters into an array and indicates the end of
them with an extra character whose value is explicitly 0 (zero). It uses the
library strcmp function to compare two strings.
#include <stdio.h> h>
#include <stdlib.
#include <string.h>
#define LINELNG 100 /* max. length of input line */
main(){
char in_line[LINELNG];
char *cp;
int c;
cp = in_line;
while((c = getc(stdin)) != EOF){
if(cp == &in_line[LINELNG-1] || c == 'n'){
/*
* Insert end-of-line marker
*/
*cp = 0;
if(strcmp(in_line, "stop") == 0 )
exit(EXIT_SUCCESS);
else
printf("line was %d characters longn",
(int)(cp-in_line));
cp = in_line;
}
else
*cp++ = c;
}
exit(EXIT_SUCCESS);
}
6.STRINGS
A string in C is actually a character array. As an individual character variable can store only
one character, we need an array of characters to store strings. Thus, in C string is stored in an
array of characters. Each character in a string occupies one location in an array. The null
character ‘0’ is put after the last character. This is done so that program can tell when the end
of the string has been reached. For example, the string ”I Like C Programming” is stored.
Since the string has 20 characters (including space), it requires an arrayof at least, size 21 to
store it.
Thus, in C, a string is a one-dimensional array of characters terminated a null character. The
terminating null character is important. In fact, a string not terminated by ‘0’ is not really a
string, but merely a collection of characters.
A string may contain any character, including special control characters, such as n, t,  etc...
There is an important distinction between a string and a single character in C. The convention
is that single characters are enclosed by single quotes e.g. '*' and have the type char. Strings,
on the hand, are enclosed by double quotes e.g. "name" and have the type "pointer to char"
(char *) or array of char.
Strings can be declared in two main ways; one of these is as an array of characters, the other
is as a pointer to some pre-assigned array. Perhaps the simplest way of seeing how C stores
arrays is to give an extreme example which would probably never be used in practice.
#include<stdio.h> int main () { char string[]; string[0] = 'C'; string[1] = 'P'; string[2] =
'r'; string[3] = 'o'; string[4] = 'g'; string[5] = 'r'; string[6] = 'a'; string[7] = 'm'; string[8]
= 'm'; string[9] = 'i'; string[10]= 'n'; string[11] = 'g'; printf ("%s", string);
1. strlen()
Syntax: #include < string.h> size_t strlen( char *str );
2. string function : strlwr()
Syntax: char * strlwr(char *str)
strlwr(str) coverts str to all lowercase.
3. string function : strupr()
Syntax: char * strupr(char *str);
4. strcat()
Syntax: #include<string.h> char *strcat( char *str1, const char *str2 );
7. POINTERS
Pointer is a variable that represents the location of a data item, such as variable or an array
element. Within the computer’s memory, every stored data item occupies one or more
contiguous memory cells. The number of memory cells required to store a data item depends
on the type of the data item. For example, a single character will typically be stored in one
byte of memory; an integer usually requires two contiguous bytes, a floating-point number
usually requires four contiguous bytes, and a double precision usually requires eight
contiguous bytes.
Suppose v is a variable that represents some particular data item. The compiler will
automatically assign memory cells to this data item. The data item can then be accessed if we
know the address of the first memory cell. The address of v’s memory location can be
determined by the expression &v, where & is the unary operator, called the address operator,
that evaluates the address of its operand.
Now let us assign the address of v to another variable pv. Thus pv = &v; This new variable is
called pointer to v. since it “points to” the location where v is stored in address, not its value.
Thus pv is referred to as a pointer variable. The relationship between pv and v is illustrated in
the following figure.
Address of V-----------> Value of V
The data item represented by v. (i.e. the data item stored in v’s memory cells) can be accessed
by the expression *pv where * is a unary operator called the indication operator, that operates
only on a pointer variable. Therefore, *pv and v both represent the same data item.
The address operator (&) and indirection operator(*) are unary operators and they are the
members of the same precedence group as the other unary operators. The address operator
(&) must act upon operands that associated with unique address, such as ordinary variable or
single array element. Thus the address operators cannot act upon arithmetic expressions. The
indirection operator can only act upon operands that are pointers (e.g., pointer variables).
Pointer declaration:
Pointer variables, like all other variables, must be declared before, they may be used in C
program. When a pointer variable is declared, the variable name must be preceded by an
asterisk(*). This identifies the fact that the variable is a pointer. The data type that appears in
the declaration refers to the object of the pointer. i.e. the data item that is stored in the address
represented by the pointer, rather than the pointer itself. Thus a pointer declaration may be
written in general terms as :
Data-type *ptr;
8. USER DEFINED DATA TYPES
STRUCTURE
A structure is a user defined data type. We know that arrays can be used to represent a group
of data items that belong to the same type, such as int or float. However we cannot use an
array if we want to represent a collection of data items of different types using a single name.
A structure is a convenient tool for handling a group of logically related data items.
The syntax of structure declaration is struct structure_name { type element 1; type element 2;
…………….. type element n; };
In structure declaration the keyword struct appears first, this followed by structure name. The
member of structure should be enclosed between a pair of braces and it defines one by one
each ending with a semicolon. It can also be array of structure. There is an enclosing brace at
the end of declaration and it end with a semicolon.
We can declare structure variables as follows struct structure_name var1,var2,…..,var n;
For Example: To store the names, roll number and total mark of a student you can declare 3
variables. To store this data for more than one student 3 separate arrays may be declared.
Another choice is to make a structure. No memory is allocated when a structure is declared. It
just defines the “form” of the structure. When a variable is made then memory is allocated.
This is equivalent to saying that there's no memory for “int” , but when we declare an integer
that is. int var; only then memory is allocated. The structure for the above-mentioned case
will look like
struct student { int rollno; char name[25]; float totalmark; };
We can now declare structure variables stud1, stud2 as follows struct student stud1,stud2;
Thus, the stud1 and stud2 are structure variables of type student. The above structure can
hold information of 2 students.
Union
Union is a data type with two or more member similar to structure but in this case all the
members share a common memory location. The size of the union corresponds to the length
of the largest member. Since the member share a common location they have the same
starting address.
The real purpose of unions is to prevent memory fragmentation by arranging for a standard
size for data in the memory. By having a standard data size we can guarantee that any hole
left when dynamically allocated memory is freed will always be reusable by another instance
of the same type of union. This is a natural strategy in system programming where many
instances of different kinds of variables with a related purpose and stored dynamically.
A union is declared in the same way as a structure.The syntax of union declaration is union
union_name { type element 1; type element 2; …………….. type element n; }; This declares
a type template. Variables are then declared as: union union_name x,y,z;
For example, the following code declares a union data type called Student and a union
variable called stud: union student { int rollno; float totalmark; }; union student stud;
It is possible to combine the declaration of union combination with that of the union
variables, as shown below. union union_name { type element 1; type element 2;
…………….. type element n; }var1,var2,…,varn;
The following single declaration is equivalent to the two declaration presented in the previous
example.
union student { int rollno; float totalmark; }x,y,z
9. FILE HANDLING IN C
1. fopen()
Declaration: FILE * fopen (const char *filename, const char *mode);
The fopen () function opens a file whose
name is pointed to by ‘filename’ and
returns the stream that is associated with it.
The type of operation that will be allowed
on the file are defined by the vale of mode.
The legal values of modes are shown in the
following table. File Type
Meaning
“r” Open an existing file for reading only
“w” Open a new file for writing only. If a file
with the specified file-name currently
exists, it will be destroyed and a new file
created in its place.
“a” Open an existing file for appending (i.e.,
for adding new information at the end of
the file). If a file with the specified file-
name currently does not exist, a new file
will be created.
“r+” Open an existing file for both reading and
writing.
“w+” Open a new file for both reading and
writing. If a file with the specified file-
name currently exists, it will be destroyed
and a new file created in its place.
“a+” Open an existing file for both reading and
appending. If a file with the specified file-
name currently does not exist, a new file
will be created.
10. PRE-COMPILER DIRECTIVE
Preprocessor directives are lines included in a program that begin with the character #, which
make them different from a typical source code text. They are invoked by the compiler to
process some programs before compilation. Preprocessor directives change the text of the
source code and the result is a new source code without these directives.
Preprocessor programs provide preprocessors directives which tell the compiler to preprocess
the source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash)
symbol. This (‘#’) symbol at the beginning of a statement in a C/C++ program indicates that
it is a pre-processor directive. We can place these preprocessor directives anywhere in our
program. Examples of some preprocessor directives are: #include, #define, #ifndef etc. There
are 4 main types of preprocessor directives:
1.Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
Let us now learn about only macros in detail.
Macros: Macros are a piece of code in a program which is given some name.
Whenever this name is encountered by the compiler the compiler replaces the name
with the actual piece of code. The ‘#define’ directive is used to define a macro.
Let us now understand the macro definition with the help of a program:
#include<stdio.h>
// macro definition
#define LIMIT 5
int main()
{
for(int i=0; i<LIMIT; i++){
printf(“%dn”,i);
}
return0;} OUTPUT : 0 1 2 3
CHAPTER – 3
INTRODUCTION TO OOP AND C++
1. C++ OVERVIEW
C++ is an extension of the C programming language that was first implemented on the
UNIX operating system by Dennis Ritchie way back in 1972. C is a flexible
programming language that emains popular today and is used on a large number of
platforms for everything from microcontrollers to the most advanced scientific
systems. C++ was developed by Dr. Bjarne Stroustrup between 1983-1985 while
working at AT&T Bell Labs in New Jersey. He added features to the original C
language to produce what he called “C with classes”. These classes define
programming objects with specific features that transform the procedural nature of C
into the object-oriented programming language of C++. The C programming language
was so named as it succeeded an earlier programming language named “B” that had
been introduced around 1970. The name “C++” displays some programmers’ humor
because the programming ++ increment operator denotes that C++ is an extension of
the C language. C++, like C, is not platform-dependent so programs can be created on
any operating system. Most illustrations in this book depict output on the Windows
operating system purely because it is the most widely used desktop platform. The
examples can also be created on other platforms such as Linux or MacOS.
2. OBJECTORIENTED PROGRAMMING
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming
language or also we can say it is a method to solve a problem using tools and
techniques that are available to us following some approach. There are lots for
programming language that are known but all of them need to follow some strategy
when they are implemented and this methodology/strategy is paradigms. Apart from
varieties of programming language there are lots of paradigms to fulfil each and every
demand.
BASIC FEATURES OF OOP
The Objects Oriented programming language supports all the features of normal
programming languages. In addition it supports some important concepts and
terminology which has made it popular among programming methodology.
The important features of Object Oriented programming are:
Inheritance
Polymorphism
Data Hiding
Encapsulation
3. CLASSES AND OBJECTS
Class: The building block of C++ that leads to Object Oriented programming is a Class. It is
a user defined data type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class. A class is like a blueprint for
an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brand but all of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits,
mileage are their properties.
 A Class is a user defined data-type which has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
defines the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage etc
and member functions can be apply brakes, increase speed etc.
OBJECTS
An Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
A class is defined in C++ using keyword class followed by the name of class. The body of
class is defined inside the curly brackets and terminated by a semicolon at the end.
Declaring Objects: When a class is defined, only the specification for the object is defined;
no memory or storage is allocated. To use the data and access functions defined in the class,
you need to create objects.
SYNTAX: ClassName ObjectName;
// C++ program to demonstrate
// accessing of data members
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};
int main() {
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}
Output- Geekname is: Abhi
4. CONSTRUCTORS AND DESTRUCTORS
Constructors are special class functions which performs initialization of every object. The
Compiler calls the Constructor whenever an object is created. Constructors initialize values to
object members after storage is allocated to the object.Whereas, Destructor on the other hand
is used to destroy the class object.While defining a contructor you must remeber that
the name of constructor will be same as the name of the class, and contructors will never
have a return type.Constructors can be defined either inside the class definition or outside
class definition using class name and scope resolution :: operator.Types of Constructors in
C++.
Constructors are of three types
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor
Default Constructors: Default constructor is the constructor which doesn't take any
argument. It has no parameter. Syntax:
Class_name(parameter1, parameter2,…)
{
//constructor definition
}
Parameterized Constructors: These are the constructors with parameter .Using this
constructor you can provide different values to data members of different objects, by passing
the appropriate values as argument.
Copy Constructors: These are special type of constructors which takes an object as
argument, and is used to copy values of data members of one object into other object.
5. ACCESS CONTROL
Now before studying how to define class and its objects, lets first quickly learn what are
access modifiers.
Access modifiers in C++ class defines the access control rules. C++ has 3 new keywords
introduced, namely,
1. public
2. private
3. protected
These access modifiers are used to set boundaries for availability of members of class be it
data members or member functions
Access modifiers in the program, are followed by a colon. You can use either one, two or all
3 modifiers in the same class to set different boundaries for different class members.
They change the boundary for all the declarations that follow them.
Public Access Modifier in C++
Public, means all the class members declared under public will be available to everyone. The
data members and member functions declared public can be accessed by other classes too.
Hence there are chances that they might change them. So the key members must not be
declared public.
Private Access Modifier in C++
Private keyword, means that no one can access the class members declared private, outside
that class. If someone tries to access the private members of a class, they will get a compile
time error. By default class variables and member functions are private.
Protected Access Modifier in C++
Protected, is the last access specifier, and it is similar to private, it makes class member
inaccessible outside the class. But they can be accessed by any subclass of that class. (If class
A is inherited by class B, then class B is subclass of class A.
6.CONSTRUCTORAND FUNCTION OVERLOADING
CONSTRUCTOR IN C++OVERLOADING
In C++, We can have more than one constructor in a class with same name, as long as each
has a different list of arguments. This concept is known as Constructor Overloading and is
quite similar to function overloading.
 Overloaded constructors essentially have the same name (name of the class) and
different number of arguments.
 A constructor is called depending upon the number and type of arguments passed.
 While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.
FUNCTION OVERLOADING IN C++
Function overloading is a feature in C++ where two or more functions can have the same
name but different parameters.
Function overloading can be considered as an example of polymorphism feature in C++.
CHAPTER - 4
ADVANCED C++ PROGRAMMING
1.DEALING WITH INHERITANCE
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or
Super class.
The article is divided into following subtopics:
1. Why and when to use inheritance?
2. Modes of Inheritance
3. Types of Inheritance
Why and when to use inheritance?
Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes. If
we create these classes avoiding inheritance then we have to write all of these classes
avoiding inheritance then we have to write all of these functions in each of the three classes
as shown in below figure:
CLASS BUS CLASS CAR CLASS TRUCK
TYPES OF INHERITANCE
C++ supports six types of inheritance as follows:
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Heirarchical Inheritance
Hybrid Inheritance
Multipath Inher
fuel amount()
capacity()
applybrakes()
fuel amount()
Capacity()
applybrakes()
Fuel amount()
Capacity()
Applybrakes()
2.ABSTRACT CLASSES
An abstract class is, conceptually, a class that cannot be instantiated and is usually
implemented as a class that has one or more pure virtual (abstract) functions.
A pure virtual function is one which must be overridden by any concrete (i.e., non-abstract)
derived class. This is indicated in the declaration with the syntax " = 0" in the member
function's declaration.
EXAMPLE:
ClassAbstractClass{
Public:
AbstractMemberFunction()=0;
Pure virtual functionmakes
// thisclassAbstract class.
Virtual void
NonAbstractMemberFunction1();//
Virtual function.
Void
NonAbstractMemberFunction2();
};
In general an abstract class is used to define an implementation and is intended to be
inherited from by concrete classes. It's a way of forcing a contract between the class
designer and the users of that class. If we wish to create a concrete class (a class that
can be instantiated) from an abstract class we must declare and define a matching
member function for each abstract member function of the base class. Otherwise, if
any member function of the base class is left undefined, we will create a new abstract
class (this could be useful sometimes).
An abstract class is a class that is designed to be specifically used as a base class. An
abstract class contains at least one pure virtual function. You declare a pure virtual
function by using a pure specifier (= 0) in the declaration of a virtual member function
in the class declaration.
The following is an example of an abstract class:
class AB {
public:
virtual void f()=0;
};
3.INPUT AND OUTPUT IN C++
C++ comes with libraries which provides us many ways for performing input and output. In
C++ input and output is performed in the form of sequence of bytes or more commonly
known as streams.
Input Stream: If the direction of flow of bytes is from device(for example: Keyboard) to the
main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device( display screen ) then this process is called output.
Header files available in C++ for Input – Output operation are:
 iostream: iostream stands for standard input output stream. This header file contains
definitions to objects like cin, cout, cerr etc.
 iomanip: iomanip stands for input output manipulators. The methods declared in this
files are used for manipulating streams. This file contains definitions of setw,
setprecision etc.
 fstream: This header file mainly describes the file stream. This header file is used to
handle the data being read from a file as input or data being written into the file as
output.
In C++ articles, these two keywords cout and cin are used very often for taking inputs and
printing outputs. These two are the most basic methods of taking input and output in C++.
For using cin and cout we must include the header file iostream in our program.
In this article we will mainly discuss about the objects defined in the header file iostreamlike
cin and cout.
 Standard output stream (cout): Usually the standard output device is the display
screen. cout is the instance of the ostream class. cout is used to produce output on the
standard output device which is usually the display screen. The data needed to be
displayed on the screen is inserted in the standard output stream (cout) using the
insertion operator (<<).
#include <iostream>
using namespace std;
int main( ) {
char sample[] = "GeeksforGeeks";
cout << sample << " - A computer science portal for geeks";
return 0;
}
 Output:
Geeksforgeeks – A computer science portal for geeks
standard input stream (cin): Usually the input device is the keyboard. cin is the instance of
the class istream and is used to read input from the standard input device which is usually
keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The
extraction operator extracts the data from the object cin which is entered using the keboard.
#include<iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age:";
cin >> age;
cout << "nYour age is: "<<age;
return 0;
}
INPUT:18
OUTPUT:
Enter Your Age :
Your Age Is:18
4.C++ STANDARD LIBRARY
The Standard Template Library (STL) is a set of C++ template classes to provide common
programming data structures and functions such as lists, stacks, arrays, etc. It is a library of
container classes, algorithms, and iterators. It is a generalized library and so, its components
are parameterized. A working knowledge of template classes is a prerequisite for working
with STL.
STL has four components
 Algorithms
 Containers
 Functions
 Iterators
Algorithms
The header algorithm defines a collection of functions especially designed to be used
on ranges of elements.They act on containers and provide means for various operations
for the contents of the containers.
Containers
Containers or container classes store objects and data. There are in total seven standard “first-
class” container classes and three container adaptor classes and only seven header files that
provide access to these containers or container adaptors.
Functions
The STL includes classes that overload the function call operator. Instances of such classes
are called function objects or functors. Functors allow the working of the associated function
to be customized with the help of parameters to be passed.
Iterators
As the name suggests, iterators are used for working upon a sequence of values. They are the
major feature that allow generality in STL.
5.EXCEPTION HANDLING
One of the advantages of C++ over C is Exception Handling. Exceptions are run-time
anomalies or abnormal conditions that a program encounters during its execution. There are
two types of exceptions: a)Synchronous, b)Asynchronous(Ex:which are beyond the
program’s control, Disc failure etc). C++ provides following specialized keywords for this
purpose.
try: represents a block of code that can throw an exception.
catch: represents a block of code that is executed when a particular exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function throws, but
doesn’t handle itself.
Why Exception Handling?
Following are main advantages of exception handling over traditional error handling.
1) Separation of Error Handling code from Normal Code: In traditional error handling
codes, there are always if else conditions to handle errors. These conditions and the
code to handle errors get mixed up with the normal flow. This makes the code less
readable and maintainable. With try catch blocks, the code for error handling becomes
separate from the normal flow.
2) Functions/Methods can handle any exceptions they choose: A function can throw
many exceptions, but may choose to handle some of them. The other exceptions
which are thrown, but not caught can be handled by caller. If the caller chooses not to
catch them, then the exceptions are handled by caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw keyword.
The caller of this function must handle the exception in some way (either by
specifying it again or catching it.
3) Grouping of Error Types: In C++, both basic types and objects can be thrown as
exception. We can create a hierarchy of exception objects, group exceptions in namespaces or
classes, categorize them according to types.
BUILT IN USER DEFINED EXCEPTIONS
An exception is a problem that arises during the execution of a program. A C++ exception is
a response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
 throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.
 catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception
 try - A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the code that
might generate an exception.
Here is the small description of each exception mentioned in the above hierarchy −
Sr.No Exception & Description
1 std::exception
An exception and parent class of all the standard C++ exceptions.
2 std::bad_alloc
This can be thrown by new.
3 std::bad_cast
This can be thrown by dynamic_cast.
4 std::bad_exception
This is useful device to handle unexpected exceptions in a C++ program.
5 std::bad_typeid
This can be thrown by typeid.
6 std::logic_error
An exception that theoretically can be detected by reading the code.
7 std::domain_error
This is an exception thrown when a mathematically invalid domain is used.
8 std::invalid_argument
This is thrown due to invalid arguments.
9 std::length_error
This is thrown when a too big std::string is created.
10 std::out_of_range
This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().
11 std::runtime_error
An exception that theoretically cannot be detected by reading the code.
12 std::overflow_error
This is thrown if a mathematical overflow occurs.
13 std::range_error
This is occurred when you try to store a value which is out of range.
14 std::underflow_error
This is thrown if a mathematical underflow occurs.
TABLE: 1.3
6.NAMESPACEIN C++
A namespace is a declarative region that provides a scope to the identifiers (the names
of types, functions, variables, etc) inside it. Namespaces are used to organize code into
logical groups and to prevent name collisions that can occur especially when your code
base includes multiple libraries. All identifiers at namespace scope are visible to one
another without qualification. Identifiers outside the namespace can access the
members by using the fully qualified name for each identifier, for
example std::vector<std::string> vec;, or else by a using Declaration for a single
identifier (using std::string), or a using Directive for all the identifiers in the
namespace (using namespace std;). Code in header files should always use the fully
qualified namespace name.
The following example shows a namespace declaration and
three ways that code outside the namespace can accesses their members.
namespace ContosoData
{
class ObjectManager
{
public:
void DoSomething() {}
};
void Func(ObjectManager) {}
}
USING DIRECTIVES
The using directive allows all the names in a namespace to be used without the namespace-
nameas an explicit qualifier. Use a using directive in an implementation file (i.e. *.cpp) if you
are using several different identifiers in a namespace; if you are just using one or two
identifiers, then consider a using declaration to only bring those identifiers into scope and not
all the identifiers in the namespace. If a local variable has the same name as a namespace
variable, the namespace variable is hidden. It is an error to have a namespace variable with
the same name as a global variable.
Declaring namespaces and namespace members
Typically, you declare a namespace in a header file. If your function implementations are in a
separate file, then qualify the function names, as in this example.
//contosoData.h
#pragma once
namespace ContosoDataServer
{
void Foo();
int Bar();
}
C PROGRAMMING
1. Write a program that shows the summation of positive integer in between lower limit to upper
limit.
#include<stdio.h>
#include<conio.h>
int main()
{
long int i,a,b,sum=0;
printf("enter the lower and upper number:n");
scanf("%d %d",&a,&b);
for(i=a;i<=b;i++)
{
sum+=i;
}
printf("%ld",sum);
getch();
}
2. Write a program that shows the even summation of positive integer in between lower limit to
upper limit.
#include<stdio.h>
#include<conio.h>
int main()
{
long int i,a,b,sum=0;
scanf("%d %d",&a,&b);
for(i=a;i<=b;i++)
{
if(i%2==0)
sum+=i;
}
printf("%ld",sum);
getch();
}
3. Write a program that show the odd summation of positive integer in between lower limit to
upper limit if summation is greater than 9000.
#include<stdio.h>
#include<conio.h>
int main()
{
long int i,a,b,sum=0;
printf("enter the lower and upper number:n");
scanf("%d %d",&a,&b);
for(i=a;i<=b;i++)
{
if(i%2!=0)
sum+=i;}
if(sum>9000)
printf("%ld",sum);
else
printf("sum is smallar than 9000");
getch();
}
4. Write a program that show the summation of 12.2!+22.3!+32.4!+………..+n2.(n+1)! .
#include<stdio.h>
main(){
int i,n,r,j=0,k;
printf("Enter your limit:n");
scanf("%d",&n);
printf("The output is:n");
for(i=1;i<=n;i++)
{
r=1;
for(k=1;k<=i+1;k++)
r*=k;
j+=r*i*i;}
printf("%d",j);
getch();
}
5. Write a program that shows prime/non-prime number.
Sample input: 6
Output : 6 is not a prime number
#include<stdio.h>
#include<conio.h>
int main(){
int n,i,c=0;
printf("Enter the number:n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{if(n%i==0)
c++;}
if(c==2)
printf("%d is a prime number",n);
else
printf("it is not prime number");
getch();
}
6. Write a program to generate the all prime numbers of a given range.
#include<stdio.h>
#include<conio.h>
int main()
{
int n,i,j,c,a,b;
printf("Enter the upper number:n");
scanf("%d",&b);
for(i=1;i<=b;i++)
{c=0;
for(j=1;j<=i;j++)
{if(i%j==0)
c++;}
if(c==2)
printf("n%d is a prime numbern",i);
printf("n");}
getch();
}
7. Write a program for nPr
#include<stdio.h>
main(){
int i,n,fact=1,sum=1,p,r,c;
printf("enter the value of n and r:n");
scanf("%d %d",&n,&r);
for(i=1;i<=n;i++)
fact=fact*i;
c=n-r;
for(i=1;i<=c;i++)
{sum=sum*i;}
p=fact/sum;
printf("the value of npr is=%d",p);
getch();
}
8. Write a program for nCr
#include<stdio.h>
main(){
int i,n,fact=1,sum=1,p,r,c,m=1,e;
printf("enter the value of n and r:n");
scanf("%d %d",&n,&r);
for(i=1;i<=n;i++)
fact=fact*i;
c=n-r;
for(i=1;i<=c;i++)
sum=sum*i;
for(i=1;i<=r;i++)
m=m*i;
p=m*sum;
e=fact/p;
printf("the value of ncr is=%d",e);
getch();
}
9. Write a program that shows the all factorial of positive integer in between lower limit to upper
limit.
#include<stdio.h>
#include<conio.h>
int fact(int i);
int main()
{
int n,i;
printf("enter the number:n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{ printf("i!=%dn",fact(i));
}
getch();
}
int fact(int i)
{if(i<=1)
return(1);
else
return(i*fact(i-1));
getch();
}
10. Write a program to generrate Fibonacci Series of a given range.
(Fibonacci Series= 0 1 1 2 3 5 8 13 …..)
Sample input: 7
Output : 0 1 1 2 3 5 8 13 21
#include<stdio.h>
main(){
int m=0,r=1,p,n,i;
printf("Enter the input:n");
scanf("%d",&n);
printf("The output is:n");
printf("0 1 ");
for(i=0;i<n;i++)
{p=m+r;
m=r;
r=p;
printf("%d ",p);}
getch();
}
11. Write a program that shows the multiplication of two matrix.
#include<stdio.h>
#include<conio.h>
void main ()
{
int i,j,k;
int a[3][3],b[3][3],c[3][3],sum;
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
{scanf("%d",&a[i][j]);}
}
printf("first matrix:n");
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
{printf("%d",a[i][j]);}
printf("n");}
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
{scanf("%d",&b[i][j]);}
}
printf("secound matrix:n");
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
{printf("%d",b[i][j]);}
printf("n");}
printf("multiplication:n");
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
{sum=0;
for(k=0;k<3;k++)
{sum=sum+a[i][k]*b[k][j];}
c[i][j]=sum;
printf("%d ",c[i][j]);
}
printf("n");
}
getch();
}
12. Write a program that shows a transpose matrix.
#include<stdio.h>
#include<conio.h>
void main ()
{
int i,j;
int a[3][3];
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
{scanf("%d",&a[i][j]);}}
printf("the matrix is:n");
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
{printf("%d ",a[i][j]);}
printf("n");}
printf("transpose matrix:n");
for(i=0;i<3;i++)
{for(j=0;j<3;j++)
{printf("%d ",a[j][i]);}
printf("n");}
getch();}
C++ PROGRAMMING
Compute quotient and remainder
1. 1. #include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. int divisor, dividend, quotient, remainder;
7.
8. cout << "Enter dividend: ";
9. cin >> dividend;
10.
11. cout << "Enter divisor: ";
12. cin >> divisor;
13.
14. quotient = dividend / divisor;
15. remainder = dividend % divisor;
16.
17. cout << "Quotient = " << quotient << endl;
18. cout << "Remainder = " << remainder;
19.
20. return 0;
21. }
2. Calculate H.C.F using recursion
1. #include <iostream>
2. using namespace std;
3.
4. int hcf(int n1, int n2);
5.
6. int main()
7. {
8. int n1, n2;
9.
10. cout << "Enter two positive integers: ";
11. cin >> n1 >> n2;
12.
13. cout << "H.C.F of " << n1 << " & " << n2 << " is: " << hcf(n1, n2);
14.
15. return 0;
16. }
17.
18. int hcf(int n1, int n2)
19. {
20. if (n2 != 0)
21. return hcf(n2, n1 % n2);
22. else
23. return n1;
24. }
3. Calculate FactorialUsing Recursion
1. #include<iostream>
2. using namespace std;
3.
4. int factorial(int n);
5.
6. int main()
7. {
8. int n;
9.
10. cout << "Enter a positive integer: ";
11. cin >> n;
12.
13. cout << "Factorial of " << n << " = " << factorial(n);
14.
15. return 0;
16. }
17.
18. int factorial(int n)
19. {
20. if(n > 1)
21. return n * factorial(n - 1);
22. else
23. return 1;
24. }
4. C++ program to add two complex numbers by passing objects to a
function.
1. #include <iostream>
2. using namespace std;
3.
4. class Complex
5. {
6. private:
7. int real;
8. int imag;
9. public:
10. Complex(): real(0), imag(0) { }
11. void readData()
12. {
13. cout << "Enter real and imaginary number respectively:"<<endl;
14. cin >> real >> imag;
15. }
16. void addComplexNumbers(Complex comp1, Complex comp2)
17. {
18. // real represents the real data of object c3 because this function is called using
code c3.add(c1,c2);
19. real=comp1.real+comp2.real;
20.
21. // imag represents the imag data of object c3 because this function is called using
code c3.add(c1,c2);
22. imag=comp1.imag+comp2.imag;
23. }
24.
25. void displaySum()
26. {
27. cout << "Sum = " << real<< "+" << imag << "i";
28. }
29. };
30. int main()
31. {
32. Complex c1,c2,c3;
33.
34. c1.readData();
35. c2.readData();
36.
37. c3.addComplexNumbers(c1, c2);
38. c3.displaySum();
39.
40. return 0;
41. }
FIGURE
FIG : 1.1
FIG :1.2
FIG :1.3
FIG :1.4
FIG :1.5
FIG :1.6
PROJECT SOLUTION
// Simple Quiz Library
// This header file contains all functions that are required to run the quiz system
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <conio.h>
#include "miscFuncLib.h"
#include "allVars.h"
void startQuiz();
void menuController();
void prepareQuizData();
void selectTenQuestions();
int checkDup(int currQ);
void runQuiz();
void displayResult();
void addCategoryTotal(char *qCategory, int marks, int fmarks);
// It shows the first opening menu
void menuController()
{
// printf("Here is the menu controlern");
int ch = 0;
while (ch != 2)
{
// Present the menu
system("cls");
printf("Welcome to Simple Quiz Gamen");
printf("---------------------------nn");
printf(" Your Optionsn");
printf(" ------------nn");
printf(" 1) Start The gamen");
printf(" 2) Quitnn");
printf(" Enter your choice (1/2) :: ");
scanf ("%d", &ch);
// Evaluate choices
switch (ch)
{
case 1 :
startQuiz();
break;
case 2 :
break;
default :
printf("Please choose between 1 or 2 .. Press a key to continue.n");
getch();
}
}
}
// This function will call the functions that runs a quiz session
void startQuiz()
{
prepareQuizData();
selectTenQuestions();
runQuiz();
displayResult();
}
// This function will read all the data from the question bank (SQG-QTNBNK.txt) and
stores it into an array
void prepareQuizData()
{
// read data from the file
char buff[268];
char fld[50];
FILE *fp;
fp = fopen("SQG-QTNBNK.txt", "r" );
printf("Loading Question Bank ...n");
while (fgets(buff, 259, fp)!=NULL)
{
// Extract the actual fields content from buffer
stringExtract(fld, buff, 0, 8);
strcpy(quizQuestions[maxQuestions].qCategory, fld);
//printf("%sn",quizQuestions[maxQuestions].qCategory);
stringExtract(fld, buff, 9, 13);
quizQuestions[maxQuestions].qId = atoi(fld);
//printf("%dn",quizQuestions[maxQuestions].qId);
stringExtract(fld, buff, 14, 53);
strcpy(quizQuestions[maxQuestions].qText, fld);
//printf("%sn",quizQuestions[maxQuestions].qText);
stringExtract(fld, buff, 54, 103);
strcpy(quizQuestions[maxQuestions].qAnswer1, fld);
//printf("%sn",quizQuestions[maxQuestions].qAnswer1);
stringExtract(fld, buff, 104, 153);
strcpy(quizQuestions[maxQuestions].qAnswer2, fld);
//printf("%sn",quizQuestions[maxQuestions].qAnswer2);
stringExtract(fld, buff, 154, 203);
strcpy(quizQuestions[maxQuestions].qAnswer3, fld);
//printf("%sn",quizQuestions[maxQuestions].qAnswer3);
stringExtract(fld, buff, 204, 253);
strcpy(quizQuestions[maxQuestions].qAnswer4, fld);
//printf("%sn",quizQuestions[maxQuestions].qAnswer4);
stringExtract(fld, buff, 254, 254);
quizQuestions[maxQuestions].qCAnswer = atoi(fld);
//printf("%dn",quizQuestions[maxQuestions].qCAnswer);
stringExtract(fld, buff, 255, 257);
quizQuestions[maxQuestions].qAllottedMarks = atoi(fld);
//printf("%dn",quizQuestions[maxQuestions].qAllottedMarks);
maxQuestions++;
//getch();
}
}
// The function selects 10 questions randomly from the array containing the entire
question bank
// These 10 questions would be stored in a seperate array
void selectTenQuestions()
{
int i, currQ;
time_t t;
srand((unsigned) time(&t));
printf("Prepareing the quiz question list ...n");
for(i=0; i<10; i++)
{
currQ = rand()%maxQuestions;
while (checkDup(currQ))
{
currQ = rand()%maxQuestions;
}
testQuestions[i].qIndex = currQ;
strcpy(testQuestions[i].qCategory, quizQuestions[currQ].qCategory);
testQuestions[i].qId = quizQuestions[currQ].qId;
strcpy(testQuestions[i].qText, quizQuestions[currQ].qText);
strcpy(testQuestions[i].qAnswer1, quizQuestions[currQ].qAnswer1);
strcpy(testQuestions[i].qAnswer2, quizQuestions[currQ].qAnswer2);
strcpy(testQuestions[i].qAnswer3, quizQuestions[currQ].qAnswer3);
strcpy(testQuestions[i].qAnswer4, quizQuestions[currQ].qAnswer4);
testQuestions[i].qCAnswer = quizQuestions[currQ].qCAnswer;
testQuestions[i].qAllottedMarks = quizQuestions[currQ].qAllottedMarks;
}
}
// When selecting questions for the quiz session there is a possibility that same
questions may be selected multiple times
// This function checks if the current query has already been stored in the array
int checkDup(int currQ)
{
int i;
for(i = 0; i < 10; i++)
{
if (testQuestions[i].qIndex == currQ)
{
return 1;
}
}
return 0;
}
// This function will present the selected 10 questions before the player and ask him to
find right answer
// This function will also record the performance and calculate the total allotted marks
void runQuiz()
{
int i;
char yn = ' ', ysno = ' ';
// Present welcome scene
printf("Welcome to Simple Quiz Gamenn");
printf("Player's Name :: ");
scanf(" %[^n]s", playerName);
printf("nnReady for quiz ? (Y/N) :: ");
scanf(" %c", &yn);
if (yn == 'Y' || yn == 'y')
{
for(i = 0; i < 10; i++)
{
ysno = 'N';
while (ysno == 'N' || ysno == 'n')
{
system("cls");
printf("Question number - %d :: n", i+1);
printf("Question category - %s :: n",
testQuestions[i].qCategory);
printf("Question text - %s nn",
testQuestions[i].qText);
printf("Avalilable answers .. n");
printf("1) %sn", testQuestions[i].qAnswer1);
printf("2) %sn", testQuestions[i].qAnswer2);
printf("3) %sn", testQuestions[i].qAnswer3);
printf("4) %snn", testQuestions[i].qAnswer4);
printf("Marks allotted - %d :: nn",
testQuestions[i].qAllottedMarks);
printf("Enter the correct answer (1/2/3/4) :: ");
scanf("%d", &testQuestions[i].qSelectedAns);
printf("nnLock it ? (Y/N) :: ");
scanf(" %c", &ysno);
}
if (testQuestions[i].qCAnswer == testQuestions[i].qSelectedAns)
testQuestions[i].qRecivedMarks = testQuestions[i].qAllottedMarks;
else
testQuestions[i].qRecivedMarks = 0;
totMarks = totMarks + testQuestions[i].qRecivedMarks;
fullMarks = fullMarks + testQuestions[i].qAllottedMarks;
}
}
}
// The function displays the final result after the quiz session is over
void displayResult()
{
int i;
printf("Now you may see the results ");
getch();
for(i = 0; i < 10; i++)
{
printf("Question number - %d :: n", i+1);
printf("Question category - %s :: n",
testQuestions[i].qCategory);
printf("Question text - %s nn", testQuestions[i].qText);
printf("Avalilable answers .. n");
printf("1) %sn", testQuestions[i].qAnswer1);
printf("2) %sn", testQuestions[i].qAnswer2);
printf("3) %sn", testQuestions[i].qAnswer3);
printf("4) %snn", testQuestions[i].qAnswer4);
printf("Correct Answer - %dn", testQuestions[i].qCAnswer);
printf("You Selected - %dn", testQuestions[i].qSelectedAns);
printf("Marks Received - %dnn",
testQuestions[i].qRecivedMarks);
getch();
// Add category wise totals
addCategoryTotal(testQuestions[i].qCategory,
testQuestions[i].qRecivedMarks,testQuestions[i].qAllottedMarks);
}
printf("%s, you recieved a total marks of %d out of %d nn", playerName, totMarks,
fullMarks);
// Printing the category summary
printf("Categorywise breakup ..n");
for(i = 1; i <= maxCategory; i++)
{
printf("Category : %s Obtained Marks : %d Total Marks : %dn",
categoryTotals[i].qCategory, categoryTotals[i].totMarks, categoryTotals[i].fullMarks);
}
getch();
}
// The function calculates the question category wise total and stores it into array.
void addCategoryTotal(char *qCategory, int marks, int fmarks)
{
int i;
int marksAdded = 0;
for(i = 1; i <= maxCategory; i++)
{
if (strcmp(qCategory, categoryTotals[i].qCategory)==0)
{
categoryTotals[i].totMarks = categoryTotals[i].totMarks + marks;
categoryTotals[i].fullMarks = categoryTotals[i].fullMarks + fmarks;
marksAdded = 1;
}
}
if (marksAdded==0)
{
maxCategory += 1;
strcpy(categoryTotals[maxCategory].qCategory , qCategory);
categoryTotals[maxCategory].totMarks = marks;
categoryTotals[maxCategory].fullMarks = fmarks;
}
}
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++
Report on c and c++

More Related Content

Report on c and c++

  • 3. TABLE OF CONTENTS Chapter No. Title Page No. CHAPTER-1: FUNDAMENTAL OF C PROGRAMMING 1-Introduction 2-Setting up environment 3-Fundamental concept in C 4-Math Function 5-IO function 6-Decision Making in C 1-7 1 2 3 4 5
  • 4. 7-Repetitive Constructs in C 6 7 CHAPTER-2: ADVANCED C PROGRAMMING 1-C Standard Library 2-User defined functions 10 3-Single Dimensional Arrays 11 4-Multi-Dimension Arrays 12 5-Dealing with characters 12 126-Strings 14 7-Pointers 14 8-User defined data types 15 9-File handling in C 16 10-Pre-compiler directives 17 8-17 8 CHAPTER-3 CHAPTER-4 INTRODUCTION TO OOP AND C++ 1-C++ Overview 18 2-Object Oriented Programming 18 3-Classes and Objects 19 4-Constructors & Destructors 20 5-Access Control 21 6-Constuctor and Function Overloading 22 ADVANCED C++ PROGRAMMING 23-29 1-Dealing with Inheritance 23 2-Abstract Classes 24 18 - 22
  • 5. 3-Input & Output in C++ 25 4-C++ Standard Library 26 5-Exception Handling 27 6-Namespace 29 C PROGRAMMING 31 C++ PROGRAMMING 36 PROJECT SOLUTION 41- LIST OF Tables Table No Title Page No 1.1 MATH FUNCTION 4 1.2 C STANDARD LIBRARY 8 1.3 C++ STANDARD LIBRARY 28
  • 6. List of Symbols, Abbreviation ASTERISK * DIVISION / MODULO % AMPERSAND & INCREMENT++ DECREMENT-
  • 7. CHAPTER-1 FUNDAMENTALS OF C PROGRAMMING 1. INTRODUCTION The C language was invented at Bell Labs by Dennis Ritchie in 1972 to allow the writing of the UNIX operating system, then developed by Ken Thompson and Dennis Ritchie. The UNIX operating system, born in the late 1960s – early 1970s, was written directly in assembly language for the machines which it was intended. Born in the late 1960s – early 1970s, was written directly in assembly language for the machines which it was intended. If the assembly language for writing such a system, it was nevertheless not easy to use. Such language is in fact a particular type of processor, which makes the whole system should be rewritten to make it work on a new architecture. This is its main creator, Ken Thompson, wanted to use a language more quickly evolved to rewrite UNIX. Among the languages available at the time, BCPL (Basic Combined Programming Language for, which is a simplification of CPL), created by Martin Richards in 1966, was interesting. Without going into detailed descriptions, BCPL is a simple language, procedural, and not typed. Its simplicity makes it easy to create BCPL compilers on machines of the time, when resources were very limited (the first computer used by Keith Thompson was to launch a Unix PDP-7, which had a memory of 4000 words 18 bits, or less than 9 KB). Ken Thompson has evolved to design the B language, which he implemented the first UNIX machines. However, some limitations of language B were UNIX could be rewritten in this language. From 1971, Dennis Ritchie B did evolve to address these issues. Like the programmers increment versions of their programs, Ritchie “Nudge” the letter B to call the new language C. This evolution is “stabilized” to 1973, from which UNIX and UNIX system utilities have been rewritten successfully in C. Subsequently in 1978, Brian W. Kernighan documentation very active language, and finally publish the book with reference Ritchie The C Programming Language. Often called K & R C language as specified in the first edition of this book. In the years that followed, the C language was carried on many other machines. These ports were often made at the beginning, from the pcc compiler Steve Johnson, but then the original compilers were developed independently. During these years, every C compiler was written in accordance with the specifications of K & R, but some added extensions, such as data types or additional features, or different interpretations of certain parts of the book (not necessarily very precise). Because of this, it was less easy to write C programs that can run unchanged on many architectures.
  • 8. 2. SETTING UP ENVIRONMENT Every C program must have one special function main (). This is the point where execution begins when the program is running. We will see later that this does not have to be the first statement in the program, but it must exist as the entry point. The group of statements defining the main () enclosed in a pair of braces ({}) are executed sequentially. Each expression statement must end with a semicolon. The closing brace of the main function signals the end of the program. The main function can be located anywhere in the program but the general practice is to place it as the first function. Here is an elementary C program. Main () { } There is no way to simplify this program, or to leave anything out. Unluckily, the program does not do anything. Following the “main” program name is a couple of parentheses, which are an indication to the compiler that this is a function. The 2 curly brackets { }, properly called braces, are used to specify the limits of the program itself. The actual program statements go between the 2 braces and in this case, there are no statements because the program does absolutely nothing. You will be able to compile and run this program, but since it has no executable statements, it does nothing. Keep in mind however, that it is a legal C program. Main ( ) function should return zero or one.Turbo C accepts both int and void main ( ) and Turbo C coders use both int and void main ( ) in their programs.But in my belief, void main ( ) is not a standard usage. The reason is, whenever a program gets executed it returns an integer to the OS. If it returns ‘zero’, the program is executed successfully. Otherwise it means the program has been ended with error. So main ( ) shouldn’t be declared as void.d as void. Main( ) should be declared as int main( ) { …………….. …………….. …………….. return 0 ; }
  • 9. 3. FUNDAMENTAL CONCEPTS IN C 1- IDENTIFIERS Identifiers are the names that are given to various program elements such as variables, symbolic constants and functions.Variable or function identifier that is called a symbolic constant name. Identifier can be freely named, the following restrictions. ~Z , 0~9 ) and half underscore ( _ ) can only be ~Z ) or half underscore ( _ ) can only be used. e. That is, word and WORD is recognized as a separate identifier. included. 2- KEYWORDS Keywords are standard identifiers that have standard predefined meaning in C. Keywords are all lowercase, since uppercase and lowercase characters are not equivalent it's possible to utilize an uppercase keyword as an identifier but it's not a good programming practice. Points to remember Keywords can be used only for their intended purpose. 2. Keywords can't be used as programmer defined identifier. 3. The keywords can't be used as names for variables. 3- DATA TYPE C offers a standard, minimal set of basic data types. Sometimes these are called "primitive" types. A lot of complex data structures can be developed from these basic data types. The C language defines 4 fundamental data types: character integer floating-point and double floating-point This data types are declared using the keywords char,int,float and double respectively TYPE Bytes Possible Values le Values int 2 or 4 -32,767 to 32,767 unsigned int 2 or 4 0 to 65,535 signed int 2 or 4 -32,767 to 32,767 short int 2 -32,767 to 32,767 unsigned short int 2 0 to 65,535 signed short int 2 -32,767 to 32,767 long int 4 -2,147,483,647 to 2,147,483,647 signed long int 4 -2,147,483,647 to 2,147,483,647 unsigned long int 4 0 to 4,294,967,295
  • 10. 4. MATH FUNCTIONS Function Description floor ( ) This function returns the nearest integer which is less than or equal to the argument passed to this function. round ( ) This function returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from “.1 to .5”, it returns integer value less than the argument. If decimal value is from “.6 to .9”, it returns the integer value greater than the argument. ceil ( ) This function returns nearest integer value which is greater than or equal to the argument passed to this function. sin ( ) This function is used to calculate sine value. cos ( ) This function is used to calculate cosine. cosh ( ) This function is used to calculate hyperbolic cosine. p ( ) ex This function is used to calculate the exponential “e” to the xth power. tan ( ) This function is used to calculate tangent. tanh ( ) This function is used to calculate hyperbolic tangent. sinh ( ) This function is used to calculate hyperbolic sine. log ( ) This function is used to calculates natural logarithm. log10 ( ) This function is used to calculates base 10 logarithm. sqrt ( ) This function is used to find square root of the argument passed to this function. pow ( ) This is used to find the power of the given number. trunc.(.) This function truncates the decimal value from floating point value and returns integer value. TABLE : 1.1
  • 11. 5. I/O FUNCTION 1- SCANF The usually used input statement is scanf () function. Syntax of scanf function is scanf (“format string”, argument list); The format string must be a text enclosed in double quotes. It contains the information for interpreting the entire data for connecting it into internal representation in memory. Example: integer (%d) , float (%f) , character (%c) or string (%s). The argument list contains a list of variables each preceded by the address list and separated by comma. The number of argument is not fixed; however corresponding to each argument there should be a format specifier. Inside the format string the number of argument should tally with the number of format specifier. 2- GETCHAR getchar function will accept a character from the console or from a file, displays immediately while typing and we need to press Enter key for proceeding. Syntax of getchar() is int getchar(void); It returns the unsigned char that they read.If end- of-file or an error is encountered getchar() functions return EOF. For example: char a; a= getchar(); The function "getchar()" reads a single character from the standard input device, the keyboard being assumed because that is the standard input device, and assigns it to the variable "a". 3-GETS It is used to scan a line of text from a standard input device. The gets() function will be terminated by a newline character. The newline character won't be included as part of the string. The string may include white space characters. Syntax : char *gets(char *s); gets() function is declared in the header file stdio.h. It takes a single argument. The argument must be a data item representing a string. On successful completion, gets() shall return a pointer to string s. 4-PRINTF The usually used output statement is printf (). It is one of the library functions. Syntax : printf (“format string”, argument list); Format string may be a collection of escape sequence or/and conversion specification or/and string constant. The format string directs the printf function to display the entire text enclosed within the double quotes without any change. Escape sequence: Escape sequence is a pair of character. The first letter is a slash followed by a character. Escape sequence help us to represent within the format string invisible and non-printed character although there are physically two characters in any escape sequence. It actually represents only one
  • 12. 6. DECISION MAKING IN C 1. IF STATEMENT If statement is a conditional branching statement. In conditional branching statement a condition is evaluated, if it is evaluate true a group of statement is executed. The simple format of an if statement is as follows: if (expression) statement; If the expression is evaluated and found to be true, the single statement following the "if" is executed. If false, the following statement is skipped. Here a compound statement composed of several statements bounded by braces can replace the single statement. 2. C SWITCHSTATEMENT Switch statements simulate the use of multiple if statement.The switch statement is probably the single most syntactically awkward and error-prone feature of the C language. Syntax of c switch statement is switch(expression) { case constant1: statements 1; break; case constant2: statements 2; break; ………………….. default: statements n; break; } 3.GOTO STATEMENT The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally. In its general form, the goto statement is written as goto label; where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label. Thus the target statement will appear as label:statement;
  • 13. 7. REPETITIVE CONSTRUCTS IN C 1.FOR LOOP For loop in C is the most general looping construct. The loop header contains three parts: an initialization, a continuation condition, and step. Syntax: for (initialization, condition, step) { Statement 1; Statement 2; …………... Statement n; } 2.WHILE LOOP The while statement is also a looping statement. The while loop evaluates the test expression before every loop, so it can execute zero times if the condition is initially false. It has the following syntax. while (expression) { Statement 1; Statement 2; …………... Statement n; } 3-DO WHILE LOOP This construct is also used for looping. In this case the loop condition is tested at the end of the body of the loop. Hence the loop is executed al least one. The do-while is an unpopular area of the language, most programmers’ tries to use the straight while if it is possible. Syntax of do while loop is do { Statement 1; Statement 2; …………... Statement n; } while(expression); Here the block of statement following the do is executed without any condition check. After this expression is evaluated and if it is true the block of statement in the body of the loop is executed again. Thus the block of statement is repeatedly executed till the expression is evaluated to false. Do-while construct is not used as often as the while loops or for loops in normal case of iteration but there are situation where a loop is to be executed at least one, in such cases this construction is very useful.
  • 14. CHAPTER - 2 ADVANCED C PROGRAMMING 1. C STANDARD LIBRARY The C standard library is the standard library for the C programming language, as specified in the ANSI C standard. It was developed at the same time as the C library POSIX specification, which is a superset of it. Since ANSI C was adopted by the International Organization for Standardization, the C standard library is also called the ISO C library. <assert.h> Contains the assert macro, used to assist with detecting logical errors and other types of bug in debugging versions of a program. <complex.h> C99 A set of functions for manipulating complex numbers. <ctype.h> Defines set of functions used to classify characters by their types or to convert between upper and lower case in a way that is independent of the used character set (typically ASCII or one of its extensions, although implementations utilizing EBCDIC are also known). <errno.h> For testing error codes reported by library functions. <fenv.h> C99 Defines a set of functions for controlling floating- point environment. <float.h> Defines macro constants specifying the implementation-specific properties of the floating-point library. <inttypes.h> C99 Defines exact-width integer types. <iso646.h> NA1 Defines several macros that implement alternative ways to express several standard tokens. For programming in ISO 646 variant character sets. <limits.h> Defines macro constants specifying the implementation-specific properties of the integer types.
  • 15. <locale.h> Defines localization functions. <math.h> Defines common mathematical functions. <setjmp.h> Declares the macros setjmp and longjmp, which are used for non- local exits. <signal.h> Defines signal-handling functions. <stdalign.h> C11 For querying and specifying the alignment of objects. <stdarg.h> For accessing a varying number of arguments passed to functions. <stdatomic.h> C11 For atomic operations on data shared between threads. <stdbool.h> C99 Defines a boolean data type. <stddef.h> Defines several useful types and macros. <stdint.h> C99 Defines exact-width integer types. <stdio.h> Defines core input and output functions <stdlib.h> , memory allocation, process control functions Defines numeric conversion functions, pseudo-random numbers generation functions <stdnoreturn.h> C11 For specifying non-returning functions <string.h> Defines string-handling functions <tgmath.h> C99 Defines type-generic mathematical functions.
  • 16. <threads.h> C11 Defines functions for managing multiple threads, mutexes and condition variables <time.h> Defines date- and time-handling functions <uchar.h> C11 Types and functions for manipulating Unicode characters <wchar.h> NA1 Defines wide-string-handling functions <wctype.h> NA1 Defines set of functions used to classify wide characters by their types or to convert between upper and lower case TABLE : 1.2 2. USER DEFINED FUNCTION A function is a block of code that performs a specific task. C allows you to define functions according to your need. These functions are known as user- defined functions. Here is an example to add two integers. To perform this task, we have created an user- defined addNumbers(). 1. #include <stdio.h>
  • 17. 2. int addNumbers(int a, int b); // function prototype 3. 4. int main() 5. { 6. int n1,n2,sum; 7. 8. printf("Enters two numbers: "); 9. scanf("%d %d",&n1,&n2); 10. 11. sum = addNumbers(n1, n2); // function call 12. printf("sum = %d",sum); 13. 14. return 0; 15. } 16. 17. int addNumbers(int a, int b) // function definition 18. { 19. int result; 20. result = a+b; 21. return result; // return statement 3. SINGLE DIMENSIONALARRAYS Array is a data structure, which provides the facility to store a collection of data of same type under single variable name. Just like the ordinary variable, the array should also be declared properly. The declaration of array includes the type of array that is the type of value we are going to store in it, the array name and maximum number of elements. The type may be any valid type supported by C. Array names, like other variable names, can contain only letter, digit and underscore characters. Array names cannot begin with a digit character. I.e., The rule for giving the array name is same as the ordinary variable. The size should be an individual constant. To refer to a particular location or element in the array, we specify the name of the array and the index of the particular element in the array. The index specifies the location of the element in the array. The array index starts from zero. The maximum index value will be equal to the size of the array minus one. The array index can be an integer variable for an integer constant. The declaration form of one-dimensional array is Data_type array_name [size]; The following declares an array called ‘numbers’ to hold 5 integers and sets the first and last elements. C arrays are always indexed from 0. So the first integer in ‘numbers’ array is numbers[0] and the last is numbers[4]. int numbers [5]; numbers [0] = 1; // set first element numbers [4] = 5; // set last element This array contains 5 elements. Any one of these elements may be referred to by giving the name of the array followed by the position number of the particular element in square brackets ([]). The first element in every array is the zeroth element.Thus, the first element of array ‘numbers’is referred to as numbers[ 0 ], the second element of array ‘numbers’is referred to as numbers[ 1 ], the fifth element of array ‘numbers’is referred to as numbers[ 4 ], and, in general, the n-th element of array ‘numbers’is referred to as numbers[ n - 1 ].
  • 18. It's a very common error to try to refer to non-existent numbers[ 5], element. C does not do much hand holding. It is invariably up to the programmer to make sure that programs are free from errors. This is especially true with arrays. C does not complain if you try to write to elements of an array which do not exist! For example: If you wrote: numbers[ 5 ], = 6; C would happily try to write 6 at the location which would have corresponded to the sixth element, had it been declared that way. this unfortunately would probably be memory taken up by some other variable or perhaps even by the operating system. The result would be either: consequences. The second of these tends to be the result on operating systems with proper memory protection. Writing over the bounds of an array is a common source of error. Remember that the array limits run from zero to the size of the array minus one. 4. MULTI-DIMENSIONALARRAY Two-dimensional array are those type of array, which has finite number of rows and finite number of columns. The declaration form of 2-dimensional array is Data_type Array_name [row size][column size]; The type may be any valid type supported by C. The rule for giving the array name is same as the ordinary variable. The row size and column size should be an individual constant. The following declares a two-dimensional 3 by 3 array of integers and sets the first and last elements to be 10. int matrix [3][3]; matrix[0][0] = 10; matrix[2][2] = 10; The following Figure illustrates a two dimensional array, matrix. The array contains three rows and tree columns, so it is said to be a 3-by-3 array. In general, an array with m rows and n columns is called an m-by-n array. Every element in array matrix is identified by an element name of the form matrix[ i ][ j ]; matrix is the name of the array, and i and j are the subscripts that uniquely identify each element in matrix . Notice that the names of the elements in the first row all have a first subscript of 0; the names of the elements in the third column all have a second subscript of 2. In the case of Two-dimensional array, during declaration the maximum number of rows and maximum number of column should be specified for processing all array elements. The implementation of the array stores all the elements in a single contiguous block of memory. The other possible implementation would be a combination of several distinct one- dimensional arrays. That’s not how C does it. In memory, the array is arranged with the elements of the rightmost index next to each other. In other words, matrix[1][1] comes right before matrix[1][2] in memory. 5. DEALING WITH CHARACTERS C is widely used for character and string handling applications. This is odd, in some ways, because the language doesn't really have any built-in string handling features. If you're used
  • 19. to languages that know about string handling, you will almost certainly find C tedious to begin with. The standard library contains lots of functions to help with string processing but the fact remains that it still feels like hard work. To compare two strings you have to call a function instead of using an equality operator. There is a bright side to this, though. It means that the language isn't burdened by having to support string processing directly, which helps to keep it small and less cluttered. What's more, once you get your string handling programs working in C, they do tend to run very quickly. Character handling in C is done by declaring arrays (or allocating them dynamically) and moving characters in and out of them ‘by hand’. Here is an example of a program which reads text a line at a time from its standard input. If the line consists of the string of characters stop, it stops; otherwise it prints the length of the line. It uses a technique which is invariably used in C programs; it reads the characters into an array and indicates the end of them with an extra character whose value is explicitly 0 (zero). It uses the library strcmp function to compare two strings. #include <stdio.h> h> #include <stdlib. #include <string.h> #define LINELNG 100 /* max. length of input line */ main(){ char in_line[LINELNG]; char *cp; int c; cp = in_line; while((c = getc(stdin)) != EOF){ if(cp == &in_line[LINELNG-1] || c == 'n'){ /* * Insert end-of-line marker */ *cp = 0; if(strcmp(in_line, "stop") == 0 ) exit(EXIT_SUCCESS); else printf("line was %d characters longn", (int)(cp-in_line)); cp = in_line; } else *cp++ = c; } exit(EXIT_SUCCESS); }
  • 20. 6.STRINGS A string in C is actually a character array. As an individual character variable can store only one character, we need an array of characters to store strings. Thus, in C string is stored in an array of characters. Each character in a string occupies one location in an array. The null character ‘0’ is put after the last character. This is done so that program can tell when the end of the string has been reached. For example, the string ”I Like C Programming” is stored. Since the string has 20 characters (including space), it requires an arrayof at least, size 21 to store it. Thus, in C, a string is a one-dimensional array of characters terminated a null character. The terminating null character is important. In fact, a string not terminated by ‘0’ is not really a string, but merely a collection of characters. A string may contain any character, including special control characters, such as n, t, etc... There is an important distinction between a string and a single character in C. The convention is that single characters are enclosed by single quotes e.g. '*' and have the type char. Strings, on the hand, are enclosed by double quotes e.g. "name" and have the type "pointer to char" (char *) or array of char. Strings can be declared in two main ways; one of these is as an array of characters, the other is as a pointer to some pre-assigned array. Perhaps the simplest way of seeing how C stores arrays is to give an extreme example which would probably never be used in practice. #include<stdio.h> int main () { char string[]; string[0] = 'C'; string[1] = 'P'; string[2] = 'r'; string[3] = 'o'; string[4] = 'g'; string[5] = 'r'; string[6] = 'a'; string[7] = 'm'; string[8] = 'm'; string[9] = 'i'; string[10]= 'n'; string[11] = 'g'; printf ("%s", string); 1. strlen() Syntax: #include < string.h> size_t strlen( char *str ); 2. string function : strlwr() Syntax: char * strlwr(char *str) strlwr(str) coverts str to all lowercase. 3. string function : strupr() Syntax: char * strupr(char *str); 4. strcat() Syntax: #include<string.h> char *strcat( char *str1, const char *str2 ); 7. POINTERS Pointer is a variable that represents the location of a data item, such as variable or an array element. Within the computer’s memory, every stored data item occupies one or more contiguous memory cells. The number of memory cells required to store a data item depends on the type of the data item. For example, a single character will typically be stored in one byte of memory; an integer usually requires two contiguous bytes, a floating-point number
  • 21. usually requires four contiguous bytes, and a double precision usually requires eight contiguous bytes. Suppose v is a variable that represents some particular data item. The compiler will automatically assign memory cells to this data item. The data item can then be accessed if we know the address of the first memory cell. The address of v’s memory location can be determined by the expression &v, where & is the unary operator, called the address operator, that evaluates the address of its operand. Now let us assign the address of v to another variable pv. Thus pv = &v; This new variable is called pointer to v. since it “points to” the location where v is stored in address, not its value. Thus pv is referred to as a pointer variable. The relationship between pv and v is illustrated in the following figure. Address of V-----------> Value of V The data item represented by v. (i.e. the data item stored in v’s memory cells) can be accessed by the expression *pv where * is a unary operator called the indication operator, that operates only on a pointer variable. Therefore, *pv and v both represent the same data item. The address operator (&) and indirection operator(*) are unary operators and they are the members of the same precedence group as the other unary operators. The address operator (&) must act upon operands that associated with unique address, such as ordinary variable or single array element. Thus the address operators cannot act upon arithmetic expressions. The indirection operator can only act upon operands that are pointers (e.g., pointer variables). Pointer declaration: Pointer variables, like all other variables, must be declared before, they may be used in C program. When a pointer variable is declared, the variable name must be preceded by an asterisk(*). This identifies the fact that the variable is a pointer. The data type that appears in the declaration refers to the object of the pointer. i.e. the data item that is stored in the address represented by the pointer, rather than the pointer itself. Thus a pointer declaration may be written in general terms as : Data-type *ptr; 8. USER DEFINED DATA TYPES STRUCTURE A structure is a user defined data type. We know that arrays can be used to represent a group of data items that belong to the same type, such as int or float. However we cannot use an array if we want to represent a collection of data items of different types using a single name. A structure is a convenient tool for handling a group of logically related data items. The syntax of structure declaration is struct structure_name { type element 1; type element 2; …………….. type element n; }; In structure declaration the keyword struct appears first, this followed by structure name. The member of structure should be enclosed between a pair of braces and it defines one by one each ending with a semicolon. It can also be array of structure. There is an enclosing brace at the end of declaration and it end with a semicolon. We can declare structure variables as follows struct structure_name var1,var2,…..,var n; For Example: To store the names, roll number and total mark of a student you can declare 3 variables. To store this data for more than one student 3 separate arrays may be declared. Another choice is to make a structure. No memory is allocated when a structure is declared. It just defines the “form” of the structure. When a variable is made then memory is allocated. This is equivalent to saying that there's no memory for “int” , but when we declare an integer
  • 22. that is. int var; only then memory is allocated. The structure for the above-mentioned case will look like struct student { int rollno; char name[25]; float totalmark; }; We can now declare structure variables stud1, stud2 as follows struct student stud1,stud2; Thus, the stud1 and stud2 are structure variables of type student. The above structure can hold information of 2 students. Union Union is a data type with two or more member similar to structure but in this case all the members share a common memory location. The size of the union corresponds to the length of the largest member. Since the member share a common location they have the same starting address. The real purpose of unions is to prevent memory fragmentation by arranging for a standard size for data in the memory. By having a standard data size we can guarantee that any hole left when dynamically allocated memory is freed will always be reusable by another instance of the same type of union. This is a natural strategy in system programming where many instances of different kinds of variables with a related purpose and stored dynamically. A union is declared in the same way as a structure.The syntax of union declaration is union union_name { type element 1; type element 2; …………….. type element n; }; This declares a type template. Variables are then declared as: union union_name x,y,z; For example, the following code declares a union data type called Student and a union variable called stud: union student { int rollno; float totalmark; }; union student stud; It is possible to combine the declaration of union combination with that of the union variables, as shown below. union union_name { type element 1; type element 2; …………….. type element n; }var1,var2,…,varn; The following single declaration is equivalent to the two declaration presented in the previous example. union student { int rollno; float totalmark; }x,y,z 9. FILE HANDLING IN C 1. fopen() Declaration: FILE * fopen (const char *filename, const char *mode); The fopen () function opens a file whose name is pointed to by ‘filename’ and returns the stream that is associated with it. The type of operation that will be allowed on the file are defined by the vale of mode. The legal values of modes are shown in the following table. File Type Meaning “r” Open an existing file for reading only “w” Open a new file for writing only. If a file with the specified file-name currently exists, it will be destroyed and a new file created in its place. “a” Open an existing file for appending (i.e., for adding new information at the end of the file). If a file with the specified file-
  • 23. name currently does not exist, a new file will be created. “r+” Open an existing file for both reading and writing. “w+” Open a new file for both reading and writing. If a file with the specified file- name currently exists, it will be destroyed and a new file created in its place. “a+” Open an existing file for both reading and appending. If a file with the specified file- name currently does not exist, a new file will be created. 10. PRE-COMPILER DIRECTIVE Preprocessor directives are lines included in a program that begin with the character #, which make them different from a typical source code text. They are invoked by the compiler to process some programs before compilation. Preprocessor directives change the text of the source code and the result is a new source code without these directives. Preprocessor programs provide preprocessors directives which tell the compiler to preprocess the source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. This (‘#’) symbol at the beginning of a statement in a C/C++ program indicates that it is a pre-processor directive. We can place these preprocessor directives anywhere in our program. Examples of some preprocessor directives are: #include, #define, #ifndef etc. There are 4 main types of preprocessor directives: 1.Macros 2. File Inclusion 3. Conditional Compilation 4. Other directives Let us now learn about only macros in detail. Macros: Macros are a piece of code in a program which is given some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro. Let us now understand the macro definition with the help of a program: #include<stdio.h> // macro definition #define LIMIT 5 int main() { for(int i=0; i<LIMIT; i++){ printf(“%dn”,i); } return0;} OUTPUT : 0 1 2 3
  • 24. CHAPTER – 3 INTRODUCTION TO OOP AND C++ 1. C++ OVERVIEW C++ is an extension of the C programming language that was first implemented on the UNIX operating system by Dennis Ritchie way back in 1972. C is a flexible programming language that emains popular today and is used on a large number of platforms for everything from microcontrollers to the most advanced scientific systems. C++ was developed by Dr. Bjarne Stroustrup between 1983-1985 while working at AT&T Bell Labs in New Jersey. He added features to the original C language to produce what he called “C with classes”. These classes define programming objects with specific features that transform the procedural nature of C into the object-oriented programming language of C++. The C programming language was so named as it succeeded an earlier programming language named “B” that had been introduced around 1970. The name “C++” displays some programmers’ humor because the programming ++ increment operator denotes that C++ is an extension of the C language. C++, like C, is not platform-dependent so programs can be created on any operating system. Most illustrations in this book depict output on the Windows operating system purely because it is the most widely used desktop platform. The examples can also be created on other platforms such as Linux or MacOS. 2. OBJECTORIENTED PROGRAMMING Paradigm can also be termed as method to solve some problem or do some task. Programming paradigm is an approach to solve problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots for programming language that are known but all of them need to follow some strategy when they are implemented and this methodology/strategy is paradigms. Apart from varieties of programming language there are lots of paradigms to fulfil each and every demand. BASIC FEATURES OF OOP The Objects Oriented programming language supports all the features of normal programming languages. In addition it supports some important concepts and terminology which has made it popular among programming methodology. The important features of Object Oriented programming are: Inheritance Polymorphism Data Hiding Encapsulation
  • 25. 3. CLASSES AND OBJECTS Class: The building block of C++ that leads to Object Oriented programming is a Class. It is a user defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object. For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.  A Class is a user defined data-type which has data members and member functions.  Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions defines the properties and behavior of the objects in a Class.  In the above example of class Car, the data member will be speed limit, mileage etc and member functions can be apply brakes, increase speed etc. OBJECTS An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside the curly brackets and terminated by a semicolon at the end. Declaring Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. SYNTAX: ClassName ObjectName; // C++ program to demonstrate // accessing of data members #include <bits/stdc++.h> using namespace std; class Geeks { // Access specifier public: // Data Members string geekname; // Member Functions() void printname() { cout << "Geekname is: " << geekname;
  • 26. } }; int main() { // Declare an object of class geeks Geeks obj1; // accessing data member obj1.geekname = "Abhi"; // accessing member function obj1.printname(); return 0; } Output- Geekname is: Abhi 4. CONSTRUCTORS AND DESTRUCTORS Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object.Whereas, Destructor on the other hand is used to destroy the class object.While defining a contructor you must remeber that the name of constructor will be same as the name of the class, and contructors will never have a return type.Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator.Types of Constructors in C++. Constructors are of three types 1. Default Constructor 2. Parametrized Constructor 3. Copy Constructor Default Constructors: Default constructor is the constructor which doesn't take any argument. It has no parameter. Syntax: Class_name(parameter1, parameter2,…) { //constructor definition } Parameterized Constructors: These are the constructors with parameter .Using this constructor you can provide different values to data members of different objects, by passing the appropriate values as argument. Copy Constructors: These are special type of constructors which takes an object as argument, and is used to copy values of data members of one object into other object.
  • 27. 5. ACCESS CONTROL Now before studying how to define class and its objects, lets first quickly learn what are access modifiers. Access modifiers in C++ class defines the access control rules. C++ has 3 new keywords introduced, namely, 1. public 2. private 3. protected These access modifiers are used to set boundaries for availability of members of class be it data members or member functions Access modifiers in the program, are followed by a colon. You can use either one, two or all 3 modifiers in the same class to set different boundaries for different class members. They change the boundary for all the declarations that follow them. Public Access Modifier in C++ Public, means all the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes too. Hence there are chances that they might change them. So the key members must not be declared public. Private Access Modifier in C++ Private keyword, means that no one can access the class members declared private, outside that class. If someone tries to access the private members of a class, they will get a compile time error. By default class variables and member functions are private. Protected Access Modifier in C++ Protected, is the last access specifier, and it is similar to private, it makes class member inaccessible outside the class. But they can be accessed by any subclass of that class. (If class A is inherited by class B, then class B is subclass of class A.
  • 28. 6.CONSTRUCTORAND FUNCTION OVERLOADING CONSTRUCTOR IN C++OVERLOADING In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments. This concept is known as Constructor Overloading and is quite similar to function overloading.  Overloaded constructors essentially have the same name (name of the class) and different number of arguments.  A constructor is called depending upon the number and type of arguments passed.  While creating the object, arguments must be passed to let compiler know, which constructor needs to be called. FUNCTION OVERLOADING IN C++ Function overloading is a feature in C++ where two or more functions can have the same name but different parameters. Function overloading can be considered as an example of polymorphism feature in C++.
  • 29. CHAPTER - 4 ADVANCED C++ PROGRAMMING 1.DEALING WITH INHERITANCE The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important feature of Object Oriented Programming. Sub Class: The class that inherits properties from another class is called Sub class or Derived Class. Super Class:The class whose properties are inherited by sub class is called Base Class or Super class. The article is divided into following subtopics: 1. Why and when to use inheritance? 2. Modes of Inheritance 3. Types of Inheritance Why and when to use inheritance? Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes. If we create these classes avoiding inheritance then we have to write all of these classes avoiding inheritance then we have to write all of these functions in each of the three classes as shown in below figure: CLASS BUS CLASS CAR CLASS TRUCK TYPES OF INHERITANCE C++ supports six types of inheritance as follows: Single Inheritance Multilevel Inheritance Multiple Inheritance Heirarchical Inheritance Hybrid Inheritance Multipath Inher fuel amount() capacity() applybrakes() fuel amount() Capacity() applybrakes() Fuel amount() Capacity() Applybrakes()
  • 30. 2.ABSTRACT CLASSES An abstract class is, conceptually, a class that cannot be instantiated and is usually implemented as a class that has one or more pure virtual (abstract) functions. A pure virtual function is one which must be overridden by any concrete (i.e., non-abstract) derived class. This is indicated in the declaration with the syntax " = 0" in the member function's declaration. EXAMPLE: ClassAbstractClass{ Public: AbstractMemberFunction()=0; Pure virtual functionmakes // thisclassAbstract class. Virtual void NonAbstractMemberFunction1();// Virtual function. Void NonAbstractMemberFunction2(); }; In general an abstract class is used to define an implementation and is intended to be inherited from by concrete classes. It's a way of forcing a contract between the class designer and the users of that class. If we wish to create a concrete class (a class that can be instantiated) from an abstract class we must declare and define a matching member function for each abstract member function of the base class. Otherwise, if any member function of the base class is left undefined, we will create a new abstract class (this could be useful sometimes). An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration. The following is an example of an abstract class: class AB { public: virtual void f()=0; };
  • 31. 3.INPUT AND OUTPUT IN C++ C++ comes with libraries which provides us many ways for performing input and output. In C++ input and output is performed in the form of sequence of bytes or more commonly known as streams. Input Stream: If the direction of flow of bytes is from device(for example: Keyboard) to the main memory then this process is called input. Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device( display screen ) then this process is called output. Header files available in C++ for Input – Output operation are:  iostream: iostream stands for standard input output stream. This header file contains definitions to objects like cin, cout, cerr etc.  iomanip: iomanip stands for input output manipulators. The methods declared in this files are used for manipulating streams. This file contains definitions of setw, setprecision etc.  fstream: This header file mainly describes the file stream. This header file is used to handle the data being read from a file as input or data being written into the file as output. In C++ articles, these two keywords cout and cin are used very often for taking inputs and printing outputs. These two are the most basic methods of taking input and output in C++. For using cin and cout we must include the header file iostream in our program. In this article we will mainly discuss about the objects defined in the header file iostreamlike cin and cout.  Standard output stream (cout): Usually the standard output device is the display screen. cout is the instance of the ostream class. cout is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator (<<). #include <iostream> using namespace std; int main( ) { char sample[] = "GeeksforGeeks"; cout << sample << " - A computer science portal for geeks"; return 0; }  Output: Geeksforgeeks – A computer science portal for geeks standard input stream (cin): Usually the input device is the keyboard. cin is the instance of the class istream and is used to read input from the standard input device which is usually keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keboard.
  • 32. #include<iostream> using namespace std; int main() { int age; cout << "Enter your age:"; cin >> age; cout << "nYour age is: "<<age; return 0; } INPUT:18 OUTPUT: Enter Your Age : Your Age Is:18 4.C++ STANDARD LIBRARY The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. A working knowledge of template classes is a prerequisite for working with STL. STL has four components  Algorithms  Containers  Functions  Iterators Algorithms The header algorithm defines a collection of functions especially designed to be used on ranges of elements.They act on containers and provide means for various operations for the contents of the containers. Containers Containers or container classes store objects and data. There are in total seven standard “first- class” container classes and three container adaptor classes and only seven header files that provide access to these containers or container adaptors. Functions The STL includes classes that overload the function call operator. Instances of such classes are called function objects or functors. Functors allow the working of the associated function to be customized with the help of parameters to be passed.
  • 33. Iterators As the name suggests, iterators are used for working upon a sequence of values. They are the major feature that allow generality in STL. 5.EXCEPTION HANDLING One of the advantages of C++ over C is Exception Handling. Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. There are two types of exceptions: a)Synchronous, b)Asynchronous(Ex:which are beyond the program’s control, Disc failure etc). C++ provides following specialized keywords for this purpose. try: represents a block of code that can throw an exception. catch: represents a block of code that is executed when a particular exception is thrown. throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself. Why Exception Handling? Following are main advantages of exception handling over traditional error handling. 1) Separation of Error Handling code from Normal Code: In traditional error handling codes, there are always if else conditions to handle errors. These conditions and the code to handle errors get mixed up with the normal flow. This makes the code less readable and maintainable. With try catch blocks, the code for error handling becomes separate from the normal flow. 2) Functions/Methods can handle any exceptions they choose: A function can throw many exceptions, but may choose to handle some of them. The other exceptions which are thrown, but not caught can be handled by caller. If the caller chooses not to catch them, then the exceptions are handled by caller of the caller. In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it. 3) Grouping of Error Types: In C++, both basic types and objects can be thrown as exception. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types. BUILT IN USER DEFINED EXCEPTIONS An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
  • 34. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.  throw − A program throws an exception when a problem shows up. This is done using a throw keyword.  catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception  try - A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks. Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Here is the small description of each exception mentioned in the above hierarchy − Sr.No Exception & Description 1 std::exception An exception and parent class of all the standard C++ exceptions. 2 std::bad_alloc This can be thrown by new. 3 std::bad_cast This can be thrown by dynamic_cast. 4 std::bad_exception This is useful device to handle unexpected exceptions in a C++ program. 5 std::bad_typeid This can be thrown by typeid.
  • 35. 6 std::logic_error An exception that theoretically can be detected by reading the code. 7 std::domain_error This is an exception thrown when a mathematically invalid domain is used. 8 std::invalid_argument This is thrown due to invalid arguments. 9 std::length_error This is thrown when a too big std::string is created. 10 std::out_of_range This can be thrown by the 'at' method, for example a std::vector and std::bitset<>::operator[](). 11 std::runtime_error An exception that theoretically cannot be detected by reading the code. 12 std::overflow_error This is thrown if a mathematical overflow occurs. 13 std::range_error This is occurred when you try to store a value which is out of range. 14 std::underflow_error This is thrown if a mathematical underflow occurs. TABLE: 1.3 6.NAMESPACEIN C++ A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification. Identifiers outside the namespace can access the
  • 36. members by using the fully qualified name for each identifier, for example std::vector<std::string> vec;, or else by a using Declaration for a single identifier (using std::string), or a using Directive for all the identifiers in the namespace (using namespace std;). Code in header files should always use the fully qualified namespace name. The following example shows a namespace declaration and three ways that code outside the namespace can accesses their members. namespace ContosoData { class ObjectManager { public: void DoSomething() {} }; void Func(ObjectManager) {} } USING DIRECTIVES The using directive allows all the names in a namespace to be used without the namespace- nameas an explicit qualifier. Use a using directive in an implementation file (i.e. *.cpp) if you are using several different identifiers in a namespace; if you are just using one or two identifiers, then consider a using declaration to only bring those identifiers into scope and not all the identifiers in the namespace. If a local variable has the same name as a namespace variable, the namespace variable is hidden. It is an error to have a namespace variable with the same name as a global variable. Declaring namespaces and namespace members Typically, you declare a namespace in a header file. If your function implementations are in a separate file, then qualify the function names, as in this example. //contosoData.h #pragma once namespace ContosoDataServer { void Foo(); int Bar(); }
  • 37. C PROGRAMMING 1. Write a program that shows the summation of positive integer in between lower limit to upper limit. #include<stdio.h> #include<conio.h> int main() { long int i,a,b,sum=0; printf("enter the lower and upper number:n"); scanf("%d %d",&a,&b); for(i=a;i<=b;i++) { sum+=i; } printf("%ld",sum); getch(); } 2. Write a program that shows the even summation of positive integer in between lower limit to upper limit. #include<stdio.h> #include<conio.h> int main() { long int i,a,b,sum=0; scanf("%d %d",&a,&b); for(i=a;i<=b;i++) { if(i%2==0) sum+=i; } printf("%ld",sum); getch(); } 3. Write a program that show the odd summation of positive integer in between lower limit to upper limit if summation is greater than 9000. #include<stdio.h> #include<conio.h> int main() { long int i,a,b,sum=0; printf("enter the lower and upper number:n"); scanf("%d %d",&a,&b); for(i=a;i<=b;i++) { if(i%2!=0) sum+=i;} if(sum>9000)
  • 38. printf("%ld",sum); else printf("sum is smallar than 9000"); getch(); } 4. Write a program that show the summation of 12.2!+22.3!+32.4!+………..+n2.(n+1)! . #include<stdio.h> main(){ int i,n,r,j=0,k; printf("Enter your limit:n"); scanf("%d",&n); printf("The output is:n"); for(i=1;i<=n;i++) { r=1; for(k=1;k<=i+1;k++) r*=k; j+=r*i*i;} printf("%d",j); getch(); } 5. Write a program that shows prime/non-prime number. Sample input: 6 Output : 6 is not a prime number #include<stdio.h> #include<conio.h> int main(){ int n,i,c=0; printf("Enter the number:n"); scanf("%d",&n); for(i=1;i<=n;i++) {if(n%i==0) c++;} if(c==2) printf("%d is a prime number",n); else printf("it is not prime number"); getch(); } 6. Write a program to generate the all prime numbers of a given range. #include<stdio.h> #include<conio.h> int main()
  • 39. { int n,i,j,c,a,b; printf("Enter the upper number:n"); scanf("%d",&b); for(i=1;i<=b;i++) {c=0; for(j=1;j<=i;j++) {if(i%j==0) c++;} if(c==2) printf("n%d is a prime numbern",i); printf("n");} getch(); } 7. Write a program for nPr #include<stdio.h> main(){ int i,n,fact=1,sum=1,p,r,c; printf("enter the value of n and r:n"); scanf("%d %d",&n,&r); for(i=1;i<=n;i++) fact=fact*i; c=n-r; for(i=1;i<=c;i++) {sum=sum*i;} p=fact/sum; printf("the value of npr is=%d",p); getch(); } 8. Write a program for nCr #include<stdio.h> main(){ int i,n,fact=1,sum=1,p,r,c,m=1,e; printf("enter the value of n and r:n"); scanf("%d %d",&n,&r); for(i=1;i<=n;i++) fact=fact*i; c=n-r; for(i=1;i<=c;i++) sum=sum*i; for(i=1;i<=r;i++) m=m*i; p=m*sum; e=fact/p; printf("the value of ncr is=%d",e); getch();
  • 40. } 9. Write a program that shows the all factorial of positive integer in between lower limit to upper limit. #include<stdio.h> #include<conio.h> int fact(int i); int main() { int n,i; printf("enter the number:n"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("i!=%dn",fact(i)); } getch(); } int fact(int i) {if(i<=1) return(1); else return(i*fact(i-1)); getch(); } 10. Write a program to generrate Fibonacci Series of a given range. (Fibonacci Series= 0 1 1 2 3 5 8 13 …..) Sample input: 7 Output : 0 1 1 2 3 5 8 13 21 #include<stdio.h> main(){ int m=0,r=1,p,n,i; printf("Enter the input:n"); scanf("%d",&n); printf("The output is:n"); printf("0 1 "); for(i=0;i<n;i++) {p=m+r; m=r; r=p; printf("%d ",p);} getch(); } 11. Write a program that shows the multiplication of two matrix. #include<stdio.h>
  • 41. #include<conio.h> void main () { int i,j,k; int a[3][3],b[3][3],c[3][3],sum; for(i=0;i<3;i++) {for(j=0;j<3;j++) {scanf("%d",&a[i][j]);} } printf("first matrix:n"); for(i=0;i<3;i++) {for(j=0;j<3;j++) {printf("%d",a[i][j]);} printf("n");} for(i=0;i<3;i++) {for(j=0;j<3;j++) {scanf("%d",&b[i][j]);} } printf("secound matrix:n"); for(i=0;i<3;i++) {for(j=0;j<3;j++) {printf("%d",b[i][j]);} printf("n");} printf("multiplication:n"); for(i=0;i<3;i++) {for(j=0;j<3;j++) {sum=0; for(k=0;k<3;k++) {sum=sum+a[i][k]*b[k][j];} c[i][j]=sum; printf("%d ",c[i][j]); } printf("n"); } getch(); } 12. Write a program that shows a transpose matrix. #include<stdio.h> #include<conio.h> void main () { int i,j; int a[3][3]; for(i=0;i<3;i++) {for(j=0;j<3;j++) {scanf("%d",&a[i][j]);}} printf("the matrix is:n"); for(i=0;i<3;i++) {for(j=0;j<3;j++)
  • 42. {printf("%d ",a[i][j]);} printf("n");} printf("transpose matrix:n"); for(i=0;i<3;i++) {for(j=0;j<3;j++) {printf("%d ",a[j][i]);} printf("n");} getch();} C++ PROGRAMMING Compute quotient and remainder 1. 1. #include <iostream> 2. using namespace std; 3. 4. int main() 5. { 6. int divisor, dividend, quotient, remainder; 7. 8. cout << "Enter dividend: "; 9. cin >> dividend; 10. 11. cout << "Enter divisor: "; 12. cin >> divisor; 13. 14. quotient = dividend / divisor; 15. remainder = dividend % divisor; 16. 17. cout << "Quotient = " << quotient << endl; 18. cout << "Remainder = " << remainder; 19. 20. return 0; 21. } 2. Calculate H.C.F using recursion 1. #include <iostream> 2. using namespace std; 3. 4. int hcf(int n1, int n2); 5. 6. int main() 7. { 8. int n1, n2; 9. 10. cout << "Enter two positive integers: "; 11. cin >> n1 >> n2; 12. 13. cout << "H.C.F of " << n1 << " & " << n2 << " is: " << hcf(n1, n2);
  • 43. 14. 15. return 0; 16. } 17. 18. int hcf(int n1, int n2) 19. { 20. if (n2 != 0) 21. return hcf(n2, n1 % n2); 22. else 23. return n1; 24. } 3. Calculate FactorialUsing Recursion 1. #include<iostream> 2. using namespace std; 3. 4. int factorial(int n); 5. 6. int main() 7. { 8. int n; 9. 10. cout << "Enter a positive integer: "; 11. cin >> n; 12. 13. cout << "Factorial of " << n << " = " << factorial(n); 14. 15. return 0; 16. } 17. 18. int factorial(int n) 19. { 20. if(n > 1) 21. return n * factorial(n - 1); 22. else 23. return 1; 24. } 4. C++ program to add two complex numbers by passing objects to a function. 1. #include <iostream> 2. using namespace std; 3.
  • 44. 4. class Complex 5. { 6. private: 7. int real; 8. int imag; 9. public: 10. Complex(): real(0), imag(0) { } 11. void readData() 12. { 13. cout << "Enter real and imaginary number respectively:"<<endl; 14. cin >> real >> imag; 15. } 16. void addComplexNumbers(Complex comp1, Complex comp2) 17. { 18. // real represents the real data of object c3 because this function is called using code c3.add(c1,c2); 19. real=comp1.real+comp2.real; 20. 21. // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2); 22. imag=comp1.imag+comp2.imag; 23. } 24. 25. void displaySum() 26. { 27. cout << "Sum = " << real<< "+" << imag << "i"; 28. } 29. }; 30. int main() 31. { 32. Complex c1,c2,c3; 33. 34. c1.readData(); 35. c2.readData(); 36. 37. c3.addComplexNumbers(c1, c2); 38. c3.displaySum(); 39. 40. return 0; 41. }
  • 45. FIGURE FIG : 1.1 FIG :1.2 FIG :1.3
  • 47. PROJECT SOLUTION // Simple Quiz Library // This header file contains all functions that are required to run the quiz system #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <conio.h> #include "miscFuncLib.h" #include "allVars.h" void startQuiz(); void menuController(); void prepareQuizData(); void selectTenQuestions(); int checkDup(int currQ); void runQuiz(); void displayResult(); void addCategoryTotal(char *qCategory, int marks, int fmarks); // It shows the first opening menu void menuController() { // printf("Here is the menu controlern"); int ch = 0; while (ch != 2) { // Present the menu system("cls"); printf("Welcome to Simple Quiz Gamen"); printf("---------------------------nn"); printf(" Your Optionsn"); printf(" ------------nn"); printf(" 1) Start The gamen"); printf(" 2) Quitnn"); printf(" Enter your choice (1/2) :: "); scanf ("%d", &ch); // Evaluate choices switch (ch)
  • 48. { case 1 : startQuiz(); break; case 2 : break; default : printf("Please choose between 1 or 2 .. Press a key to continue.n"); getch(); } } } // This function will call the functions that runs a quiz session void startQuiz() { prepareQuizData(); selectTenQuestions(); runQuiz(); displayResult(); } // This function will read all the data from the question bank (SQG-QTNBNK.txt) and stores it into an array void prepareQuizData() { // read data from the file char buff[268]; char fld[50]; FILE *fp; fp = fopen("SQG-QTNBNK.txt", "r" ); printf("Loading Question Bank ...n"); while (fgets(buff, 259, fp)!=NULL) { // Extract the actual fields content from buffer stringExtract(fld, buff, 0, 8); strcpy(quizQuestions[maxQuestions].qCategory, fld); //printf("%sn",quizQuestions[maxQuestions].qCategory); stringExtract(fld, buff, 9, 13); quizQuestions[maxQuestions].qId = atoi(fld); //printf("%dn",quizQuestions[maxQuestions].qId); stringExtract(fld, buff, 14, 53); strcpy(quizQuestions[maxQuestions].qText, fld);
  • 49. //printf("%sn",quizQuestions[maxQuestions].qText); stringExtract(fld, buff, 54, 103); strcpy(quizQuestions[maxQuestions].qAnswer1, fld); //printf("%sn",quizQuestions[maxQuestions].qAnswer1); stringExtract(fld, buff, 104, 153); strcpy(quizQuestions[maxQuestions].qAnswer2, fld); //printf("%sn",quizQuestions[maxQuestions].qAnswer2); stringExtract(fld, buff, 154, 203); strcpy(quizQuestions[maxQuestions].qAnswer3, fld); //printf("%sn",quizQuestions[maxQuestions].qAnswer3); stringExtract(fld, buff, 204, 253); strcpy(quizQuestions[maxQuestions].qAnswer4, fld); //printf("%sn",quizQuestions[maxQuestions].qAnswer4); stringExtract(fld, buff, 254, 254); quizQuestions[maxQuestions].qCAnswer = atoi(fld); //printf("%dn",quizQuestions[maxQuestions].qCAnswer); stringExtract(fld, buff, 255, 257); quizQuestions[maxQuestions].qAllottedMarks = atoi(fld); //printf("%dn",quizQuestions[maxQuestions].qAllottedMarks); maxQuestions++; //getch(); } } // The function selects 10 questions randomly from the array containing the entire question bank // These 10 questions would be stored in a seperate array void selectTenQuestions() { int i, currQ; time_t t; srand((unsigned) time(&t)); printf("Prepareing the quiz question list ...n"); for(i=0; i<10; i++) { currQ = rand()%maxQuestions; while (checkDup(currQ)) { currQ = rand()%maxQuestions; } testQuestions[i].qIndex = currQ; strcpy(testQuestions[i].qCategory, quizQuestions[currQ].qCategory); testQuestions[i].qId = quizQuestions[currQ].qId;
  • 50. strcpy(testQuestions[i].qText, quizQuestions[currQ].qText); strcpy(testQuestions[i].qAnswer1, quizQuestions[currQ].qAnswer1); strcpy(testQuestions[i].qAnswer2, quizQuestions[currQ].qAnswer2); strcpy(testQuestions[i].qAnswer3, quizQuestions[currQ].qAnswer3); strcpy(testQuestions[i].qAnswer4, quizQuestions[currQ].qAnswer4); testQuestions[i].qCAnswer = quizQuestions[currQ].qCAnswer; testQuestions[i].qAllottedMarks = quizQuestions[currQ].qAllottedMarks; } } // When selecting questions for the quiz session there is a possibility that same questions may be selected multiple times // This function checks if the current query has already been stored in the array int checkDup(int currQ) { int i; for(i = 0; i < 10; i++) { if (testQuestions[i].qIndex == currQ) { return 1; } } return 0; } // This function will present the selected 10 questions before the player and ask him to find right answer // This function will also record the performance and calculate the total allotted marks void runQuiz() { int i; char yn = ' ', ysno = ' '; // Present welcome scene printf("Welcome to Simple Quiz Gamenn"); printf("Player's Name :: "); scanf(" %[^n]s", playerName); printf("nnReady for quiz ? (Y/N) :: "); scanf(" %c", &yn); if (yn == 'Y' || yn == 'y') {
  • 51. for(i = 0; i < 10; i++) { ysno = 'N'; while (ysno == 'N' || ysno == 'n') { system("cls"); printf("Question number - %d :: n", i+1); printf("Question category - %s :: n", testQuestions[i].qCategory); printf("Question text - %s nn", testQuestions[i].qText); printf("Avalilable answers .. n"); printf("1) %sn", testQuestions[i].qAnswer1); printf("2) %sn", testQuestions[i].qAnswer2); printf("3) %sn", testQuestions[i].qAnswer3); printf("4) %snn", testQuestions[i].qAnswer4); printf("Marks allotted - %d :: nn", testQuestions[i].qAllottedMarks); printf("Enter the correct answer (1/2/3/4) :: "); scanf("%d", &testQuestions[i].qSelectedAns); printf("nnLock it ? (Y/N) :: "); scanf(" %c", &ysno); } if (testQuestions[i].qCAnswer == testQuestions[i].qSelectedAns) testQuestions[i].qRecivedMarks = testQuestions[i].qAllottedMarks; else testQuestions[i].qRecivedMarks = 0; totMarks = totMarks + testQuestions[i].qRecivedMarks; fullMarks = fullMarks + testQuestions[i].qAllottedMarks; } } } // The function displays the final result after the quiz session is over void displayResult() { int i; printf("Now you may see the results "); getch(); for(i = 0; i < 10; i++) {
  • 52. printf("Question number - %d :: n", i+1); printf("Question category - %s :: n", testQuestions[i].qCategory); printf("Question text - %s nn", testQuestions[i].qText); printf("Avalilable answers .. n"); printf("1) %sn", testQuestions[i].qAnswer1); printf("2) %sn", testQuestions[i].qAnswer2); printf("3) %sn", testQuestions[i].qAnswer3); printf("4) %snn", testQuestions[i].qAnswer4); printf("Correct Answer - %dn", testQuestions[i].qCAnswer); printf("You Selected - %dn", testQuestions[i].qSelectedAns); printf("Marks Received - %dnn", testQuestions[i].qRecivedMarks); getch(); // Add category wise totals addCategoryTotal(testQuestions[i].qCategory, testQuestions[i].qRecivedMarks,testQuestions[i].qAllottedMarks); } printf("%s, you recieved a total marks of %d out of %d nn", playerName, totMarks, fullMarks); // Printing the category summary printf("Categorywise breakup ..n"); for(i = 1; i <= maxCategory; i++) { printf("Category : %s Obtained Marks : %d Total Marks : %dn", categoryTotals[i].qCategory, categoryTotals[i].totMarks, categoryTotals[i].fullMarks); } getch(); } // The function calculates the question category wise total and stores it into array. void addCategoryTotal(char *qCategory, int marks, int fmarks) { int i; int marksAdded = 0; for(i = 1; i <= maxCategory; i++) { if (strcmp(qCategory, categoryTotals[i].qCategory)==0) { categoryTotals[i].totMarks = categoryTotals[i].totMarks + marks;
  • 53. categoryTotals[i].fullMarks = categoryTotals[i].fullMarks + fmarks; marksAdded = 1; } } if (marksAdded==0) { maxCategory += 1; strcpy(categoryTotals[maxCategory].qCategory , qCategory); categoryTotals[maxCategory].totMarks = marks; categoryTotals[maxCategory].fullMarks = fmarks; } }