Anda di halaman 1dari 38

ASHISH KUMAR :: 9990781319 :: 1

A computer can neither think nor make any judgement on its own. Also it is impossible for any
computer to independently analyze a given data or follow its own method of selection. It needs
a program to tell what to do.
A program is a set of instructions that are arranged in a sequence that guides a computer to
solve a problem.
The process of writing a program is called programming.

A programming language is an artificial language designed to express the computation that


can be performed by a machine, particularly by a computer.
Programming languages can be used to create programs that control the behavior of a machine
to express algorithm precisely or as a mode of human communication.
In other words, a programming language is a notation for writing programs which are
specifications of a computation or algorithm.

1st Generation
Low Level
Languages
2nd Generation

Programming High Level 3rd Generation


Languages Languages

4th Generation

Very High Level


5th Generation
Languages

It is the machine level programming language. This is a sequence of instructions written in the
form of Binary Numbers consisting of 1 and 0 to which computer responds directly.
Machine level language is also known as computers native language as this system of code
directly understood by the computer.
An instruction prepared in any machine language will have at least two parts:
The first part is the command or operations, which tells the computer what functions are
to be performed. All computers have an operation code of its functions.
The second part of the instruction is the operand which tells the computer where to find
and store the data that has to be manipulated.

ADVANTAGE : The code a user writes can run very fast and efficiently since it is directly
executed by the CPU.

DISADVANTAGES
It is difficult to develop and understand a program using 1GL.
Anybody going through the program for checking will have a difficult task understanding
what will achieve when this program is executed.
Machine language for one computer could be different for another computer.

ASHISH KUMAR :: 9990781319 :: 2


When we employ symbols (letters, digits or special characters) for the operation part and the
address part and the parts of instruction code, this representation is called an assembly
language program.
Each machine has got its own assembly language which dependent upon the internal
architecture of the processor.

ASSEMBLER: An assembler is a translator which takes its input in the form of assembly
language program and produces machine language code as its output.
An assembly language program cannot be executed by the machine directly as it is not in the
binary form. An assembler is needed in order to translate an assembly language program into
the object code executed by the machine.

ASSEMBLY LANGUAGE
ASSEMBLER OBJECT CODE
PROGRAM

ADVANTAGES
It is more convenient than machine language.
It gives a little more readability.

DISADVANTAGES
It is machine dependent.
It is not as fast as machine language

It is the refinement of second generation language. The third generation brought to make the
languages more programmers friendly. This includes features like improved support for
aggregate data types and expressing concepts in a way that favors the programmer, not the
computer. A 3GL improves over 2GL by having the computer take care of non-essential details
not the programmer. For example: ALGOL, COBOL, C, C++, C#, Java, Delphi etc.

COMPILER & INTERPRETER: The names compiler and interpreter primarily used for the
programs that translate source code from a high level language to low level language.
A compiler and interpreter is likely to perform many or all of the following operations: lexical
analysis, preprocessing, parsing, syntax-directed translation, code-generation and code-
optimization, e.g. Turbo C++.

COMPILER INTERPRETER

Scans the entire program first and Translate the program line by line.
then translate it into machine code. Every time the program is executed
Converts the entire program to object every line is checked its syntax error
code; when all the syntax errors are and then converted to equivalent
removed, execution takes place. machine code.
Slow for debugging. Good for fast debugging.
Execution time is less Execution time is more.

ASHISH KUMAR :: 9990781319 :: 3


It is the high level language that requires significantly fewer instructions to accomplish a
particular task than a 3GL does. Thus a programmer should be able to write a program faster
in 4GL than in 3GL.
4GL are non-procedural languages. The programmer does not have to give the details of the
procedures in the programs but instead specifies what is wanted.
Major 4GL are used to get information from files and data bases and to display or print the
information.
A 4GL is designed with a special purpose in mind, such as the development of commercial
business softwares.
FoxPro, FOCUS, SQL, NATURAL, MATLAB, SQR are few common 4GL.

A 5GL is a programming language based around solving problems using constraints given to
the program rather than using an algorithm written by a programmer. Most constraints based
and logic programming languages and some declarative languages are 5GL.
While 4GL are designed to build specific programs, 5GL are designed to make the computer to
solve the given problem without the programmer.
This way the programmer only needs to worry about what problem need to be solved and what
conditions need to be met, without worrying about how to implement a routine or algorithm to
solve them.

5GL used mainly in artificial intelligence research e.g. Prolog, OPS5, Mercury.

C is a general purpose programming language developed between 1969 and 1973 by Dennis
Ritchie at the Bell Telephone Laboratories for use with the UNIX operating system.
Although C was designed for implementing system software, it is also widely used for
developing portable application softwares.

The initial development of C occurred at AT&T Bell Labs between 1969 and 1973; according to
Dennis Ritchie the most creative period occurred in 1972.
It was named C because its features were derived from an earlier language called B, while
according to Ken Thompson was a striped down version of BCPL programming language.
The origin of C is closely tied to the development of Unix Operating System, originally
implemented in assembly language on a PDP-7 by Ritchie and Thompson. Eventually they
decided to port the PDP-11.
Bs inability to take the advantage of some of the PDP-11 features led to the development of
any early version of C.

C is a procedural systems implementation language. It was designed to be compiled using a


relative straight forward compiler to provide low-level access to the memory, to provide the
language constructs that map efficiently to machine instruction and to require minimal run-
time support. C was therefore useful for many applications that had formerly been coded in
assembly language.
C is a hardware independent widely available language. Application written in C can run with
little or no modifications on a wide range of different computer systems.

ASHISH KUMAR :: 9990781319 :: 4


Variables may be hidden in nested blocks.
Partially weak typing: for instance, character can be used as integers.
Low-level access to computer memory by converting machine address to typed pointers.
Functions and data pointers supporting run time polymorphism.
A relative small set of reserved keywords.
A large number of compound operators such as +=, ==, *=, ++ etc.

C++ programming language was developed at AT&T Bell Labs in the early 1980 by Bjarne
Stroustrup. C++ provides a number of features that spruce up the C language, but more
importantly, it provides capabilities for object oriented programming.
In short, C++ is the upgraded version of C.

A C++ program is a collection of one or more functions. Each function performs some particular
task and collectively they solve the entire problem.
A function is like a black box that does something for you without exposing the internals
inside.
Every C++ program must have a function named main.
One can assume main() as master and other functions as servants.
C++ begins execution at main() even if main is not the first function in the program.

The header file contains the definition of various built-in functions. e.g.
<iostream.h> contains definition input-output functions for C++
<stdio.h> contains definition input-output functions for C

A preprocessor is a program that executes automatically before the compilation phase.


e.g. #include<iostream.h> It insert contents of header file into a program.

Comments in a program can be useful for a variety of purpose. They provide the easiest way to
set off specific parts of codes and their purposes; as well as providing a visual split between
various parts of the code.
Comments cannot be executed by the compiler. Comments come in two forms:
// Single line comment
/* Multi line
Comments */

Letters A-Z, a-z


Digits 0-9
Special Symbols + - / * & % ! ^ ~ ( ) [ ] { } = etc.
White Spaces Blank Space, Tab, Return, New Line etc.
Others ASCII (American Standard Codes for
Information Interchange)

ASHISH KUMAR :: 9990781319 :: 5


ASCII are the most common codes to represent characters in computers.
It represents English characters as numbers with each letter assigned a number from 0 to 255.
Some important ASCII codes are:

32 (space) (Question 95 _ (underscore)


63 ?
(exclamation mark) 96 ` (Grave accent)
33 !
mark) 64 @ (At sign) 97 a (Lowercase a )
(Quotation 65 A (Capital A ) 98 b (Lowercase b )
34 "
mark) 66 B (Capital B ) 99 c (Lowercase c )
35 # (Number sign) 67 C (Capital C ) 100 d (Lowercase d )
36 $ (Dollar sign) 68 D (Capital D ) 101 e (Lowercase e )
37 % (Percent sign) 69 E (Capital E ) 102 f (Lowercase f )
38 & (Ampersand) 70 F (Capital F ) 103 g (Lowercase g )
39 ' (Apostrophe) 71 G (Capital G ) 104 h (Lowercase h )
(round brackets 72 H (Capital H ) 105 i (Lowercase i )
40 (
or parentheses) 73 I (Capital I ) 106 j (Lowercase j )
(round brackets 74 J (Capital J ) 107 k (Lowercase k )
41 )
or parentheses) 75 K (Capital K ) 108 l (Lowercase l )
42 * (Asterisk) 76 L (Capital L ) 109 m (Lowercase m )
43 + (Plus sign) 77 M (Capital M ) 110 n (Lowercase n )
44 , (Comma) 78 N (Capital N ) 111 o (Lowercase o )
45 - (Hyphen) 79 O (Capital O ) 112 p (Lowercase p )
46 . (Full stop , dot) 80 P (Capital P ) 113 q (Lowercase q )
47 / (Slash) 81 Q (Capital Q ) 114 r (Lowercase r )
48 0 (number zero) 82 R (Capital R ) 115 s (Lowercase s )
49 1 (number one) 83 S (Capital S ) 116 t (Lowercase t )
50 2 (number two) 84 T (Capital T ) 117 u (Lowercase u )
51 3 (number three) 85 U (Capital U ) 118 v (Lowercase v )
52 4 (number four) 86 V (Capital V ) 119 w (Lowercase w )
53 5 (number five) 87 W (Capital W ) 120 x (Lowercase x )
54 6 (number six) 88 X (Capital X ) 121 y (Lowercase y )
55 7 (number seven) 89 Y (Capital Y ) 122 z (Lowercase z )
56 8 (number eight) 90 Z (Capital Z ) (curly brackets
123 {
57 9 (number nine) (square or braces)
58 : (Colon) 91 [ brackets or box (vertical-bar,
59 ; (Semicolon) brackets) vbar, vertical
124 |
(Less-than sign 92 \ (Backslash) line or vertical
60 <
) (square slash)
61 = (Equals sign) 93 ] brackets or box (curly brackets
125 }
(Greater-than brackets) or braces)
62 > sign ; (Caret or (Tilde ; swung
126 ~
Inequality) 94 ^ circumflex dash)
accent) 127 DEL (Delete)

ASHISH KUMAR :: 9990781319 :: 6


The smallest individual unit in a program is known as token / lexical unit. C++ has the
following tokens:
Identifiers Literals Operators
Keywords Punctuators

These are the fundamental building blocks of a program and are used as general terminology
for the names given to different parts of the program, viz. variables, functions etc.
An identifier is a series of characters consisting of letters, digits and underscore.
An identifier can be of any length, but only first 31 characters are required to be recognized
by the C++ compiler.
C++ is case sensitive- uppercase and lowercase characters are different in C++.
Note: Avoid starting identifiers with the underscore to prevent the conflict with the
compiler generated identifiers and standard library identifiers.

Keywords are the words that convey a special meaning to language compiler. These are
reserved for special purpose and must not be used as normal identifier names. e.g. if, default,
else, do, for, while, float, int, unsigned, void, short etc.

Literals (often referred to as constants) are data items that never change their value during a
program run. C++ allows several kinds of literals:
Integer Constant
Integers are the whole numbers without any fractional part. An integer constant must have at
least one digit and must not contain decimal point. It may contain either + or sign. A number
with no sign is considered to be as positive. Commas cannot appear in a integer constant. C++
allows three types of integer constant:
Decimal (base 10): An integer constant consisting of a sequence of digits is taken to be decimal
integer constant unless it is begins with zero.
Octal (base 8): A sequence of digits starting with zero is taken to be as octal integers.
Hexadecimal (base 16): A sequence of digit preceded by 0x or 0X is taken to be as
hexadecimal integers. Example:

Decimal Octal Hexadecimal


12 014 0XC
Character Constant
A character constant is one character enclosed in single quotes. The value of character constant
is the numerical value of character constant in the machines character set. e.g. C 99.
C++ have certain non-graphic character in the character constant. Non-graphic characters are
those characters that cannot be typed directly from the keyboard. e.g. backspace, tabs, carriage
return etc.
These non-graphic characters can be represented by using Escape Sequences. An Escape
Sequence is represented by a backslash followed by one or more characters.
\ Single Quote \a Alert or Bell \t Horizontal Tab
\ Double Quote \b Backspace \v Vertical Tab
\? Question Mark \f New Page \0 Null
\\ Back Slash \n New Line \On Octal Numbers
\xHn Hexadecimal Numbers
ASHISH KUMAR :: 9990781319 :: 7
Floating / Real Constant
There are numbers having fractional parts. They may be written in one of the two forms:
A real constant in fractional form must have at least one digit before and at least
one digit after decimal point. It may also have either + or sign preceding it. A real
constant with no sign assumed to be positive. e.g. 2.0, 17.5, -13.04
A real constant in exponent form has two parts:
o A mantissa (the part appearing before E)
o A exponent (the part appearing after E)
The mantissa must be either an integer or a proper real constant. The exponent must
be an integer. e.g. 152E05, 1.52E07, 1.52E+8.

String Literal
Multiple character constants are treated as string literals. A string literal is a sequence of
characters surrounded by double quotes.
The difference between a string literal and a multi-character constants are treated as integers
and their values are dependent. Whereas a string literal is treated as sequence of characters
(array of chars).
Each string literal is by default added with special character \0 which makes the end of string.
\0 is a single character. Thus the size of the string is the number of characters plus one for
this terminator. e.g. abc is of size 4 and \ab is of size 3.

Brackets [ ] Colon :
Opening and closing brackets indicates single It indicates a labeled statement.
and multi-dimensional array subscript. Asterisk *
Parentheses ( ) It is used for pointer declaration. The
Opening and closing parentheses indicates asterisk is also used as an operator to either
function calls and function parameters. pointer or the multiplication operator.
Parentheses also group expressions and Ellipsis
isolate conditional expressions. It is used in the formal argument lists of
Braces { } functions prototypes to indicate a variable
Opening and closing braces indicate the start number of argument (which means argument
and end of compound statement. list may contain any number of arguments
Comma , and of any data type).
It is used as separator in a function Equal to =
argument list. It is used for variable initialization and as an
Semicolon ; assignment operator in expressions.
It is used as statement terminator. Pound sign #
It is used for preprocessor directive.

FILES LINKS

GLOBAL DECLARATION

main ( )

FUNCTIONS

ASHISH KUMAR :: 9990781319 :: 8


P1. Exact Print Name Mark Grad
Name Marks Class s e
Ram 78 XI Ram 78 A1
Sita 65 XII Sita 65 A2
Bharat 79 IX Bharat 79 A1
Shankar 98 X Shanka 98 A+
Vishnu 78 XI r
P2. Exact Print Vishnu 78 A1

P3. WAP that prints a box, an oval, an arrow and a diamond:


************* * *** *
* * *** * * * *
* * ***** * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
************* * *** *
P4. WAP that will print your initials in block letters, each letter made up of the same
character it represents. The letters should be a minimum of seven printed lines high and
should appear all in a row. Example:
A S S H H IIIIIII S S H H
A A S S H H I S S H H
A A S H H I S H H
AAAAAA S S HHHHHHHH I S S HHHHHHHH
A A S H H I S H H
A A S S H H I S S H H
A A S S H H IIIIIII S S H H

Data types are means to identify the type of data and associated operations of handling it.
Data types are of two types:
Fundamental: int, char, float, double, void
Derived: array, functions, pointers, references, classes, structures, union, enumerations

This data type represents integers commonly used in mathematics.

This data type represents character. Characters can store any number of the C++ basic
character set. If a character from this set is stored in char, its value is equivalent to the
integer code (ASCII code) of the character because it is very easy to code numbers into binary.

A number having fractional part is a floating point number. e.g. 3.14159. Decimal point
signals it is a floating point number not an integer, for example 12 is an integer but 12.0 is

ASHISH KUMAR :: 9990781319 :: 9


a floating point number.
These are also written in exponent notations, e.g. 5.8 = 0.58E01
Floating point operations are usually slower than integer operation and there are only 7 digits
after decimal place.

This is also used for handling floating point numbers. But it occupies twice as much memory
as type float and store floating point numbers with much larger range and precision. There
are 15 digits after decimal place in a double floating point number.

The void data type specifies an empty set of values. It is used as the return data type for the
functions that do not return a value. No object of type void may be declared.
TYPE SIZE RANGE
int 2 bytes = 16 bits 2 16 -32768 32767
char 1 byte = 8 bit 2 8 -128 127
float 4 byte = 32 bits 2 32 3.410-38 - (3.410-38-1)
double 8 byte = 64 bits 264 1.710-308 - (1.710-308-1)

Signed: By default, for all the data types.


Unsigned: It makes the data types not to hold negative values.
The leftmost bit of a memory word determines the sign of the contents of the word;
when it is set to 1 the value stored in the remaining bits are negative.
Long: Generally, doubles the byte size.
Short: On some computers it halfs the amount of memory. As for present day computers,
with memory cheap and plentiful, most compiler writers make no distinction between int
and short int.

A variable refers to the storage location referenced by identifiers where content can varying
during processing.
There are two values associated with symbolic variables:
rvalue: it is the data value stored at variable
lvalue: it is the location value (address of variable in the memory)

This keyword creates constant variables. It means the value of variable remains same
throughout the program. e.g. const float pi=3.1428;

The operations (specific tasks) are represented by operators. The objects of the operation are
referred to as operand. e.g.
Expression
a+b
Operand

Operator
There are three types of operators:
Unary operators: Unary operators. e.g. +a, -a Operators that act on two
Operators that act on one etc. operands are referred to as
operand are referred to as Binary operators: Binary operators. e.g. a+b,
a-b etc.

ASHISH KUMAR :: 9990781319 :: 10


Ternary operators: Operators that act on three Ternary operators. e.g.
operands are referred to as 6>4?9:7 etc.

Unary + it is by default value for all operands.


Unary - it reverse the sign of operands. Same as in mathematics.

+ Addition * Multiplication % Modulus (remainder)


Subtraction / Division

Order of evaluation (precedence): ( ) ... unary ... unary ... * ... / . .. % ... ...

= is known as assignment operator. It causes the value on the right to be assigned to the
variable on the left. e.g. a 5 It stores 5 in variable a.

Less than Less than equal to Equal to


Greater than Greater than equal to ! Not equal to

They are used only for numbers and characters, not for strings.
If comparison is true, then result is 1 and if comparison is false, then result is 0.

Logical operators refer the ways by which relational operators are connected.
& & Logical AND || Logical OR ! Logical NOT
If comparison is true, then result is 1 and if comparison is false, then result is 0.

, , * , / , %
Example: x x 3 & x 3 both have same meaning.

Increment ( ): It adds 1 to the value of Decrement ( ): It subtracts 1 from the


existing variable or operand. value of existing variable or operand.
They both come in two versions:

Prefix: The prefix increment and decrement Postfix: The prefix increment and decrement
operators follow: change then use rule i.e. they operators follow: use then change rule i.e. they
first change the value of their operand, then first use the value of their operand in
use the new value in evaluating the evaluating the expression, then change the
expression. operands value.

P1. Store any two numbers in integer data type from user and perform all arithmetic
operations on them.
P2. Store a number in integer type & print table. Example:
7 14 21 28 35 42 49 56 63 70

ASHISH KUMAR :: 9990781319 :: 11


P3. Store any one number in integer type from user and print table. Example:
Enter the number = 7 7X1=7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70
P4. Store any one number from user and print three tables as given in example:
Enter the number = 7

6 7 8
12 14 16
18 21 24
24 28 32
30 35 40
36 42 48
42 49 56
48 56 64
54 63 72
60 70 80
P5. Store SALE and PURCHASE in float data type from user and print: PURCHASE,
SALE, COMMISION, SALES TAX, VAT TAX and PROFIT/LOSS
COMMISION = 5% OF SALE SALES TAX = 4% OF SALE
VAT TAX = 11% OF SALE
PROFIT/LOSS = SALE PURCHASE SALES TAX VAT TAX
P6. Store a number in int data type from the users and calculate the sum of numbers from
n(n 1)
1 to the number entered by the user. Sum = .
2
P7. Store four numbers from user a and b (int) and c and d (flaot). Evaluate the following
expressions:
c cd cd a
a. 3 e.
d c. 3 5 b
b. (c d )(c d ) 4c 1
f.
1 cd
d. d
c
P8. WAP that converts a Celsius temperature to Fahrenheit. The program should print both
9
the values with identifying message. F C 32
5
P9. Store radius in float type from user and print the diameter, circumference and area of
the circle Must declare a constant PI = 3.14285
P10. Input the Principal Amount, rate of interest and the time period from the user and
P R T
calculate Interest Amount. I .
100

ASHISH KUMAR :: 9990781319 :: 12


P11. WAP to take radius input from the user, compute the volume of sphere and print
4 3
them on the screen. V r
3
P12. The Fibonacci numbers F1, F2, F3,Fn are defined by the relations:
F1 = 1 F2 = 2 F(n) = F(n-1) + F(n-2)
F3 and successive numbers of the series are obtained by adding the preceding two
numbers. For large n ratios of two consecutive Fibonacci Numbers is approximately
0.618033989. Given that F(100) = 354,224,848,179,261,915,075. WAP to find
approximations of F(99) and F(101).
P13. The Lucas Numbers are defined by the same recurrence relation as Fibonacci Series,
where L1 is 1 but L2 is 3. WAP to print first 10 Lucas numbers.
P14. WAP to print first 10 Fibonacci numbers.
P15. Evaluate b = a+++++a if a = 10.
P16. Evaluate x = ++y+y++ if y = 10.
P17. Give the output of the following programs:
int x 1, y 2, z 3, w; int x 10, y 11, z 12, w;
w x y z; w x y ;
cout w " " x " " y " " z "\n" ; cout w " " x " " y " " z "\n" ;
w x y z ; w z% y;
cout w " " x " " y " " z "\n" ; cout w " " x " " y " " z "\n" ;
w x * y% z; w y x * z;
cout w " " x " " y " " z "\n" ; cout w " " x " " y " " z "\n" ;
w x z % y; w x% y% z%w ;
cout w " " x " " y " " z "\n" ; cout w " " x " " y " " z "\n" ;
w x y z; w w/ x/y ;
cout w " " x " " y " " z "\n" ; cout w " " x " " y " " z "\n" ;
w x * y y * x;
cout w " " x " " y " " z "\n" ;
w x * y x * y * z ;
cout w " " x " " y " " z "\n" ;

? : known as conditional operator.


Syntax: Expression? TrueValue : FalseValue

sizeof(variable/type): Return the size of variable or data type in bytes.


Comma: It is used to combine several expressions.

P1. A computer programming contest requires teams of 5 members each. WAP that asks for
the number of players, and then gives the number of teams and number of players left
over.

ASHISH KUMAR :: 9990781319 :: 13


P2. WAP that inputs experience and age of a person. The salary of the person is 6000
if the person is experienced and his age is more than 35 otherwise if the person is
experienced and his age is more than 28 but less than 35 then the salary should
be 4800 otherwise for experienced person the salary should be 3000 and for
inexperienced person the salary should be 2000.
P3. WAP that input Principal amount and time. If time is more than 10 years, calculate the
simple interest with rate 8%. Otherwise calculate it with 12% per annum.
P4. WAP to input a number. If the number is even print the square otherwise print its cube.
P5. WAP to input choice. If choice is 1, print area of circle otherwise print perimeter of circle.
Accept the radius of circle from user.
P6. WAP to input three integers and print the largest of three.
P7. WAP that reads a character from keyboard and print whether it is lowercase char,
uppercase char, number or symbol.

The process of converting one predefined data type to another is called Type Conversion.
As an example, consider the following program:
# include iostream.h
void main( )
{
int i 7;
float f 155.5;
double d i * f;
cout " d " d;
}
Here a variable of type int is multiplied by a variable of type float to yield a result of type
double.
This program compiles without errors, the compiler considers it normal that you want to
perform any arithmetic operations on different types.
Not all languages are this relaxed. Some dont permit mixed expressions and would flag
as an error the line that performs the arithmetic in MIXED. Such languages assume that when
you mix types youre making a mistake and they try to save you from yourself.
C++ and C, however, assume that you must have a good reason for doing what you are
doing and they help to carry out your intentions. This is one reason for the popularity of C++
and C. They give you more freedom.
Type conversions come in two forms:

Type Promotion
It is the process of assigning a value of smaller data to a value of larger data type. In the
evaluation of expressions of more than one operand data type conversions obey the following
rules:
Steps If eithers type is The resultant type of other operand
1 Long Double Long Double
2 Double Double
3 Float Float
4 Char or Short int Int or unsigned int
5 Unsigned Long Unsigned Long

ASHISH KUMAR :: 9990781319 :: 14


6 Long int and other is unsigned Long int or Unsigned Long int (according to
int capacity)
7 Long Long
8 Unsigned Unsigned

e.g. char ch; int i; float ft; double db; long double ld;
result (ch / i) (fl * db) (fl i) (ld / fl)
int double
float long
double
int double

float
double

long
double double

long
double

Type demotion
It is the process of assigning a value of larger data type to the value of smaller data type.
o When a double value is converted to float, the value is rounded to the precision of
float, before truncation occurs. If the result is out of range the behavior is undefined.
o Converting floating point value to integer type the rule is: If the value is small enough
for it to fit into an int, the digits after its decimal points are discarded and the int
variable is assigned the integer part of the floating point number. e.g. if 7.68 is assign
to int, the value is 7 and if -4.65 is assign to int, the value is -4 or -5 depending on
machine. If the value is out of range, the result is undefined.
o Converting bigger integer type to smaller int type: if the data is out of range, the
result is undefined.

An explicit type conversion is user defined that forces an expression to be of specific type.
e.g. float ( x y) / 2

Some mathematical functions in math.h are:


pow(x, y) It gives the value of xy
sqrt(x) It gives the square root of x
fabs(x) It gives the value of | x |
floor(x) It gives value of [x]
fmod(x, y) It gives the value of x % y
log(x) It gives the value of natural logarithm for x
log10(x) It gives the value of common logarithm for x
exp(x) It gives the value of ex
ceil(x) It gives the value of smallest integer
sin(x), cos(x), tan(x) Here x is in radians
asin(x), acos(x), atan(x) Here x is in radians

ASHISH KUMAR :: 9990781319 :: 15


P1. Write a equivalent C++ expressions for the following:
1 2 3
a. ut ft 3x 5 y 8xy 2
2 c.
b. 5x 3 y 2 yx
sin a tan 1 a e 2x 2
4 x|
d. e|2 x
P2. Determine the data type of the expression
100(1 pq ) ( p r ) / s

(q r ) ( long)( s p)
p int, r float, q long, s double
P3. WAP to input a number. If number is even, print its square otherwise print n 5 .
P4. WAP which will raise any number x to a positive power n. Obtain value of x and n from
the user.
P5. WAP which firstly input choice of mathematical function then takes function values and
prints the solution. Use
1 for sqrt(x)
2 for pow(x, y)
3 for log(x)
4 for exp(x)
5 for ln(x)
6 for fabs(x)

An algorithm is a logical sequence of discrete steps that describe a complete solution to a


given problem in a finite amount of time.

A flowchart is a pictorial representation of step by step solution of a problem.

Symbol Purpose Processing

Decision box
Start / Stop
Flow of Control

Input / Output Annotations

Connector

This statement is similar to the conditional operator, but it allows you to expand the scope of
your decision making by providing much more flexibility.

ASHISH KUMAR :: 9990781319 :: 16


IF IF ELSE IF - Else- IF Nested IF

Syntax: Syntax: Syntax: Syntax:

if (expression) if (expression) if (expression) if (expression)


statement; statement; statement; {
else else if (expression) if (expression)
statement; statement; statement;
else else
statement; statement;
}
else
statement;

P1. WAP that accepts two integers and print largest of two.
P2. WAP that accepts three integers and print largest of three. You can use logical
operators.
P3. WAP which accepts a number and print whether it is odd or even.
P4. WAP which inputs a year in integer and prints whether it is leap year or not.
P5. WAP which accepts month in number and print this month in words. For example: if
input is 10 it prints October.
P6. WAP which accepts month in number and check whether it has 30 days, 31 days, 28/29
days.
P7. WAP which inputs a char and print whether it is vowel or consonant.
P8. WAP which inputs a char and check whether it is a number, capital alpha, small alpha
or a symbol.
P9. Write a Temperature conversion program that gives the option of converting
Fahrenheit to Celsius or Celsius to Fahrenheit and depending upon the users choice
carries out the conversion.
P10. WAP to create equivalent of four function calculator. The program requires the user to
enter two numbers and an operator. It then carries out the specified arithmetical
operation. Finally, it displays the result.
P11. WAP to calculate commission for the salesman. The commission is calculated according
to following rates:
SALES RATE
0 5000 0%
5001 12000 3%
12001 22000 7%
22001 30000 10%
30001 onwards 15%
The program accepts the sales made by the Salesman and price of sale and displays the
calculated commission.
P18. WAP to calculate the area of circle, rectangle and a triangle depending upon users
choice.
P19. Given three numbers, WAP to write their values in descending order.
P20. WAP to convert lowercase character to uppercase character.
P21. WAP that inputs two coordinates and find the slope of line joining these coordinates.
Also, check whether the line is vertical or horizontal.

ASHISH KUMAR :: 9990781319 :: 17


P22. WAP which accepts two numbers and determines the following:
a. The first is positive, negative or zero.
b. The second is positive, negative or zero.
c. The first is exactly divisible by second.
P23. WAP that accepts coefficients a, b and c of a quadratic equation and determines its
roots are real, complex or equal.
P24. WAP that accepts a digit from the keyboard and displays it in English.
P25. WAP that input three integers and print largest of three without using logical
operators.
P12. WAP that inputs four integers and print largest of four without using logical operators.

The switch statement allows a program to determine the best course of execution based on
an expression. Syntax:

switch (expression)
{
case constant - exp1 :
default :
statement;
statement;
break;
}
case constant - exp2 :
statement;
break;
Here, break keyword cause the entire Switch statements to exit. The default keyword gives the
Switch construction a way to take an action if the value of expressions does not match any of
the case statement.
Nested Switch: Like if statements, a switch statement can also be nested. There can be a
switch as a part of the statement sequence of another switch.
Some important things about Switch:
A switch statement can only work for equality comparisons.
No two case labels in the same switch can have identical values. But in case of nested
switch, the case constants of the inner and outer switch can contain common values.
If character constants are used in the switch statement, they are automatically
converted to their integers.
The switch statement is more efficient than if in a situation that supports the
nature of switch operation.

P1. Complete P36, P37, P40, P42, P43, P45, P51 by using Switch.
P2. WAP that inputs a three digit number and print it in words. e.g. 123 One Two
Three

The jump statements unconditionally transfer program control within a function. There are
four jump statements in C++: goto, return, break, continue

ASHISH KUMAR :: 9990781319 :: 18


goto
A goto statement can transfer the program control anywhere in the program. The target
destination of a goto statement is marked by a label.
goto label;
----------
The target label and goto must appear in the same function. Syntax:
----------
label :
Where label is user supplied identifier and can appear either before or after goto.

Write programs as per examples given below:

P1. Enter a number = 7


1 2 3 4 5 6 7

P2. Enter first number = 9


Enter second number = 15
9 10 11 12 13 14 15
P3. Enter a number = 5
5 1 5
5 2 10

5 10 50
P4. Enter first number = 9
Enter second number = 12
9 is odd
10 is even
11 is odd
12 is even
P5. Enter a year = 1997
Enter a year = 2001
1997 : not a Leap Year
1998 : not a Leap Year
1999 : not a Leap Year
2000 : a Leap Year
2001 : not a Leap Year
P6.

Enter any character = b Enter any character = f


Enter any character = f Enter any character = b

b c d e f f e d c b
P7.
Enter a number = 9
Enter a number = 6
Enter a number = 6
Enter a number = 9
6 7 8 9 9 8 7 6
P8. Write a calculator program that does not exit until the user wants.

ASHISH KUMAR :: 9990781319 :: 19


P9. Enter any number = 4
Biggest number of 4 digit = 9999
P10. Enter any number = 4
Smallest number of 4 digit = 1000

P11. Enter a number = 6


Fibonacci Series upto 6 numbers: 0 1 1 2 3 5

Loops allow a set of instructions to be performed repeatedly until a certain condition is


fulfilled. C++ provides three kinds of Loops:
for while do-while

Parts of a Loop

INITIALIZATION UPDATE
TEST EXPRESSION BODY OF LOOP
EXPRESSION EXPRESSION
Before entering in The test expression is an The update This contains the
a loop, its control expression whose value expression changes statement that are
variable must be decides whether the the value of loop executed repeatedly
initialized. The loop-body will be variable. from the body of loop.
initialization of the executed or not. The update In an entry-
control variable If the test expression expression is controlled loop, first
takes place under evaluates to true (1), the executed at the end the test expression is
initialization of loop body gets executed of the loop after the evaluated if it is true
expression. otherwise (0) the loop is loop body is then body of the loop
The initialization terminated. executed. is executed,
expression is In an entry-controlled otherwise loop is
executed only once, loop, the test expression terminated.
in the beginning of is evaluated before In an exit-controlled
the loop. entering into a loop loop, the body of loop
whereas in an exit- is executed first and
controlled loop, the test then the test
expression is evaluated expression is
before exiting from the evaluated. If it is
loop. false, the loop is
for & while are entry- terminated otherwise
controlled loops. repeated.
do-while is exit-
controlled loop.

for (initializ ation exp; test exp; update exp)


Syntax:
body of loop;
If there are multiple statements in body of loop use { }.
Working of for loop

ASHISH KUMAR :: 9990781319 :: 20


INTIALIZATION

FALSE
TEST EXIT

TRUE

BODY

UPDATE EXP.

FOR LOOP VARIATIONS


Multiple initialization and update expressions
for(a 0, b 3; a c ; b a, a)
Example:
cout a endl;
Prefer prefix increment/decrement operator over postfix because prefix operators are
faster than postfix.
One can skip any or all of the loop expressions. Example:
for(a 0; a 5; )
{
int i;
is similar to for(i 1; i 10; i ) and cout a;
for(;i 10; i )
a ;
}
Infinite loop
An infinite loop is created by omitting test expression. e.g. for(a 0; ; a ) or for(;; )
Empty loop
If a loop does not entrain any statement in loop-body is said to be an empty loop.
e.g., for(a 0; a 10; a );
Declaration of variables in loop
for(int a 0; a 10; a)
Example:
{- - - - --}
The for loop is executed at least one time whether the test expression is false or true.

ASHISH KUMAR :: 9990781319 :: 21


Complete all questions of Exercise 8 by using for loop.

P1. Print your name by an Infinite loop.


P2. WAP to input two numbers from user and print which number is prime and which are
composite from first number to second number.
P3. WAP to input five numbers from user and print sum of these numbers.
P4. WAP to input five numbers from user and print multiplication table of five numbers.
P5. WAP to print reverse of a number entered by user.
P6. WAP to calculate factorial of an integer.

x 2 5x 5
P7. WAP to tabulate the function f ( x ) . x should take the values
x 3
10,8,...,8,10 .
P8. WAP to display rectangle operations and perform according to users choice.
P9. WAP that prints 1, 2, 4, 8,16, 32, 64 ,128 with and without math.h

P10. WAP that input a digit and print it in words.


P11. WAP to check whether square root of a number is prime or not.
P12. WAP to find average of list of numbers entered through keyboard.
P13. WAP to find largest number of list of numbers entered through keyboard.
P14. WAP to find the factors of a number.
P15. WAP to find LCM of two numbers.
P16. WAP print every integer between 1 and n divisible by m. Also report whether the
number divisible by m is even or odd.
P17. WAP to print sum of given sequences:
2 5 8 x2 x3 x4 x5 x6
a. ... d. x
9 13 17 2! 3! 4! 5! 6!
b. 12 32 52 ... n 2 x2 x3 xn
e. x ...
1 1 1 2 3 n
c. 1 ...
1! 2! 3! f. 1 x x 2 ... x n
P18. WAP to determine how many zeroes are there at the end of 1000!.
P19. Two numbers are entered through keyboard. WAP to find the value of one number
raised to the power of other.
3 3 3
P20. WAP to print out all Armstrong numbers between 1 and 500. e.g. 153 1 5 3 .
P21. WAP to check whether entered number is an Armstrong number or not.

ASHISH KUMAR :: 9990781319 :: 22


A loop may contain another loop in its body. This form of a loop is called nested loop.
In a nested loop, the inner loop must terminate before the outer loop.
for(a 1; a 4; a )
{
e.g. for(b 1; b a; b )
cout a " " b endl;
}

WAP using nested loops to produce the following designs:


P1. A P2.
A B
&&&&&&&&&
A B C &&&&&&&
A B C D &&&&&
A B C D E &&&
A B C D E F &
P3. P4. Enter number = 6
* *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
**************
P5. Enter number = 6 P6. Enter number = 6
+ + + + + + 1
+ + + + + 2 2
+ + + + 3 3 3
+ + + 4 4 4 4
+ + 5 5 5 5 5
+ 6 6 6 6 6 6
P7. Enter number = 6 P8. Enter number = 6
6 6 6 6 6 6 1
5 5 5 5 5 2 3
4 4 4 4 4 5 6
3 3 3 7 8 9 10
2 2 11 12 13 14 15
1 16 17 18 19 20 21
P9. Enter number = 6 P10. Enter number = 6
21 A
20 19 B B
18 17 16 C C C
15 14 13 12 D D D D
11 10 9 8 7 E E E E E
6 5 4 3 2 1 F F F F F F

ASHISH KUMAR :: 9990781319 :: 23


P11. Enter number = 5 P12. Enter number = 5
15 14 13 12 11 A
10 9 8 7 B C
6 5 4 D E F
3 2 G H I J
1 K L M N O
P13. Enter number = 5 P14. Enter number = 5
B B B B A
A B B B A A
A A B B A A A
A A A B A A A A
A A A A A A A A A
P15. Enter Number = 5 P16. Enter number = 5
A Enter character = N
A A N
A A A N N
A A A A N N N
A A A A A N N N N
A A A A N N N N N
A A A N N N N
A A N N N
A N N
N
P17. WAP using nested loops to produce a rectangle of * with 6 rows and 20 columns.

The while loop is like the if statement, tests a condition.


while (test expression) while(n! 0)
Syntax: e.g.
{- - - - - - - - - - - - - - --} cin n;
The while loop looks like a simplified version of the for loop. It contains a test
expression but no initialization or increment expressions. The initialization and
increment/decrement expression are left upto the programmer to provide.

The loop iterates/executes over and over as long as the expression is true when it is
tested. When the expression is false the program skips the body and execution continues.
While loop is an entry controlled loop.
While loop is suitable in the conditions where it is not known when the loop is
terminated.

While is preferred when you want to execute the loop body even once in case the test
condition is false.

Working of while loop

ASHISH KUMAR :: 9990781319 :: 24


FALSE
WHILE EXIT

TRUE

BODY

Complete Exercise 8 and 9 by using while loop.

The do-while loop is an exit controlled loop i.e., it evaluates the test expression at the bottom
of the loop after executing its loop body statements. This means that a do-while loop always
executes at least once.
do
{
Syntax:
------
} while(test expression);
The do-while loop is a good choice when you asking a question, whose answer will determine if
the loop is to be repeated or terminated.
Working of do-while loop

BODY

FALSE
WHILE EXIT

TRUE

Complete Exercise 8 and 9 by using do-while loop.

ASHISH KUMAR :: 9990781319 :: 25


This function causes the program to terminate as soon as it is encountered, no matter where
it appears in the program listing.
This function is defined under the header file process.h

The continue statement skips the rest of the loop statements and causes the next iteration of
the loop. Following examples shows the difference between continue and break:
for(int i 1; i 10; i) for(int i 1; i 10; i)
{ {
if(i%3 0) if(i%3 0)
continue; break;
else else
cout i " " ; cout i " " ;
} }
Output: Output:
1 2 4 5 6 7 8 9 10 1 2

ASHISH KUMAR :: 9990781319 :: 26


An array is a collection of variables of the same type that are referenced by a common name.
Arrays are very much useful in a case where quite many elements of the same data types
need to be stored and processed.
e.g. A[5] is an array named A and can store 5 elements.
The elements numbers in [ ] are called subscripts or indices.

Single Dimensional Arrays / 1D Array


A one-dimensional array is stored as a contiguous block of memory with each element of the
array taking up some portion of that memory. e.g. An array of 5 integers
234 156 784 139 642
[0] [1] [2] [3] [4]
One-dimensional arrays are structured variables, with one name used by all the variables in
the array.
These variables can share a common name and data type, but each lives in its own unique
little section of computer memory in line with all the others.
Syntax: data - type array - name[index - count]; e.g. int a[5];
The data type of the array elements is known as the base type of the array.
Accessing Individual Components Accessing Array Elements
Consider an array A[5]. Each array component for(i 0; i 5; i )
can be treated as a single variable. e.g. Consider an array A[5].
cout a[i];
a[2] 5;
cout a[3];
cin a[0];
y sqrt(a[4]);

Initializing Arrays in Declarations Size of Arrays


Consider an array A[5] and B[ ] size of array no of indices size of base type
int a[5] {23, 10, 4, 6, 8}
int B[ ] {1, 2, 3, 4, 5, 6}
Here, compiler automatically gives the values.

P1. WAP that inputs 15 numbers and print them with labelling.
P2. WAP that input 7 numbers and print their tables.
P3. WAP that input 5 numbers and find the largest number.
P4. WAP that input 5 numbers and print their sum.
P5. WAP that input 10 numbers and store them in another array in reverse order.
P6. WAP that input 10 numbers and divide into two new arrays of size 5 each.
P7. WAP that reverse the order of elements in an array.
P8. WAP that calculates the mean and standard deviation of integers.
x ( x x )2
x
n n

ASHISH KUMAR :: 9990781319 :: 27


Two-Dimensional Arrays / 2D Arrays
A two-dimensional array is an array in which each element is itself an array. A two-
dimensional array is used to represent a table with rows and columns, provided each time in
the table is of the same data type.
Syntax: data - type array - name[rows][columns]
Example: int A[4][3];
0 1 2
0 A[0][0] A[0][1] A[0][2]
1 A[1][0] A[1][1] A[1][2]
2 A[2][0] A[2][1] A[2][2]
3 A[3][0] A[3][1] A[3][2]

Total number of elements No. of rows No. of columns


Processing Array (2D) Initializing Arrays in Declarations
for(i 0; i 4; i ) Consider A[5][2]
{ int A[5][2] {1, 1, 2, 8, 3, 27, 4, 64, 5, 125} or
for(j 0; j 3; j ) int A[ ][2] {1, 1, 2, 8, 3, 27, 4, 64, 5, 125}
A[0][0] 1 A[0][1] 1 A[1][0] 2
cout A[i][j]; Here,
A[1][1] 8 A[2][0] 3 A[2][1] 27
}
and so on.
A very familiar example of two-dimensional array is a matrix.
A matrix with one row may be viewed as a vector.

P1. WAP that inputs a 3 3 matrix from user and convert it into 91 matrix.
P2. WAP that inputs a 91 matrix from user and convert it into 3 3 matrix.
P3. WAP that inputs two 81 matrices from user and convert it into a 4 4 matrix.
P4. WAP that inputs a 3 3 matrix and convert it into three 1 3 matrices.
P5. WAP that inputs a 3 3 matrix and convert it into three 1 3 matrices with data in
reverse order.
P6. WAP that inputs a 3 3 matrix and convert it into a new matrix as per following
example:
INPUT OUTPUT
2 4 5 5 4 2
5 8 9 9 8 5
2 1 7 7 1 2

P7. WAP that inputs a 3 3 matrix and convert it into a new matrix as per following
example:
INPUT OUTPUT
2 4 5 2 5 2
5 8 9 4 8 1
2 1 7 2 1 7

P8. WAP that inputs a 3 3 matrix and convert it into a new matrix as per following
example:
INPUT OUTPUT
2 4 5 5 9 7
5 8 9 4 8 1
2 1 7 2 5 2

ASHISH KUMAR :: 9990781319 :: 28


P9. WAP that inputs two 3 3 matrices and perform operations as per following example:
2 4 5 5 9 7 7 13 12
5 8 9 4 8 1 9 16 10
2 1 7 2 5 2 4 6 9

P10. WAP that inputs two 3 3 matrices and perform operations as per following example:
2 4 5 5 9 7 -3 -5 -2
5 8 9 4 8 1 1 0 8
2 1 7 2 5 2 0 -4 5

P11. WAP that inputs two 3 3 matrices and perform operations as per following example:
2 4 5 5 9 7 7 14 9
5 8 9 4 8 1 8 16 2
2 1 7 2 5 2 7 14 9

P12. WAP that inputs two 3 3 matrices and perform operations as per following example:
2 4 5 5 9 7 -3 0 3
5 8 9 4 8 1 -4 0 4
2 1 7 2 5 2 -5 0 5

P13. WAP that inputs a 3 3 matrix and convert it into a new matrix as per following
example:
INPUT OUTPUT
2 4 5 2
5 8 9 8
2 1 7 7

P14. WAP that inputs a 3 3 matrix and convert it into a new matrix as per following
example:
INPUT OUTPUT
2 4 5 5
5 8 9 8
2 1 7 2

P15. WAP that inputs a 3 3 matrix and convert it into a new matrix as per following
example:
INPUT OUTPUT
2 4 5 2 5
5 8 9 8
2 1 7 2 7

P16. WAP that inputs a 3 3 matrix and convert it into a new matrix as per following
example:
INPUT OUTPUT
2 4 5 4
5 8 9 5 9
2 1 7 1

P17. WAP to multiply two matrices.


P18. WAP to transpose a matrix.

ASHISH KUMAR :: 9990781319 :: 29


P19. WAP to delete duplicate elements from a vector.
P20. WAP that inputs a 4 4 matrix and perform following operations:
a. Add all elements of each row; store and display result in a new matrix.
b. Add all elements of each column; store and display result in a new matrix.
c. Add all elements of principal diagonal; store and display result in a new matrix.
d. Add all elements of secondary diagonal; store and display result in a new matrix.
P21. WAP that inputs a 4 4 matrix and divide it into new matrices as per following
example:
INPUT OUTPUT
2 4 5 2 2 4 5 2
5 8 9 1 5 8 9 1
2 6 7 0
8 1 4 7 2 6 7 0
8 1 4 7

A string is defined as an character array that is terminated by a null character \0.


Initializing Strings: char a[6] {' H' , ' E' , ' L' , ' L' , ' O' , '\0' }; or char a[6] " HELLO" ;
char a[7][10] {" Sunday" , " Monday" , " Tuesday" , " Wednesday",
" Thursday" , " Friday" , " Saturday", " Sunday" }
String Input & Output:
In header file stdio.h In header file iostream.h
Input: gets(variable); Input: cin.get(variable, indices);
Output: puts(variable); Output: cout.write(variable, indices);

P1. WAP to reverse all the strings stored in an array.


P2. WAP to find length of a string.
P3. WAP to count white space in a string.
P4. WAP to replace white space with +.
P5. WAP to concatenate two strings.
P6. WAP to count number of words in a string.
P7. WAP to reverse a string.
P8. WAP to count the occurrence of a given character in a string.
P9. WAP to compare two strings for equality.

Large programs are generally avoided because it is difficult to manage a single list of
instructions. Thus, a large program is broken in to smaller units known as functions.
A function is a named unit of a group of programming statements. This unit can be invoked
from other parts of a program.
There are two types of functions:
Built-in (Library) functions: These functions are part of the compiler package.
These are parts of standard library made available by the compiler. e.g. sqrt( ), pow( ),
clrscr( ), getch( ), getche( ) etc.

ASHISH KUMAR :: 9990781319 :: 30


User-defined functions: These functions are created by the programmer. These
functions are created as per the requirements of the program.

In C++, you must declare every identifier before it can be used. In case of functions, a function
declaration must be preceded any physical function call.
The declaration tells the compiler that at some later point we plan to present a function.
Syntax: data - type function - name (parameter - list);
Example: float volume(int a, float b, float c); or float volume(int, float, float);
In function declaration, variable names are optional.
If the data-type of the function is omitted is assumed to be returning int values.

A function definition consists of two parts: the function heading and the function body.
data - type function - name(parameter - list) int sum(int a, int b)
{ {
----------------- int c;
Syntax: Example:
body of function; c a b;
----------------- return c;
} }

The return statement is useful in two ways:


An immediate exit from the function is caused as soon as return statement is
encountered and control passes back to the main( );
It is used to return a value to the calling code.
Even through it is not necessary to have a return statement in a function, most functions rely
on the return statement to stop execution either because a value must be returned or to make
a function code simpler and more efficient.
A function may contain several return statements. However, only one of them gets executed
because the execution of the function is terminated as soon as a return statement is
encountered.

It is used as the return type for the functions that do not return a value.

void message( )
{
VOID function with NO ARGUMENTS:
cout " Hello!" ;
}
void average(int a, int b)
{
float av;
VOID function with ARGUMENTS:
av (a b)/2;
cout " Average is " av;
}
ASHISH KUMAR :: 9990781319 :: 31
char grade( )
{ char g;
if(p 60) g ' A' ;
NON-VOID function with NO ARGUMENTS:
else g ' B' ;
return g;
}
float average(int a, int b)
{
float av;
NON-VOID function with ARGUMENTS:
av (a b)/2;
return av;
}

A function can be invoked in two manners:

CALL BY VALUE CALL BY REFERENCE


The call by value method copies the values of In call by reference method the called
factual parameters (parameters in function function does not create its own copy of
call) into the formal parameter (parameters original values, rather its refers to original
in function definition), that is the function values only by different names i.e. the
created its own copy of argument values and references. Thus, the called functions works
then use them. with the original data and any change in the
Example: To test your grammar, your values get reflected to the data.
English teacher writes grammatically Example: If your English teacher gives you
incorrect passage on her sheet and gives it to the original sheet and allows you to work
you for corrections. So you copy down the upon the same sheet. Then, whatever
given passage on your own sheet and make corrections you make, will be there to the
corrections there. original. Thus, in call by reference method,
Here, your teacher passes the sheet having the changes are reflected back to the original
grammatical errors (actual parameter) to values.
you, and you copy the passage on your sheet
(formal parameter). Whatever changes takes
place are not reflected back to the original.

P1. WAP to swap two values by using call by value.


P2. WAP to swap two values by using call by reference.
P3. WAP to print largest element of an array.
P4. WAP to check whether a given character is contained in a string or not and find its
position.
P5. WAP that invokes a function calc( ) which takes two integers and an
operator(arithmetic) and prints the corresponding result.
P6. WAP to determine statistics of some text in terms of the line-count, word-count,
character-count. Use a function Text-Stat( ) to do the same. This function receives four
parameters: text, lc, wc, cc where last there parameters of integers type and are passed
by reference

ASHISH KUMAR :: 9990781319 :: 32


P7. Write a function to take an int argument and return 0 if the given no. is prime
otherwise retrun 1 .
Complete Exercise 8, 9, 10, 11, 12, 13, 14 by using functions.

The region of program code where it is legal to access an identifier is known as scope.
There are four kinds of scopes in C++:
Local Scope: A name declared in a block is local to that block and can be used only in it
and the other blocks contained under it
Global / File Scope: A name declared outside all blocks and functions has file scope i.e.
it can be used in all the blocks and functions written inside the file in which name
declaration appears.
Function Scope: The variables declared in the outermost block of a function have
function scope, i.e. they can be accessed only in the function that declares them.
Class Scope: Discuss Later
Example of Scope

# include.....
# include.....
int x, y;
FILE SCOPE
char ch;
void main( )
{
int a, b; FUNCTION
float amt; SCOPE
void check(int);
----------------
{
char grade; LOCAL
------------ SCOPE
}
}
void check(int i)
{ FUNCTION
long temp; SCOPE
}

If a variable declaration appears outside all the functions, it is said to be global variable. A
global variable is available to all the functions and blocks defined in a file.
A global variable comes into existence when the program execution starts and is destroyed
when the program terminates. Global variables hold their values throughout the program
execution. The scope of global variables is file scope.

ASHISH KUMAR :: 9990781319 :: 33


The local variables are the ones that are defined within a function. A local variable comes into
existence when the function is entered and is destroyed upon exit.

When a function declares a local identifier with the same name as global identifier, the local
identifier takes precedence within the function.
# include.....
int a 20;
main( )
Example: { Output: 50
int a 50;
cout a;
}
To unhide global variables scope resolution operator (::) can be used.
# include.....
int a 20;
main( )
Example: { Output: 20 50
int a 50;
cout :: a "\t" a;
}

The rules that determine where in the program an identifier may be accessed, given the point
where that identifier declared.
These rules are: (not complete rules)
A function name has global scope. Function definitions cannot be nested within
function definitions.
The scope of formal parameter is identical to the scope of a local variable declared in
the outermost block of the function body.
The scope of global variable or constants extends from its declaration to the end of the
file.
The scope of local variable or constants extends from its declaration to the end of the
block in which it is declared.
The scope of an identifier does not include any nested block, that contains a locally
declared identifier with the same name (name precedence).

The period of time during program execution when an identifier has memory allocated to it.
Lifetime of Global Variables: During Program Run
Lifetime of Local Variables: During Function or Block Run

The storage class of variable and function determines which part of the program can access it
and how long it stays in existence.
ASHISH KUMAR :: 9990781319 :: 34
C++ provides four storage class specifiers: auto, register, static, extern
Syntax: storage - specifier data type variable;

auto register
The storage specifier auto refers to the register variables provide fast access as they
automatic variables. are stored inside the CPU registers rather
By default, all variables are automatic. than in memory. So the time required to
Not applied for global variables. read from memory is saved.
Scope Function scope A register variable has all the
Lifetime Between function creation and characteristics to the auto variable.
destruction. Scope Function scope
Lifetime Between function creation and
destruction.
Extern
C++ allows you to split large programs into different files. A file can have some of the
functions while other file can have rest of the functions. Then these files can be separately
compiled and then later linked for the program execution.
In such files, if you have declared a global variable in a file, C++ does not allow you to
declare it again in some other file. But, what if that other file is using the global variable
that is defined outside the file. The extern specifier here comes to rescue.
The extern specifier tells the compiler that the variable types and names that follow it have
been declared elsewhere, so that fresh memory is not allocated to these variables.
The extern specifier is only for global variables.
Scope file scope (they are accessible in the files where their declaration appears)
Lifetime Life of a program

static
The static variables are permanent within their own function or file.
Static Local Variables
When static modifier applies to a local variable, it is initialized only when the very first call to
the function that defines it occurs. It is not destroyed when the function terminates, rather, it
holds its value even after functions termination but it can only be accessed within its own
function.
Scope function slope
Lifetime during program run
Static Global Variables
By putting static keyword before a global variable declaration in a file makes sure that the
only functions in the same file can access it and not any other function residing in any other
file.
Scope file scope
Lifetime during program run

Static function Extern function


The static function can be accessed only in The keyword extern before a function
the file that declares it. This means, this prototype indicates that this function has
function is not known outside its own file. been defined in another file.
Another file can use the same name for a
different function.

ASHISH KUMAR :: 9990781319 :: 35


Note: When a function call is made in a particular file in a program, C++ compiler first checks
the function prototype. If the function prototype in that file indicates that the function is
static, the compiler will look only in the file for the function. Otherwise, C++ looks for the
function in all the files of the program. If it finds two definitions with same name, an error
message is displayed. If the function is formed in the program it is executed otherwise library
files are scanned for the function.

P1. Write a function to calculate the factorial value of any integer entered through the
keyboard.
P2. Write a function power(a, b), to calculate the value of a raised to b.
P3. Write a general purpose function to convert any given year into its roman equivalent.
Decimal Roman Decimal Roman
1 I 100 C
5 V 500 D
10 X 1000 M
50 L
P4. A positive integer entered through the keyboard. Write a function to obtain its prime
factors.
P5. According to Gregorian Calendar, it was Monday on the date 01/01/1900. If any year is
input through the keyboard, write a program to find out what is the day on 1st January
of this year.
P6. WAP to fill the entire screen with a smiling face. The smiling face has an ASCII value
1.
P7. WAP to generate all combinations of 1, 2 and 3 using for loop.

P8. Write a menu driven program which has following options:

a. Factorial

b. Prime

c. Odd / Even

d. Exit

P9. Develop a program that receives the month and year from keyboard as integers and
prints the calendar.

ASHISH KUMAR :: 9990781319 :: 36


The decimal system is composed of 10 symbols. These 10 symbols are:
0 1 2 3 4 5 6 7 8 9
The lowest digit is 0 and the highest is 9. The decimal system, also called the base-10 system
because it has 10 digits.
When we write an integer in a C++ program the number is assumed to be in the decimal
number system.
The decimal system is a positional-value system in which the value of a digit depends on its
position.
Decimal Digit 9374 .712 9 10 3 3 10 2 7 101 4 10 0 7 10 1 1 10 2 2 10 3
Thousands Hundreds Tens Ones

The binary system is the native language of a computer.


In a binary system there are only two symbols: 0 and 1. Even so this base-2 system can be
used to represent any quantity that can be represented in decimal or any other number
system. The binary number system is also a positional value system.
Binary Digit 1010 .010 1 23 0 22 1 21 0 20 0 21 1 22 0 23
Eights Fours Twos Ones

The octal number system is very important in digital computer work. The octal number
system has a base of eight, meaning that it has eight unique symbols: 0 1 2 3 4 5 6 7
The octal systems also a positional value system.
Octal digit 472 .273 4 82 7 81 2 80 2 8 1 7 8 2 3 8 3
Sixty Fours Eights Ones

The hexadecimal system use base-16. Thus it has 16 possible digits symbols. These symbols
are: 0 1 2 3 4 5 6 7 8 9 a b c d e f
The hexadecimal system is also a positional value system.
Hexadecimal Digit 3DA. A3 3 16 2 D 161 A 16 0 A 16 1 3 16 2
Two hundred Sixteens Ones
& fifty sixes

ASHISH KUMAR :: 9990781319 :: 37


HEXA HEXA
DECIMAL BINARY OCTAL DECIMAL BINARY OCTAL
DECIMAL DECIMAL
0 0 0 0 26 11010 32 1A
1 1 1 1 27 11011 33 1B
2 10 2 2 28 11100 34 1C
3 11 3 3 29 11101 35 1D
4 100 4 4 30 11110 36 1E
5 101 5 5 31 11111 37 1F
6 110 6 6 32 100000 40 20
7 111 7 7 33 100001 41 21
8 1000 10 8 34 100010 42 22
9 1001 11 9 35 100011 43 23
10 1010 12 A 36 100100 44 24
11 1011 13 B 37 100101 45 25
12 1100 14 C 38 100110 46 26
13 1101 15 D 39 100111 47 27
14 1110 16 E 40 101000 50 28
15 1111 17 F 41 101001 51 29
16 10000 20 10 42 101010 52 2A
17 10001 21 11 43 101011 53 2B
18 10010 22 12 44 101100 54 2C
19 10011 23 13 45 101101 55 2D
20 10100 24 14 46 101110 56 2E
21 10101 25 15 47 101111 57 2F
22 10110 26 16 48 110000 60 30
23 10111 27 17 49 110001 61 31
24 11000 30 18 50 110010 62 32
25 11001 31 19 51 110011 63 33

ASHISH KUMAR :: 9990781319 :: 38

Anda mungkin juga menyukai