C++ Handbook for
Class IX
Computer Science
Programming is like playing a game. The coach can assist
the players by explain...
Acknowledgement
I should thank my family members for adjusting with my time schedules and giving inputs and
comments where...
Table Of Contents
Chapter – 1................................................................................................
Chapter – 1
Introduction to Programming
•

Program – Set of instructions / command given to the
computer to complete a tas...
5. Running / Execution – The instructions written are
carried out in the CPU.
6. Debugging / Testing – The process of remo...
Components / Elements of a
programming language
1. Constants – Entities that do not change their values
during program exe...
Chapter – 2
First Program in C++
// my first program in C++
#include <iostream.h>
void main()
{
cout << "Hello World!";
}
...
•

•
•

The syntax of main function is given below.
void main()
{
…
…
}
Inside the main function, other statements can be
...
Integrated Development
Environment
•
•

An integrated development environment (IDE) is
a software application that provide...
Notes

10
Chapter – 3
C++ Variables and Constants
Before we learn C++ variables and constants, we should know
these terms – integer,...
String Constants Examples
String or character array constants should be always
enclosed in double quotes.
•
•
•
•

“123”
“...
Variables
•

Variables are actually named memory locations which
can store any value.

•

It is the programmer who assigns...
The type (i.e., datatype) of a variable will be covered in
next chapter.

Rules for naming the variables
•
•

A variable n...
•

The C++ language is a "case sensitive" language. It
means that a variable written in capital letters is
not equivalent ...
d.
e.
f.
g.

“1166”
“123.45”
‘3’
“*”

2. Indicate whether the following variable names are
valid or not
a. fgh
b. Main
c. ...
Notes

CS WORKBOOK IX
17
Priya Kumaraswami
Chapter – 4
C++ Datatypes
•

Datatypes are available in a programming language to
represent different forms of data and to...
•

1
1
With 2 bits, we can represent 4 numbers (22)
Bit Combination Decimal Value
00
0
01
1
10
2
11
3

•

With 3 bits, we ...
called ASCII code. The ASCII table for the alphabet and
digits are given below.
Char
ASCII code
A to Z
65 to 90
a to z
97 ...
•

Any variable should be declared before we use it.

•

Associating a variable name with a datatype is called
declaration...
previous statement

Variable Initialization
•

Giving an appropriate value for a variable is known as
initialization

•

E...
2. Convert the following decimal numbers to binary
a. 1024
b. 255
c. 1189
d. 52
3. Draw the table to show the bit combinat...
Notes

24
Chapter – 5
Operators and Expressions
Two Categories
•
•

Binary operators – operators which take 2 operands.
Examples +, ...
Assignment Operator =
Assignment operator is used to assign a value to a
variable
a = 10;
b = b + 20;
c = b;
There are sho...
Expressions
C++ Expressions are the result of combining constants,
variables and operators. Expressions can be arithmetic ...
Expressions with char variable
When char is used in an expression, its ASCII number
equivalent is taken.
Example
char ch =...
b.
c.
d.
3. Find
a.

A is greater than 0 and less than 100
Grade is A or B
Increment the value of X by 20
the output for t...
Notes

30
Chapter – 6
Input and Output
The output operation is already illustrated in Chapter 2
– “First Program in C++”. A recap of...
cout << "Hello, I am " << age << " years old and my zipcode is "
<< zipcode;

If we assume the age variable to contain the...
Input using cin
cin is used along with the extraction operator, which is
written as >> (two "greater than" signs).
int age...
cout << "The value you entered is " << i;
cout << " and its double is " << i*2;
}
In the above program, an int variable is...
Notes

CS WORKBOOK IX
35
Priya Kumaraswami
Chapter – 7
Conditions (if and switch)
Null Statement
•
•
•
•

Statements are the instructions given to the computer
to pe...
Operators used in conditions
•

>, <, >=, <=, ==, !=, &&, ||, !

•

Examples
grade == ‘A’
a > b
!x
x >=2 && x <=10
grade =...
•
•

Also called conditional or decision statement
Syntax of if statement
if ( condition )
statement ;

•
•
•

•

Statemen...
•

If x value is 95 (anything other than 100), 95 will be
printed. This is because the if statement includes
only one stat...
cout << "x is negative";
else
cout << "x is 0";

The above syntax can be understood as… if condition1 is
satisfied, do som...
Conditional structure: Nested if
•

In a nested if construct, you can have an if...else
if...else construct inside another...
Dangling else problem
if ( ch >= ‘A’)
if(ch <= ‘Z’)
upcase = upcase + 1;
else

•
•

Which if the else belongs to, in the a...
int a = 10;

int a = 10;

if( a >= 0)

if( a >= 0)

cout << a;
else if ( a >=

cout << a;
5)

if ( a >=

cout << a + 5;

5...
•

switch evaluates expression and checks if it is
equivalent to constant1, if it is, it executes group
of statements unde...
default:
cout << “Algol”;
break;
}
In the above program, if input is 1 for n, C++ will be
printed.
If input is 2 for n, Ja...
•

A variable can be used only within the block it is
declared.

•

Example1 - the scope of j is within that if block
only...
cout << “Fail L” ;
}
}
7.2 Program to find the grade
#include “iostream.h”
void main()
{
int x;
cout << “Enter the mark”;
...
7.3 Program to check whether a number is divisible by 5
#include <iostream.h>
void main()
{
int x;
cout << “Enter a number...
cout << “Enter choice:(1 for area, 2 for
circumference)” ;
cin >> n ;
cout << “Enter radius”;
cin >> r;
float res;
switch(...
case 2:
res = 3.14 * 2 * r;
cout << “The circumference is “ << res;
case 1:
res = 3.14 * r * r;
cout << “The area is “ << ...
Exercise
1. Find the output for the following code snippets
a. int a , b;
cin >> a >> b;
if( a % b == 0)
cout << a / b;
co...
cout << “converting from giga to bytes”;
cout << val * 1024 * 1024 * 1024;
break;
default:
cout << “invalid option”;
break...
}
else if( m1 >= 40)
{
if( m2 >= 80)
cout << “Good”;
else if (m2 >= 40)
cout << “Fair”;
else
cout << “improve”;
}
else
{
i...
g. To accept any value from 1 to 7 and display the
weekdays corresponding to the number entered. (use
switch case)
h. To f...
Chapter – 8
Loops
A loop is a piece of code that repeats itself until a
condition is satisfied. A loop alters the flow of ...
The statement can be simple or compound.

•

Example 1

In this code, i is the index variable. Its initial
value is 1. Til...
This code loops 10 to 1 with a step of -2. But the c
variable is not printed. ‘*’ is printed 5 times.
•

Example 4
for (in...
This means the null statement gets executed repeatedly.
cout << a; is independent.

Multiple initialization and update in ...
•

In this code, a is the index variable. Its initial
value is 0. Till a is less than or equal to 10, the
statements will ...
There is no update statement here. So this also becomes
infinite loop as it does not reach the final value.

Multiple init...
Nested Loops
•
•

A loop may contain one or more loops inside its body.
It is called Nested Loop.
Example 1
for(int i= 1; ...
for(int i= 1; i<=2; i++)
{
for(int j= 3; j<=4; j++)
{
for(int k= 5; k<=6; k++)
{
cout << i * j * k<< endl;
}
}
}
Here, the...
i = 1

j = 3
j = 4
k = 5
k = 6

i = 2

j = 3
j = 4
k = 5
k = 6

•
•

3
4
5
6
6
8
10
12

In the syllabus, we learn to use n...
function, the control will be given to the OS (which is the
calling code) and the program will stop.
Example
#include <ios...
while (i <= 10)
{
cout << i << “table starts” ;
int j = 1;
while (j <= 20)
{
cout<<i << “ x “<< j << “ = “<< i * j<<endl;
...
}

8.5 Program to print the pattern.
#include <iostream.h>
void main()
{
for (char i = ‘A’ ; i <= ‘E’; i++)
{
for (char j ...
8.7 Program to print the pattern.

*******
*****

#include <iostream.h>
void main()
{

***

}
8.8 Program to print the pat...
}
8.9 Program to print the pattern.

1
121

#include <iostream.h>
void main()
{

12321
1234321

}
8.10 Program to print th...
}
8.11 Program to print the pattern.
2468642

#include <iostream.h>
void main()
{

24642
242

}
8.12 Program to print the ...
}
8.13 Program to print the pattern.

$$$$$
$&&&$

#include <iostream.h>
void main()
{

}

Exercise
1. Find the outputs
70...
a. int a = 33, b = 44;
for(int i = 1; i < 3; i++)
{
cout << a + 2 << b++ << endl;
cout << ++a << b – 2<< endl;
}
b. long n...
72
Notes

CS WORKBOOK IX
73
Priya Kumaraswami
Chapter – 9
Number Arrays
•
•
•

An array represents continuous memory locations having
a name which can store data of a s...
Declaration of an array
•
•
•
•
•
•
•
•
•

datatype arrayname [size];
Example
int a [6];
The datatype indicates the dataty...
Calculation of bytes
The memory occupied by an array is calculated as
size of the element x number of elements
For example...
Generally we avoid combining input and output of array
elements in a single loop because it mixes up the display
on the sc...
}
9.2 Program to sum up all the elements.
#include <iostream.h>
void main()
{

78
}
9.3 Program to find the max and min in the given array.
#include <iostream.h>
void main()
{

}
9.4 Program to replace an...
}
9.5 Program to reverse the array.
#include <iostream.h>
void main()
{

80
}
9.6 Program to swap the first half with the second half.
#include <iostream.h>
void main()
{

}
9.7 Program to swap the ...
}
9.7 Program to search for a given element using flag.
#include <iostream.h>
void main()
{

82
}

Exercise
1. Fill in the blanks
The following program searches for a given element using
count. Some portions of the pro...
c. A float array of size 50
3. Write Programs
a. To count the number of elements divisible by 4 in
the given array of size...
Chapter – 10
Char Arrays
Char arrays are similar to number arrays. The storage in
memory is similar to that of number arra...
•
•
•

Example
char A [8];
We give the arrayname and it has to follow the rules
of naming the variables.
An array has size...
where puts is a function to display a string on the
screen. This will display the string till the null
character.
To use g...
•
•
•
•

toupper()
isalpha()
isdigit()
isalnum()

to
to
to
to

convert to uppercase
check if the char is alphabet
check if...
char arr[40];
// declare char array of required size
gets (arr);
// take input for char array
int len = strlen(arr);
// fi...
char arr [51];
gets(arr);
int len = strlen(arr);
for(i = 0; i < len; i= i+1)
{
if( isupper(arr[i]))
arr[i] = tolower(arr[i...
10.4

Program to take a string as input, reverse it and
check if it’s a palindrome

CS WORKBOOK IX
91
Priya Kumaraswami
10.5

Program to take a string as input and search for a char

Exercise
1. Find the output
92
a. char ch = ‘&’;
char st[20]="BpEaCeFAvourEr";
for(i=0;st[i] != ‘0’;i++)
{
if(st[i]>='D' && st[i]<='J')
st[i]=tolower(st[...
Chapter – 11
Functions
•
•
•
•
•

Large programs are difficult to manage and maintain.
A large program is broken down into...
int calculateresult (int p, int q)
{
int r;
r = p + q + (p * q);
return r;
}

 Function Definition

Working of a function...
ReturnDatatype functionname ( datatype arg1, datatype arg2,
……) ;
ReturnDatatype denotes the datatype of the return value
...
•

The function prototype and the function definition
must agree EXACTLY on the return type, function name
and argument / ...
Example
1. float func ( int a, int b )
{
float k = 0.5 * a * b;
return k;
}
2. int demo ( float x)
{
int n = x / 2;
return...
}

Function call Syntax
if the ReturnDatatype is not void
ReturnDatatype variable = Functionname (arg1, arg2 …);
if the Re...
Function Scope
•

Variables declared inside a function are available to
that function only

Example

Sample Programs
11.1 ...
long power (int a, int b)
//Function Definition
{
long pow = 1;
for (int i = 1; i <= b, i++)
pow = pow * a;
return pow;
}
...
11.4 Program to calculate volume and surface area of a
sphere using 2 separate functions (volume = 4/3 pi r3 ,
surface are...
11.6 Program to check whether a given number is prime using
a function

CS WORKBOOK IX
103
Priya Kumaraswami
11.7 Program to find the max in an int array of size 20
using a function

Exercise
1. Find the output
a. #include <iostrea...
m = m + p;
p = calc (n, m);
n = n + p;
cout << m << “ “ << n << “ “ << p;
}
int calc ( int x, int y)
{
x = x + 10;
y = y –...
2. Rewrite the following program after correcting
syntactical errors
#include <iostream.h>
void demo ( int a ; int b)
void...
Notes

CS WORKBOOK IX
107
Priya Kumaraswami
Worksheet - 1
1.

(C++ Datatypes, Constants, Variables, Operators, Input and Output)
Match the following
int a;
a. An inte...
a.

b.
c.
d.
e.

a 2 + 2ab
n−b
g. k =
1
h. z = ab + 3 (x – y)2

a2b
2ab
pnr/100
a2 + 2ab + b2

f. sum =

n(n + 1)
2

12.

...
17.
#include <iostream.h>

#include <iostream.h>

void main

void main()

{

{
int k;

int s = 75;

k = k + 10;

int ____ ...
Worksheet – 2 (if..else)
1. Write ‘if’ statements for the following
a. To check whether the value of int variable a is equ...
cout << “Am I right?”;
cout << “No??”;

e.
if ( 0 )
cout << “Third Time Tricky”;
cout << “Am I right?”;

f.
if ( !0 )
cout...
5.

30001 onwards
15%
22001 – 30000
10%
12001 – 22000
7%
5001 – 12000
3%
0 – 5000
0%
Illustrate Nested If with examples

W...
114
CS WORKBOOK IX
115
Priya Kumaraswami
116
CS WORKBOOK IX
117
Priya Kumaraswami
int b;
cin >> b;
switch (b)
{
case ‘10’;
cout <<

“Number of bats = 10” ;

break;
case ‘10’:
cout << “Number of bats = 15”...
6. Find the output of the following if a gets values 0, 1 and 2 in

7.

three consecutive runs.
int a; cin >> a;
switch (a...
Worksheet – 4 (Loops)
1. Write a program to print tables of 3,6,9,….n upto x15
2.

( multiplied by 15)
Write Programs to p...
if(c == 4) break;
else cout << c;

7.

8.

}
cout << c;
Convert the following nested for loops to nested while loops and
f...
10. Which out of the following will execute 5 times?
a. for ( int j = 0; j <= 5; j++)
b. for ( int j = 1; j < 5; j++)
c. f...
Worksheet – 5
Function related Programs
1. Write a C++ program with a function to find the volume of a cone.
The function ...
{

}

switch (m)
{
case
case
case
case
}

0:
4: cout<<AY[m]*5;
2:
1: cout<<AY[m]<<endl;

}

8. void main()
{

char Text[ ]...
digit=n-dgg;
cout<<digit+digit<<endl;
sum=sum+digit*digit*digit;
n=n/10;
}
cout<<digit<<endl<<sum;
}
void main( )
{
int nu...
Upcoming SlideShare
Loading in …5
×

C++ publish copy

1,660 views

Published on

C++ Basics - Study Material for IX standard

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

C++ publish copy

  1. 1. C++ Handbook for Class IX Computer Science Programming is like playing a game. The coach can assist the players by explaining the rules and regulations of the game. But it is when the players practice on the field, they get the expertise and nuances of the game. Same way, the teacher explains the syntax and semantics of the programming language in detail. It is when the students explore and practice programs on the computer; they get the grip of the language. Programming is purely logical and application oriented. Learning the basics of C++ in IX standard would be helpful if the student wishes to take up Computer Science in the Senior Secondary Level. Priya Kumaraswami 10/27/2013
  2. 2. Acknowledgement I should thank my family members for adjusting with my time schedules and giving inputs and comments wherever required. Next, my thanks are due to my colleagues and friends who provided constant support. My sincere thanks to all my students, their queries and curiosity have helped me compile the book in a student friendly manner. Special thanks to Gautham, Nishchay and Mohith for reviewing the book and providing valuable comments. Thanks to the Almighty for everything. Priya Kumaraswami 2
  3. 3. Table Of Contents Chapter – 1...........................................................................................................................4 Introduction to Programming...............................................................................................4 Chapter – 2...........................................................................................................................7 First Program in C++...........................................................................................................7 Chapter – 3.........................................................................................................................11 C++ Variables and Constants.............................................................................................11 Chapter – 4.........................................................................................................................18 C++ Datatypes...................................................................................................................18 Chapter – 5.........................................................................................................................25 Operators and Expressions.................................................................................................25 Chapter – 6.........................................................................................................................31 Input and Output................................................................................................................31 Chapter – 7........................................................................................................................36 Conditions (if and switch)..................................................................................................36 Chapter – 8.........................................................................................................................55 Loops..................................................................................................................................55 Chapter – 9.........................................................................................................................74 Number Arrays...................................................................................................................74 Chapter – 10.......................................................................................................................85 Char Arrays........................................................................................................................85 Chapter – 11.......................................................................................................................94 Functions............................................................................................................................94 Worksheet - 1..................................................................................................................108 Worksheet – 2 (if..else)....................................................................................................111 Worksheet – 3 (switch).....................................................................................................113 Worksheet – 4 (Loops).....................................................................................................120 Worksheet – 5 ..................................................................................................................123 CS WORKBOOK IX 3 Priya Kumaraswami
  4. 4. Chapter – 1 Introduction to Programming • Program – Set of instructions / command given to the computer to complete a task • Programming – The process of writing the instructions / program using a computer language to complete the given task. Stages in Program Development 1. Analysis – Deciding the inputs required, features offered and presentation of the outputs 2. Design – Algorithm or Flowchart can be used to design the program. 1. The given task / problem is broken down into simple steps. These steps together make an algorithm. 2. If the steps are represented diagrammatically using special symbols, it is called Flowchart. 3. The steps to arrive at the specified output from the given inputs are identified. 3. Coding – The simple steps are translated into high level language instructions. 1. For this, the rules of the language should be learnt (syntax and semantics). 4. Compilation – The high level language instructions are converted to machine language instructions. – At this point, the syntax & semantic errors in the program can be removed. – Syntax Error: error due to missing colon, semicolon, parenthesis, etc. – Semantic Error: it is a logical error. It is due to wrong logical statements. (statements that do not give proper meaning.) 4
  5. 5. 5. Running / Execution – The instructions written are carried out in the CPU. 6. Debugging / Testing – The process of removing all the logical errors in the program by checking all the conditions that the program needs to satisfy. Types / Categories of Programming techniques 1. Procedural Programming 2. Object Oriented Programming (OOP) Comparison • In Procedural Programming, importance is given to the sequence of things that needs to be done and in OOP, importance is given to the data. • In Procedural Programming, larger programs are divided into functions / steps and in OOP, larger programs are divided into objects. • In Procedural Programming, data has no security, anyone can modify it. In OOP, mostly the data is private and only functions / steps inside the object can modify the data. Why should we learn a programming language? • To write instructions / commands to the computer to perform a task All the programs and processes running inside the computer are written in some programming language. CS WORKBOOK IX 5 Priya Kumaraswami
  6. 6. Components / Elements of a programming language 1. Constants – Entities that do not change their values during program execution. Example - 4 remains 4 throughout the program. “Hello” remains “Hello” throughout the program 2. Variables – Entities that change their values during program execution. These are actually memory locations which can hold a value. 3. Operators 1. Arithmetic – Operations like +, -, *, /, ^ 2. Relational – Compares two values (<, >, <=, >=, ! =, ==) 3. Logical – AND, OR, NOT, used in conditions 4. Expressions – Built with constants, variables and operators. 5. Conditions – The statements that alter the flow of the program based on their truth values (true / false). 6. Loops – A piece of code that repeats itself until a condition is satisfied. 7. Arrays – Continuous memory locations which store same type of data. Used to store bulk data. Single data is stored in variables. 8. Functions – Portion of code within a large program that performs a specific task and which can be called as required 6
  7. 7. Chapter – 2 First Program in C++ // my first program in C++ #include <iostream.h> void main() { cout << "Hello World!"; } Explanation // my first program in C++ • This is a comment statement which is used for giving remarks in between the program. • Comments are not compiled / executed. • This is a single line comment. • For multi line comments, /* ……………… */ should be used. • Example /* This is a multi line comment spanning three lines to demonstrate the syntax of it */ #include <iostream.h> • • • #include <iostream.h> is written in a program because it is required to do input and output operations. The functions for input and output operations are available in iostream.h. iostream.h is a standard library. void main() • • • Every program should have a main() function. A function will start with { and end with }. All the statements inside the function should end with a semicolon. CS WORKBOOK IX 7 Priya Kumaraswami
  8. 8. • • • The syntax of main function is given below. void main() { … … } Inside the main function, other statements can be added. We’ll learn how to declare, define and use other functions in Chapter 11. cout << "Hello World!"; • • • • • • • • • • • cout statement is used for printing on the screen. The syntax of cout statement is cout << “Message”; We can combine many messages in one cout statement using cascading technique as shown below (using multiple <<). cout << “Message 1” << “Message 2”; If the Message 2 has to be printed in next line, endl keyword should be added in between as follows. cout << “Message 1” << endl << “Message 2”; endl denotes end of line. One more way to print the Message 2 in the next line is using ‘n’ character. ‘n’ is called a newline character. cout << “Message 1” << ‘n’ << “Message 2”; cout << “Message 1” << “n” << “Message 2”; Compilation • • After writing the code, the code has to be compiled. Compilation is the process of converting high level language instructions to machine language instructions. Execution • 8 Execution is the process of running the instructions one by one in the CPU and getting the results.
  9. 9. Integrated Development Environment • • An integrated development environment (IDE) is a software application that provides facilities for program development. An IDE normally consists of: o a source code editor where code can be written o a compiler o a provision to run the program o a provision to debug the program Exercise 1. Fill in the blanks #include ____________ void main _____ { _______ “ Hello” ; ________ “ How are you?”; /* This program prints Hello in the first line and How are you in the second line */ } 2. Write a program to print 3 lines of 10 stars. 3. Write a program to print your name, class, section and age. CS WORKBOOK IX 9 Priya Kumaraswami
  10. 10. Notes 10
  11. 11. Chapter – 3 C++ Variables and Constants Before we learn C++ variables and constants, we should know these terms – integer, floating point, character and string. Integer represents any whole number, positive or negative. The number should not contain decimal point or commas. They can be used in arithmetic calculations. Examples – 14, -19, 34, -504 Floating point represent any number (positive or negative) containing decimal point. No commas. They can be used in arithmetic calculations. Examples – 14.025, -13.65, 506.505, -990.0, 0.65 Character represents any character that can be typed through the keyboard. They cannot be used in arithmetic calculations. Examples – A, a, T, x, 9, 3, %, &, @, $ String (char array) represents a sequence of characters that can be typed through the keyboard. They cannot be used in arithmetic calculations. Examples – Year2012, Gone with the wind, email@mailbox, **(*)** Constants • Constants are the entities that do not change their values during program execution. • There are four types – string, character, floating point and integer constants. CS WORKBOOK IX 11 Priya Kumaraswami
  12. 12. String Constants Examples String or character array constants should be always enclosed in double quotes. • • • • “123” “Abc” “This is some text.” “so many $” (character (character (character (character array array array array ) ) ) ) char Constants Examples Character constants should be always enclosed in single quotes. • • ‘A’ ‘z’ (character) (character) integer constants Examples • • 123 34 (integer) (integer) floating point constants Examples • • 34.78 5666.778 (floating point) (floating point) A sample program using constants 12
  13. 13. Variables • Variables are actually named memory locations which can store any value. • It is the programmer who assigns the name for a memory location. • Variables are the entities that can change their values during program execution. Example A = 10;  A contains 10 now A = A + 1;  A contains 11 now A = 30;  A contains 30 now • There can be integer variables which can store integer values, floating point variables to store floating point values, character variables to store any character or string variables to store a set of characters. CS WORKBOOK IX 13 Priya Kumaraswami
  14. 14. The type (i.e., datatype) of a variable will be covered in next chapter. Rules for naming the variables • • A variable name should not contain space or any other special character. • 14 All variable names should begin with a letter and further it can have digits or underscores or letters. Another rule that you have to consider when naming the variables is that they cannot match any keyword of the C++ language. The standard reserved keywords in C++ are:
  15. 15. • The C++ language is a "case sensitive" language. It means that a variable written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different variables. • Generally, it is considered a good practice to name variables according to their purpose/functionality. Exercise 1. Identify the type of constants a. 123.45 b. 145.0 c. 1166 CS WORKBOOK IX 15 Priya Kumaraswami
  16. 16. d. e. f. g. “1166” “123.45” ‘3’ “*” 2. Indicate whether the following variable names are valid or not a. fgh b. Main c. 5go d. var name e. var_name f. var*name 3. Identify the errors a. ‘abc’ b. 14. c. .45 d. 50,000 16
  17. 17. Notes CS WORKBOOK IX 17 Priya Kumaraswami
  18. 18. Chapter – 4 C++ Datatypes • Datatypes are available in a programming language to represent different forms of data and to determine the bytes used by each form of data. • Datatype technically indicates the amount of memory used in the form of bytes. • • • • • So we need to understand bits and bytes. A bit in memory can store either 1 or 0. 8 bits make a byte. A byte can be used to store a sequence of 0’s and 1’s. Example – 10110011 or 11110000 Decimal to Binary Conversion Calculation of the range • 18 With 1 bit, we can represent 2 numbers (21) Bit Combination Decimal Value 0 0
  19. 19. • 1 1 With 2 bits, we can represent 4 numbers (22) Bit Combination Decimal Value 00 0 01 1 10 2 11 3 • With 3 bits, we can represent 8 numbers (23) Bit Combination Decimal Value 000 0 001 1 010 2 011 3 100 4 101 5 110 6 111 7 • With 8 bits, we can represent 256 numbers (28). If it has to cover both +ve and –ve numbers, that 256 has to be split as -128 to + 127 including 0. • With 16 bits, we can represent 65536 numbers (216). If it has to cover both +ve and –ve numbers, that 65536 has to be split as -32768 to + 32767 including 0. Fundamental Datatypes • There are five basic data types in C++ - int, char, float, double and void. • int datatype is used to represent an integer. • char datatype is used to represent a single character. char is internally stored as a number as the system can only understand numbers, that too binary numbers. So each character present in the keyboard has a number equivalent, CS WORKBOOK IX 19 Priya Kumaraswami
  20. 20. called ASCII code. The ASCII table for the alphabet and digits are given below. Char ASCII code A to Z 65 to 90 a to z 97 to 122 0 to 9 48 to 57 Please refer wikipedia for the complete ASCII table (for all characters in the keyboard). • float datatype is used to represent a floating point number. • double datatype is used to represent a larger floating point number. • void datatype is used in C++ functions covered in chapter 11. It means “nothing” stored. • There are other data types like long, short, enum, union etc out of which long is used more often. • long datatype is used to represent larger integers. • The following table gives the size in bytes and the range of numbers accommodated by each datatype. Datatype Size in bytes (Memory used) Range char 1 byte -128 to 127 int float double long 2 4 8 4 -32768 to 32767 Approx 7 digits Approx 15 digits -2147483648 to 2147483647 void None bytes bytes bytes bytes Variable Declaration 20 Example data that can be stored using the given datatype ‘a’, ‘A’, ‘$’, ‘1’, ‘0’, ‘%’ (Any single character on the keyboard) 12, 9489 12.43, 6789.566 56789.66666 45674, 998304
  21. 21. • Any variable should be declared before we use it. • Associating a variable name with a datatype is called declaration. int a; float mynumber; These are two valid declarations of variables. The first one declares a variable of type int with the name a. Now a can be used to store any integer value. It will occupy 2 bytes in memory. The second one declares a variable of type float with the name mynumber. Now mynumber can be used to store any floating point value. It will occupy 4 bytes in memory. Similarly, we can declare char, long, double variables. char ch; long num; double d; • (ch occupies 1 byte) (num occupies 4 bytes) (d occupies 8 bytes) If you are going to declare more than one variable of the same type, you can declare all of them in a single statement by separating their names with commas. For example: int a, b, c; This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as: int a; int b; int c; • Multiple declaration of a variable is an error. For example, int a; int a = 2; //error as a is already declared in the CS WORKBOOK IX 21 Priya Kumaraswami
  22. 22. previous statement Variable Initialization • Giving an appropriate value for a variable is known as initialization • Examples int a = 10; float b = 12.5; float c; c = 26.0; char ch1, ch2; ch1 = ‘q’; ch2 = ‘p’; long t = 40000; double d = 1189.345; int x = 9, y = 10; (Multiple initializations) A sample program using variables #include <iostream.h> void main () { int a, b; int result; a = 5; b = 2; a = a + 1; // 1 is added to a value and stored in // a again. a becomes 6 now. result = a - b; // result contains 4 now cout << result; // 4 is printed on screen } Exercise 1. Write correct declarations for the following a. A variable to store 13.5 b. A variable to store Hello c. A variable to store grade (A / B / C / D / E) d. A variable to store 10000 22
  23. 23. 2. Convert the following decimal numbers to binary a. 1024 b. 255 c. 1189 d. 52 3. Draw the table to show the bit combination and decimal value for 4 bits binary. 4. Identify the errors in the following a. int a = ‘a’; b. float x; y; z; c. int num = 45678; d. char ch = “abc”; e. char c = ‘abc’; f. int m$ = 10; g. long m = 90; n = 3400; CS WORKBOOK IX 23 Priya Kumaraswami
  24. 24. Notes 24
  25. 25. Chapter – 5 Operators and Expressions Two Categories • • Binary operators – operators which take 2 operands. Examples +, - , > , <, = Unary operators – operators which take 1 operand. Examples ++, --, ! Operations and the Operators Arithmetic Operators +, -, *, /, % Arithmetic operators are used to perform addition (+), subtraction (-), multiplication (*) and division (/). % is a modulo operator which gives the remainder after performing the division of 2 numbers. 10%3 will give 1. 14%2 will give 0. 27%7 will give 6. Logical Operators &&, ||, ! Logical operators are used in conditions to combine expressions. a > 10 && a < 100 b == 10 || b == 20 !(b == 10) Relational Operators >, <, >=, <=, !=, == Relational operators are used for comparisons. 10 > 2 will give true (1). 12 == 2 will give false (0). 6 <= 12 will give true (1). 7 != 7 will give false (0). CS WORKBOOK IX 25 Priya Kumaraswami
  26. 26. Assignment Operator = Assignment operator is used to assign a value to a variable a = 10; b = b + 20; c = b; There are shortcuts used in assignment. A = A + B; can be written as A += B; A = A * B; can be written as A *= B; (similarly for - , / and % operators) Increment Operator ++ Decrement Operator -• • These two operators increment or decrement the value of a variable by 1. There are 2 versions of them – post and pre Pre increment – First the increment happens and then the incremented value is used in the expression Example a = 10, b = 20 C = (++a) + (++b) = 11 + 21 = 32 Post increment – First the current value is used in the expression and then the values are incremented Example a = 10, b = 20 C = (a++) + (b++) = 10 + 20 = 30 then a becomes 11 and b becomes 21 Pre decrement – First the decrement happens and then the decremented value is used in the expression Example a = 10, b = 20 C = (--a) + (--b) = 9 + 19 = 28 Post decrement – First the current value is used in the expression and then the values are decremented Example a = 10, b = 20 C = (a--) + (b--) = 10 + 20 = 30 then a becomes 9 and b becomes 19 Sample Problem int a = int c = a = a + b = c cout << 26 20 , b = 40; a++ + ++b; b++; --a; a << b << c; 20 21 61 61 + + – 0 41 41 61 61 = 61 (a becomes 21) = 62 (b becomes 42) = 0 will be printed
  27. 27. Expressions C++ Expressions are the result of combining constants, variables and operators. Expressions can be arithmetic or logical. Arithmetic expressions use arithmetic operators and int/float constants and variables. Examples of arithmetic expression (a, b, c are integer variables) a = b + c; a = a + 20; b++; c = c * 13 % 5; Logical expressions use logical or relational operators with constants and variables. The result of a logical expression is always true (any non zero value, usually 1) or false. Examples of logical expression (a, b, c are integer variables) a > 10 && a < 90 a != b ((c%6 == 1) || (c%6 == 2)) !(a < 100) The evaluation of the expression generally follows order of precedence (similar to BODMAS rule) CS WORKBOOK IX 27 Priya Kumaraswami
  28. 28. Expressions with char variable When char is used in an expression, its ASCII number equivalent is taken. Example char ch = ‘a’; ch = ch + 5; cout << ch; will print ‘f’ on the screen. char c = ‘S’; c = c – 2; cout << c; will print ‘Q’ on the screen Exercise 1. Evaluate the following expressions a. cout << 10 + 5 * 3; b. int a = 10; a += 20; cout << a++; c. cout << (10 > 5 && 10 < 20); d. int z = !(10 < 50); cout << z; e. int f = 20 % 3 + 2; cout << f; 2. Write C++ expressions for the following a. C = A2 + B2 28
  29. 29. b. c. d. 3. Find a. A is greater than 0 and less than 100 Grade is A or B Increment the value of X by 20 the output for the following code snippets int a = 39, b = 47; a = a++ + 20; b = ++b = 40; int c = ++a + b++; cout << c; b. int x = 23, y = 34; x = x++ + ++x; y = y + ++y; cout << x << “ “ << y; c. int m = 44, n = 55; int k = m + --n; int j = n – m--; int l = k / j; cout << l; CS WORKBOOK IX 29 Priya Kumaraswami
  30. 30. Notes 30
  31. 31. Chapter – 6 Input and Output The output operation is already illustrated in Chapter 2 – “First Program in C++”. A recap of the same is given below. Output using cout cout is used along with the insertion operator, which is written as << (two "lesser than" signs). cout << "Output sentence"; // prints Output sentence on screen cout << 120; // prints number 120 on screen cout << x; // prints the content of x on screen Notice that the sentence in the first statement is enclosed between double quotes (") because it is a constant string of characters. Whenever we want to use constant strings of characters we must enclose them between double quotes (") so that they can be clearly distinguished from variable names. For example, these two sentences have very different results cout << "Hello"; cout << Hello; // prints Hello // prints the content of Hello variable The insertion operator (<<) may be used more than once in a single statement: cout << "Hello, " << "I am " << "a C++ statement"; This last statement would print the message Hello, I am a C++ statement on the screen. We can combine variables, constants and expressions in a cout statement. CS WORKBOOK IX 31 Priya Kumaraswami
  32. 32. cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode; If we assume the age variable to contain the value 24 and the zipcode variable to contain 90064 the output of the previous statement would be: Hello, I am 24 years old and my zipcode is 90064 It is important to notice that cout does not add a line break after its output unless we explicitly indicate it, therefore, the following statements: cout << "This is a sentence."; cout << "This is another sentence."; will be shown on the screen one following the other without any line break between them: This is a sentence.This is another sentence. even though we had written them in two different insertions into cout. In order to perform a line break on the output we must explicitly insert a new-line character. In C++ a new-line character can be specified as n (backslash, n): cout << "First sentence.n"; cout << "Second sentence.nThird sentence."; This produces the following output: First sentence. Second sentence. Third sentence. Additionally, to add a new-line, you may also use the endl manipulator. For example: cout << "First sentence." << endl; cout << "Second sentence." << endl; would print out: First sentence. Second sentence. 32
  33. 33. Input using cin cin is used along with the extraction operator, which is written as >> (two "greater than" signs). int age; cin >> age; The first statement declares a variable of type int called age, and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable. You can also use cin to request more than one data input from the user: cin >> a >> b; is equivalent to: cin >> a; cin >> b; Note: An uninitialized variable has junk value. Example int a; a = a + 10; cout << a; The a value is undefined here. Sample Program showing input and output #include <iostream.h> void main () { int i; cout << "Please enter an integer value: "; cin >> i; CS WORKBOOK IX 33 Priya Kumaraswami
  34. 34. cout << "The value you entered is " << i; cout << " and its double is " << i*2; } In the above program, an int variable is declared and its value is taken as input. Similarly, other type variables (long, char, float, double) can be declared and their values can be taken as inputs. Exercise 1. Write programs for the following taking necessary inputs a. To find and display the area of circle, triangle and rectangle b. To calculate the average of 3 numbers c. To find and display the simple interest d. To convert the Fahrenheit to Celsius and vice versa F = 9/5 * C + 32 C = 5/9 (F – 32) e. To convert the height in feet to inches (1 foot = 12 inches) 34
  35. 35. Notes CS WORKBOOK IX 35 Priya Kumaraswami
  36. 36. Chapter – 7 Conditions (if and switch) Null Statement • • • • Statements are the instructions given to the computer to perform any kind of action. Statements form the smallest executable unit within a program Statements are terminated with a ; The simplest is the null or empty statement ; Compound Statement • • • It is a sequence of statements enclosed by a pair of braces { } A compound statement is also called a block. A compound statement is treated as a single unit and can appear anywhere in the program. Control Statements • • • • • 36 Generally a program executes its statements from the beginning to the end of main(). But there can be programs where the statements have to be executed based on a decision or statements that need to be run repetitively. There are tools to achieve these scenarios and those statements which help us doing so are called control statements In a program, statements can be executed sequentially, selectively (based on conditions) or iteratively (repeatedly in loops). The sequence construct means the statements are being executed sequentially, from the first statement of the main() to the last statement of the main(). This represents the default flow of statements.
  37. 37. Operators used in conditions • >, <, >=, <=, ==, !=, &&, ||, ! • Examples grade == ‘A’ a > b !x x >=2 && x <=10 grade == ‘A’ || grade == ‘B’ • Please note that == (double equal-to) is used for comparisons and not = (single equal-to) • Single equal-to is used for assignment. • AND (&&) and OR(||) can be used to combine conditions as shown below • a > 20 && a < 40 Both the conditions a > 20 and a < 40 should be satisfied in the above case to get a true. • a == 0 || a < 0 Either the condition a == 0 or the condition a < 0 should be satisfied to get a true value • • • • Not operator (!) negates or inverses the truth value of the expression !true becomes false !false becomes true !(10 > 12) becomes true Note: a > 20 && < 40 is syntactically wrong. a == 0 || < 0 is syntactically wrong. Conditional structure: if CS WORKBOOK IX 37 Priya Kumaraswami
  38. 38. • • Also called conditional or decision statement Syntax of if statement if ( condition ) statement ; • • • • Statement can be single or compound statement or null statement Condition must be enclosed in parenthesis If the condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after the conditional structure. Example if (x == 100) cout << "x is 100"; • • If x value is 100, “x is 100” will be printed. If x value is 95 or 5 or 20 (anything other than 100), nothing will be printed. • If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { } if (x == 100) { cout << "x is "; cout << x; } Note: if (x == 100) { cout << "x is "; cout << x; } • • If x value is 100, x is 100 will be printed. If x value is 95 or 5 or 20 (anything other than 100), nothing will be printed. if (x == 100) cout << "x is "; cout << x; • 38 If x value is 100, x is 100 will be printed.
  39. 39. • If x value is 95 (anything other than 100), 95 will be printed. This is because the if statement includes only one statement in the absence of brackets. The second statement is independent of if. Therefore, the second statement gets executed irrespective of whether the if condition becomes true or not. Note: Any non-zero value is true. 0 is false. Conditional structure: if and else We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. It is used in conjunction with if. if (condition) statement1 ; else statement2 ; // Note the tab space // Note the tab space Example: if (x == 100) cout << "x is 100"; else cout << "x is not 100"; prints on the screen x is 100 if x has a value of 100, but if it is not 100, it prints out x is not 100. Conditional structure: if … else if … else If there are many conditions to be checked, we can use the if … else if … else ladder as shown below in the example. if (x > 0) cout << "x is positive"; else if (x < 0) CS WORKBOOK IX 39 Priya Kumaraswami
  40. 40. cout << "x is negative"; else cout << "x is 0"; The above syntax can be understood as… if condition1 is satisfied, do something. Otherwise, check if condition 2 is satisfied and if so, do something else. Otherwise (else), do completely something else. Remember that in case we want more than a single statement to be executed for each condition, we must group them in a block by enclosing them in braces { }. if (x > 0) { cout << "x is cout << “ and } else if (x < 0) { cout << "x is cout << “ and } else { cout << "x is cout << “ and } positive"; its value is “ << x ; negative"; its absolute value is “ << -x ; 0"; its value is “ << 0 ; Points to remember • • • 40 If there is only one statement for ‘if’ and ‘else’, no need to enclose them in curly braces { } Example if ( grade == ‘A’) cout << “Good grade”; else cout << “Should improve”; In an if statement, DO NOT put semicolon in the line having test condition if ( y > max) ;  if the condition is true, only null statement will be executed. { max = y; }
  41. 41. Conditional structure: Nested if • In a nested if construct, you can have an if...else if...else construct inside another if...else if ...else construct. • Syntax if (condition 1) { if (condition 2) statement 1; else statement 2; } else statement 3; if (condition 1) statement 1; else { if (condition 2) statement 2; else statement 3; } if (expression 1) { if (condition 2) statement 1; else statement 2; else { if (condition 3) statement 3; else statement 4; } CS WORKBOOK IX 41 Priya Kumaraswami
  42. 42. Dangling else problem if ( ch >= ‘A’) if(ch <= ‘Z’) upcase = upcase + 1; else • • Which if the else belongs to, in the above case? The else goes with the immediate preceding if • The above code can be understood as shown below if ( ch >= ‘A’) { if(ch <= ‘Z’) upcase = upcase + 1; else others = others + 1; • If the else has to be matching with the outer if, then use brackets { } as below if ( ch >= ‘A’) { if(ch <= ‘Z’) upcase = upcase + 1; } Difference between if…else if ladder and multiple ifs 42
  43. 43. int a = 10; int a = 10; if( a >= 0) if( a >= 0) cout << a; else if ( a >= cout << a; 5) if ( a >= cout << a + 5; 5) cout << a + 5; else if (a >= 10) if (a >= 10) cout << a + 10; cout << a + 10; else else The output here is 10. The first condition is satisfied and therefore it gets inside and prints 10. The other conditions will not be checked. The output here is 101520. The code here has multiple ifs which are independent. The else belongs to the last if. Conditional structure: switch • • Switch is also similar to if. But it tests the value of an expression against a list of integer or character constants. • Syntax switch (expression) { case constant1: statements; break; case constant2: statements; break; CS WORKBOOK IX 43 Priya Kumaraswami
  44. 44. • switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements under constant1 until it finds the break statement. When it finds the break statement, the program jumps to the end of the switch structure. • If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements under constant2 until a break keyword is found, and then will jump to the end of the switch structure. • Finally, if the value of expression did not match any of the specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional). • If there is no break statement for a case, then it falls through the next case statement until it encounters a break statement. • A case statement cannot exist outside the switch. Example of a switch construct with integer constant int n; cin >> n; switch(n) { case 1: cout << “C++”; break; case 2: cout << “Java”; break; case 5: cout << “C#”; break; 44
  45. 45. default: cout << “Algol”; break; } In the above program, if input is 1 for n, C++ will be printed. If input is 2 for n, Java will be printed. If input is 5 for n, C# will be printed. If any other number is given as input for n, Algol will be printed. Example of a switch construct with character constant char ch; cin >> ch; switch(ch) { case ‘a’: cout << “Apple”; break; case ‘$’: cout << “Samsung”; break; case ‘3’: cout << “LG”; break; default: cout << “Nokia”; break; } In the above program, if input is ‘a’ for ch, Apple will be printed. If input is ‘$’ for ch, Samsung will be printed. If input is ‘3’ for ch, LG will be printed. If any other character is given as input for ch, Nokia will be printed. Scope of a variable CS WORKBOOK IX 45 Priya Kumaraswami
  46. 46. • A variable can be used only within the block it is declared. • Example1 - the scope of j is within that if block only, starting brace of if to ending brace of if. if( a == b) { int j = 10; cout << j; à valid as j is declared inside the if block } cout << j; à invalid as j is used outside the block • Example2 - the scope of n is within the main(), starting brace of main() to ending brace of main() void main() { int n; cin >> n; if ( n > 100) { cout << n << “is invalid”; } cout << “Enter the correct value for n”; } Sample Programs 7.1 Program to print pass or fail given the mark #include <iostream.h> void main() { int x; cout << “Enter the mark”; cin >> x; if (x >= 40) { cout << “Pass J” ; } else { 46
  47. 47. cout << “Fail L” ; } } 7.2 Program to find the grade #include “iostream.h” void main() { int x; cout << “Enter the mark”; cin >> x; char grade; if (x >= 80 && x <= 100) { grade = ‘A’; } else if ( x >= 60 && x < 80) { grade = ‘B’; } else if ( x >= 45 && x < 60) { grade = ‘C’; } else if ( x >= 33 && x < 45) { grade = ‘D’; } else if ( x >= 0 && x < 33) { grade = ‘E’; } else { cout << “Not a valid mark”; grade = ‘N’; } cout << “The grade for your mark is” << grade; } CS WORKBOOK IX 47 Priya Kumaraswami
  48. 48. 7.3 Program to check whether a number is divisible by 5 #include <iostream.h> void main() { int x; cout << “Enter a number”; cin >> x; if (x % 5 == 0) { cout << “The number is divisible by 5”; } else { cout << “The number is not divisible by 5”; } } 7.4 Program to check whether a number is positive or negative #include <iostream.h> void main() { int i; cout << “Enter a number”; cin >> i; if( i >= 0) cout << “positive integer”; else cout << “negative integer”; } 7.5 Program to calculate the area and circumference of a circle using switch This program takes r (radius) as input and also a choice n as input. Depending on the choice entered, it calculates area or circumference. It calculates area if the choice is 1. It calculates circumference if choice is 2. #include <iostream.h> void main() { int n , r; 48
  49. 49. cout << “Enter choice:(1 for area, 2 for circumference)” ; cin >> n ; cout << “Enter radius”; cin >> r; float res; switch(n) { case 1: res = 3.14 * r * r; cout << “The area is “ << res; break; case 2: res = 3.14 * 2 * r; cout << “The circumference is “ << res; break; default: cout << “Wrong choice”; break; } } 7.6 Program to calculate the area and circumference of a circle using switch fall through This program takes r (radius) as input and also a choice n as input. Depending on the choice entered, it calculates area or (area and circumference). It calculates area if the choice is 1. It calculates area and circumference if choice is 2. #include <iostream.h> void main() { cout << “Enter choice:(1 for area, 2 for both)” ; int n , r; cin >> n >> r; float res; switch(n) { CS WORKBOOK IX 49 Priya Kumaraswami
  50. 50. case 2: res = 3.14 * 2 * r; cout << “The circumference is “ << res; case 1: res = 3.14 * r * r; cout << “The area is “ << res; break; default: cout << “Wrong choice”; break; } } 7.7 Program to write remarks based on grade #include <iostream.h> void main() { cout << “Enter the grade” ; char ch; cin >> ch; switch(ch) { case ‘A’: cout << “Excellent. Keep it up. “; break; case ‘B’: cout << “Very Good. Try for A Grade”; break; case ‘C’: cout << “Good. Put in more efforts”; break; case ‘D’: cout << “Should work hard for better results”; break; case ‘E’: cout << “Hard work and focus required”; break; default: cout << “Wrong Grade entered.”; break; } } 50
  51. 51. Exercise 1. Find the output for the following code snippets a. int a , b; cin >> a >> b; if( a % b == 0) cout << a / b; cout << a % b; if a is 42 & b is 7 (1st time run) if a is 45 & b is 7 (2nd time run) b. int x, y = 4; switch(x % y) { case 0: cout << x; case 1: cout << x * 2; break; case 2: cout << x * 3; case 3: cout << x * 4; default: cout << 0; when x is given as 50, 51, 52, 53, 54, 55 } c. char ch; cin >> ch; int val = 2; switch (ch) { case ‘0’: cout << “converting from giga to mega”; cout << val * 1024; break; case ‘1’: cout << “converting from giga to kilo”; cout << val * 1024 * 1024; break; case ‘2’: CS WORKBOOK IX 51 Priya Kumaraswami
  52. 52. cout << “converting from giga to bytes”; cout << val * 1024 * 1024 * 1024; break; default: cout << “invalid option”; break; } When ch is given as 1 2 3 a 0 d. int a, b; cin >> a >> b; if( ! (a % b == 0)) if( a > 10) a = a + b; else a = a + 1; else b = a + b; cout << a << “ “ << b; when a = 10 and b = 5 when a = 9 and b = 3 when a = 8 and b = 6 2. Find the mistakes #include <iostream.h> void main() { int a, b; if( a > b ) ; cout << a << “is greater than “; cout << b; else if ( b > a) cout << b << “is greater than “ ; cout << a else ( a == b) cout << a << “is equal to “ <<; cout << b; } 3. Convert the following if construct to switch construct int m1, m2; if( m1 >= 80) { if( m2 >= 80) cout << “Very Good”; else if (m2 >= 40) cout << “Good”; else cout << “improve”; 52
  53. 53. } else if( m1 >= 40) { if( m2 >= 80) cout << “Good”; else if (m2 >= 40) cout << “Fair”; else cout << “improve”; } else { if( m2 >= 80) cout << “Good”; else if (m2 >= 40) cout << “improve”; else cout << “work hard”; } 4. Write Programs a. To accept the cost price and selling price and calculate either the profit percent or loss percent. b. To accept 3 angles of a triangle and check whether the triangle is possible or not. If triangle is possible, check whether it is acute angled or right angled or obtuse angled. c. To accept the age of a candidate and check whether he can vote or not d. To calculate the electricity bill according to the given tariffs. Units consumed Charges Upto 100 units Rs 1.35 / unit > 100 units and upto Rs 1.50 / unit 200 units > 200 units Rs 1.80 / unit e. To accept a number and check whether the number is divisible by 2 and 5, divisible by 2 not 5, divisible by 5 not 2 f. To accept 3 numbers and check whether they are Pythagorean triplets CS WORKBOOK IX 53 Priya Kumaraswami
  54. 54. g. To accept any value from 1 to 7 and display the weekdays corresponding to the number entered. (use switch case) h. To find the volume of a cube or a cuboid or a sphere depending on the choice given by the user Notes 54
  55. 55. Chapter – 8 Loops A loop is a piece of code that repeats itself until a condition is satisfied. A loop alters the flow of control of the program. Each repetition of the code is called iteration. Parts of a loop • • • • Initialization expression – Control / counter / index variable has to be initialized before entering inside the loop. This expression is executed only once. (Initial Value with which the loop will start) Test expression – This is the condition for the loop to run. Until this condition is true, the loop statements get repeated. Once the condition becomes false, the loop stops and the control goes to the next statement in the program after the loop. (Final Value with which the loop will end) Update expression – This changes the value of the control / counter / index variable. This is executed at the end of the loop statements for each iteration (Step Value to reach the final value from the initial value) Body of the loop – Set of statements that needs to be repeated. for loop • Syntax for (initialization expr ; test expr ; update expr) statement; CS WORKBOOK IX 55 Priya Kumaraswami
  56. 56. The statement can be simple or compound. • Example 1 In this code, i is the index variable. Its initial value is 1. Till i value is less than or equal to 10, the statements will be repeated. So, the code prints 1 to 10. After i=10 and printing it, the index variable becomes 11, but the condition is not met. So the loop stops. Note: i=i+1 can also be written as i++. i=i-1 can also be written as i--; • Example 2 for (int a= 10; a >= 0; a=a-3) { cout << a; } This code prints 10 to 0 with a step of So 10 7 4 1 get printed. • Example 3 for (int c= 10; c >= 1; c=c-2) { cout << ‘*’; } 56 -3.
  57. 57. This code loops 10 to 1 with a step of -2. But the c variable is not printed. ‘*’ is printed 5 times. • Example 4 for (int i = 0; i < 5; i=i+1) cout << i * i; This code prints 0 1 4 9 16. If there is only one statement to be repeated, no need to enclose it in brackets. • Example 5 for (int c= 10; c >= 1; c=c-2) cout << c; cout << c; This code loops 10 to 1 with a step of -2. So 10 8 6 4 2 get printed. Since the brackets are not there, the for loop takes only one statement into consideration. The above code can be interpreted as for (int c= 10; c >= 1; c=c-2) { cout << c; } cout << c; So outside the loop, one more time c gets printed. So 0 gets printed. 10 8 6 4 2 0 is the output from the above code. Variations in for loop Null statement in a loop for (a= 10; a >= 0; a=a-3);  Note the semicolon here cout << a; CS WORKBOOK IX 57 Priya Kumaraswami
  58. 58. This means the null statement gets executed repeatedly. cout << a; is independent. Multiple initialization and update in a for loop for (int a= 1, b = 5; a <= 5 && b >= 1; a++, b--) cout << a << “ “ << b << endl; The output of the above code will be 1 5 2 4 3 3 4 2 5 1 Note: for(int for(int for(int for(int c c c c = = = = 0; 0; 0; 0; c c c c < < < < 5; 5; 5; 5; c++)  c=c++) c=c+2) c+2)  correct  wrong  correct wrong The scope rules are applicable for loops as well. A variable declared inside the body (block) of a for loop or a while loop is not accessible outside the body (block). while loop • Syntax Initial expression while (test expression) Loop body containing update expression • 58 Example 1
  59. 59. • In this code, a is the index variable. Its initial value is 0. Till a is less than or equal to 10, the statements will be repeated. So, the code prints 0 to 10. After i=10 and printing it, the index variable becomes 11, but the condition is not met. So the loop stops. Example 2 int a= 10; while (a >= 0) { cout << a; a=a-3; } This code prints 10 to 0 with a step of -3. So 10 7 4 1 get printed. Variations in while loop Infinite loop • Example 1 int a= 10; while (a >= 0);  Note the semicolon here { cout << a; a=a-3; } This means the null statement gets executed repeatedly. It becomes infinite loop as the update does not happen within the loop. • Example 2 int a= 10; while (a >= 0) { cout << a; } CS WORKBOOK IX 59 Priya Kumaraswami
  60. 60. There is no update statement here. So this also becomes infinite loop as it does not reach the final value. Multiple initialization and update in a while loop int a= 1, b = 5; while (a <= 5 && b >= 1) { cout << a << “ “ << b << endl; a++; b--; } The output of the above code will be 1 5 2 4 3 3 4 2 5 1 Quick Comparison of for and while for loop syntax while loop syntax 60
  61. 61. Nested Loops • • A loop may contain one or more loops inside its body. It is called Nested Loop. Example 1 for(int i= 1; i<=3; i++) { for(int j= 2; j<=4; j++) { cout << i * j << endl; } } Here, the i loop has j loop inside. For each i value, the j value ranges from 2 to 4. i value i = 1 i = 2 i = 3 j j j j j j j j j j value = 2 = 3 = 4 = 2 = 3 = 4 = 2 = 3 = 4 output 1 3 4 4 6 8 6 9 12 • Example 2 CS WORKBOOK IX 61 Priya Kumaraswami
  62. 62. for(int i= 1; i<=2; i++) { for(int j= 3; j<=4; j++) { for(int k= 5; k<=6; k++) { cout << i * j * k<< endl; } } } Here, the i loop has j loop inside which has k loop inside it. For each i value, the j value ranges from 2 to 4. For each value of j, k value ranges from 5 to 6. i value i = 1 j value j = 3 j = 4 i = 2 j = 3 j = 4 • k k k k k k k k k value = 5 = 6 = 5 = 6 = 5 = 6 = 5 = 6 output 15 18 20 24 30 36 40 48 Example 3 for(int i= 1; i<=2; i++) { for(int j= 3; j<=4; j++) { cout << i * j << endl; } for(int k= 5; k<=6; k++) { cout << i * k<< endl; } } Here, the i loop has j loop and k loop inside it. But j loop is independent of k loop. For each i value, the j value ranges from 2 to 4. For each value of i, k value ranges from 5 to 6. i value 62 j value k value output
  63. 63. i = 1 j = 3 j = 4 k = 5 k = 6 i = 2 j = 3 j = 4 k = 5 k = 6 • • 3 4 5 6 6 8 10 12 In the syllabus, we learn to use nested loops for printing Tables Patterns Jump Statements We will be learning 2 jump statements – break and return. Basically, jump statements are used to transfer the control. The control jumps from one place of the code to another place. We’ve already seen break statement in switch. It breaks out of the switch construct. break can be used inside a loop too to break out of the loop if the condition is met. Example for(int c = 9; c < 30; c = c + 2) { if(c%7 == 0) break; } cout << c; c starts from 9 and goes till 29 with a step of 2. If in between any c value is divisible by 7, it breaks out of the loop and prints that value. The output will be 21. return statement is used to return control from a function to the calling code. If return statement is present in main CS WORKBOOK IX 63 Priya Kumaraswami
  64. 64. function, the control will be given to the OS (which is the calling code) and the program will stop. Example #include <iostream.h> void main() { for(int i=0; i<10;i++) { cout << i; if(i==4) return; } } The above program will print 0 1 2 3 4 and stop. Sample Programs 8.1 Program to print multiplication tables from 1 to 10 upto x 20 using nested for loops. #include <iostream.h> void main() { for (int i = 1 ; i <= 10; i=i+1) { cout << i << “ table starts ”; for (int j = 1 ; j <= 20; j=j+1) // this for loop has only one statement to repeat cout << i << “ x “<< j << “ = “<< i * j<< endl ; cout << i << “ table ends” ; cout << endl; } } 8.2 Program to print multiplication tables from 1 to 10 upto x 20 using nested while loops. #include <iostream.h> void main() { int i = 1; 64
  65. 65. while (i <= 10) { cout << i << “table starts” ; int j = 1; while (j <= 20) { cout<<i << “ x “<< j << “ = “<< i * j<<endl; j = j + 1; } cout << i << “table ends” ; cout << endl; i = i + 1; } } * 8.3 Program to print the ** pattern. *** #include <iostream.h> **** void main() { for (int i = 1 ; i <= 5; i++) { for (int j = 1 ; j <= i; j++) cout << ‘*’; cout << endl; } } 8.4 Program to print the pattern. 1 12 #include <iostream.h> 123 void main() 1234 { for (int i = 1 ; i <= 5; i++) { for (int j = 1 ; j <= i; j++) cout << j; cout << endl; } CS WORKBOOK IX 65 Priya Kumaraswami
  66. 66. } 8.5 Program to print the pattern. #include <iostream.h> void main() { for (char i = ‘A’ ; i <= ‘E’; i++) { for (char j = ‘A’ ; j <= i; j++) cout << j; cout << endl; } } 8.6 Program to print the pattern. #include <iostream.h> void main() { } 66 * *** ***** ******* A AB ABC ABCD
  67. 67. 8.7 Program to print the pattern. ******* ***** #include <iostream.h> void main() { *** } 8.8 Program to print the pattern. ******* * #include <iostream.h> void main() { * * * CS WORKBOOK IX 67 Priya Kumaraswami
  68. 68. } 8.9 Program to print the pattern. 1 121 #include <iostream.h> void main() { 12321 1234321 } 8.10 Program to print the pattern. #include <iostream.h> void main() { 68 2 242 24642 2468642
  69. 69. } 8.11 Program to print the pattern. 2468642 #include <iostream.h> void main() { 24642 242 } 8.12 Program to print the pattern. $$$$$ $ $ $ $ #include <iostream.h> void main() { $ $ CS WORKBOOK IX 69 Priya Kumaraswami
  70. 70. } 8.13 Program to print the pattern. $$$$$ $&&&$ #include <iostream.h> void main() { } Exercise 1. Find the outputs 70 $&&&$ $&&&$
  71. 71. a. int a = 33, b = 44; for(int i = 1; i < 3; i++) { cout << a + 2 << b++ << endl; cout << ++a << b – 2<< endl; } b. long num = 64325; int d, r = 0; while(num != 0) { d = num % 10; r = r * 10 + d; num = num / 10; } cout << r; 2. Convert the following nested for loops to nested while loops and guess the output for(int x = 10; x < 20; x=x+4) { for(int y = 5; y <= 50; y=y*5) { cout << x << endl; } cout << y << endl; } 3. Write programs a. To print the odd number series till 999 b. To print the sum of natural numbers from 1 to 100 c. To print the factorial of a given number d. To check whether a number is prime or not e. to generate the Fibonacci and Tribonacci series f. to accept 10 numbers and print the minimum out of them g. to print the following patterns 1 55555 12345 54321 1 1 1357531 22 4444 1234 4321 21 131 13531 123 321 321 13531 131 333 CS WORKBOOK 333 IX 4444 22 %%%%%%% 1 % % 123 % % 12 12345 %%%%%%% 1234567 71 21 4321 1357531 Priya Kumaraswami 1
  72. 72. 72
  73. 73. Notes CS WORKBOOK IX 73 Priya Kumaraswami
  74. 74. Chapter – 9 Number Arrays • • • An array represents continuous memory locations having a name which can store data of a single data type. An array is stored in contiguous memory locations. Lowest address having the first element and highest address having the last element. Arrays can be single dimensional or multi dimensional. Single Dimensional Array Two Dimensional Array (Table format) We learn only single dimensional arrays in class 9. 74
  75. 75. Declaration of an array • • • • • • • • • datatype arrayname [size]; Example int a [6]; The datatype indicates the datatype of the elements that can be stored in an array. We give the arrayname and it has to follow the rules of naming the variables. An array has size. The size denotes the number of elements that can be stored in the array. Size should be positive integer constant. In the above example, a is an array that can store 6 integers. Each array element is referenced by the index number. The index number always starts from zero. So, An array A [6] will have the following elements. A [0], A [1], A [2], A [3], A [4]and A[5]. The index number ranges from 0 to 5 In this example, we have used an array of size 6. int a[6]; a[0] = 25; a[1] = 36; a[2] = 92; a[3] = 45; a[4] = 17; a[5] = 63; cout << a[4]; will print 17 on the screen. CS WORKBOOK IX 75 Priya Kumaraswami
  76. 76. Calculation of bytes The memory occupied by an array is calculated as size of the element x number of elements For example, int a [15]; will take up 2 (size of an int) x 15 (number of elements) = 30 bytes. float arr[20]; will take up 4 (size of a float) x 20 (number of elements) = 80 bytes Loops for input, processing and output Usually, we use loops to take array elements as input, to display array elements as output. Example int a[6]; for(int i = 0; i < 6; i++) cin >> a[i]; // input loop for(i = 0; i < 6; i++) a[i] = a[i] * 2; // processing loop for(i = 0; i < 6; i++) cout << a[i]; // output loop Combining the input and processing loops int a[6]; for(int i = 0; i < 6; i++) // input & processing loop { cin >> a[i]; a[i] = a[i] * 2; } for(i = 0; i < 6; i++) cout << a[i]; Note: 76 // output loop
  77. 77. Generally we avoid combining input and output of array elements in a single loop because it mixes up the display on the screen. Taking the size of the array from the user int a[50]; int size; cin >> size; for(int i = 0; i < size; i++) // input & processing loop { cin >> a[i]; a[i] = a[i] * 2; } for(i = 0; i < size; i++) cout << a[i]; // output loop Operations The following operations are covered in class 9. • Count of elements • Sum of elements • Minimum and Maximum in an array • Replacing an element • Reversing an array • Swapping the first half with the second half • Swapping the adjacent elements • Searching for an element Sample Programs 9.1 Program to count the odd elements. #include <iostream.h> void main() { CS WORKBOOK IX 77 Priya Kumaraswami
  78. 78. } 9.2 Program to sum up all the elements. #include <iostream.h> void main() { 78
  79. 79. } 9.3 Program to find the max and min in the given array. #include <iostream.h> void main() { } 9.4 Program to replace an element. #include <iostream.h> void main() { CS WORKBOOK IX 79 Priya Kumaraswami
  80. 80. } 9.5 Program to reverse the array. #include <iostream.h> void main() { 80
  81. 81. } 9.6 Program to swap the first half with the second half. #include <iostream.h> void main() { } 9.7 Program to swap the adjacent elements. #include <iostream.h> void main() { CS WORKBOOK IX 81 Priya Kumaraswami
  82. 82. } 9.7 Program to search for a given element using flag. #include <iostream.h> void main() { 82
  83. 83. } Exercise 1. Fill in the blanks The following program searches for a given element using count. Some portions of the program are missing. Complete them. #include <iostream.h> void main() { int a [ 10]; for ( ) //input for array ; int num; cout << “Enter the number to find”; cin >> num; int count = 0; for(__________________________) { if(____________) count++; } if(count ______) cout << “found in the array”; else cout << “not found in the array”; } 2. Find the number of bytes required in memory to store a. A double array of size 20. b. A char array of size 30 CS WORKBOOK IX 83 Priya Kumaraswami
  84. 84. c. A float array of size 50 3. Write Programs a. To count the number of elements divisible by 4 in the given array of size 20 b. To sum up the even elements in the array of size 10 c. To combine elements from arrays A and B into array C Notes 84
  85. 85. Chapter – 10 Char Arrays Char arrays are similar to number arrays. The storage in memory is similar to that of number arrays. The difference comes when the char array is treated as a single string. In that case, the input and output need not use a loop. At the end, a null character 0 has to be present. Null character marks the end of the string. In the below diagram, though 8 bytes are allocated, we use only 6 bytes. So the presence of null character next tells us that the string has ended. The above diagram shows a char array of size 8. But all the 8 bytes are not used since the array has to store only “class9” which has length 6, one additional byte to store the null character. Declaration of char array char arrayname [size]; CS WORKBOOK IX 85 Priya Kumaraswami
  86. 86. • • • Example char A [8]; We give the arrayname and it has to follow the rules of naming the variables. An array has size. The size denotes the number of elements that can be stored in the array. Size should be positive integer constant. In the above example, A is an array that can store 8 characters including the null character. • • Each array element is referenced by the index number. The index number always starts from zero. • • • So, An array A [8] will have the following elements. A [0], A [1], A [2], A [3], A [4], A[5], A[6] and A[7] The index number ranges from 0 to 7 char array as a single string Input Operation char str [20]; gets (str); where gets is a function to get a string from the user. Here, the null character is automatically added. Output Operation puts (str); 86
  87. 87. where puts is a function to display a string on the screen. This will display the string till the null character. To use gets() and puts() function, we need to #include <stdio.h> char array not as a string Input Operation char str [20]; for(int i=0; i<20;i++) cin>> str[i]; Here, the null character is not added and it will take all the 20 characters. Output Operation for(int i=0; i<20;i++) cout << str[i]; This will display all the 20 characters on screen. Library Functions We use two libraries ctype.h and string.h to do the char and string manipulation. ctype.h functions work at character level. string.h functions work at string level considering the sequence of characters as a single string. ctype.h functions • • • islower() to check if the char is lowercase isupper() to check if the char is uppercase tolower() to convert to lowercase CS WORKBOOK IX 87 Priya Kumaraswami
  88. 88. • • • • toupper() isalpha() isdigit() isalnum() to to to to convert to uppercase check if the char is alphabet check if the char is digit check if the char is alphanumeric Usage of ctype.h functions char ch; cin >> ch; if(islower(ch)) if(isupper(ch)) if(isalpha(ch)) if(isdigit(ch)) if(isalnum(ch)) ch = toupper(ch); ch = tolower(ch); string.h • • • • functions strlen() strcmp() strcpy() strcat() Usage of string.h functions char s[30]; gets(s); char c[30]; gets(c); int len = strlen(s); //Calculates the actual length if(strcmp(s, c) == 0) // if s and c are equal, it will give 0 strcpy(s, c); //copies c to s strcat(s, c); //Joins s and c and stores in s char manipulation inside the loop All character manipulations take place inside the loop. Example 88
  89. 89. char arr[40]; // declare char array of required size gets (arr); // take input for char array int len = strlen(arr); // find the exact length for(int i=0; i<len; i++) // loop to process { //arr[i] can be modified or processed here //arr[i] denotes each character in the char array } Operations The following operations are covered in class 9. • Count of a char in an array • Conversion of cases • Replacing a char • Reversing an array • Checking for palindrome • Searching for a char Sample Programs 10.1 Program to take a string as input and change their cases. For example, if “I am Good” is given as input, the program should change it to “i AM gOOD” #include “iostream.h” #include “string.h” #include “stdio.h” #include “ctype.h” void main() { //for //for //for //for cout and cin strlen() gets() and puts() char functions(isupper()etc) CS WORKBOOK IX 89 Priya Kumaraswami
  90. 90. char arr [51]; gets(arr); int len = strlen(arr); for(i = 0; i < len; i= i+1) { if( isupper(arr[i])) arr[i] = tolower(arr[i]); else if( islower(arr[i])) arr[i] = toupper(arr[i]); } puts(arr); } 10.2 Program to take a string as input and count the number of spaces, vowels and consonants 10.3 Program to take a string as input and replace a given char with another char 90
  91. 91. 10.4 Program to take a string as input, reverse it and check if it’s a palindrome CS WORKBOOK IX 91 Priya Kumaraswami
  92. 92. 10.5 Program to take a string as input and search for a char Exercise 1. Find the output 92
  93. 93. a. char ch = ‘&’; char st[20]="BpEaCeFAvourEr"; for(i=0;st[i] != ‘0’;i++) { if(st[i]>='D' && st[i]<='J') st[i]=tolower(st[i]); else if(st[i]=='A' || st[i]=='a'|| st[i]=='B' || st[i]=='b') st[i]=ch; else if(i%2!=0) st[i]= st[i]+1; else st[i]=st[i-1]; } puts(st); b. char msg[20] = “WELCOME”; for (int i = strlen (msg) - 1; i > 0; i--) { if (islower(msg[i])) msg[i] = toupper (msg[i]); else if (isupper(msg[i])) if( i % 2 != 0) msg[i] = tolower (msg[i-1]); else msg[i]=msg[i-1]; } cout << msg << endl; 2. Write Programs a. To convert the vowels into upper case in a string b. To replace all ‘a’s with ‘e’s (consider case) c. To count the number of digits and alphabet in a string d. To find the longest out of 3 strings Notes CS WORKBOOK IX 93 Priya Kumaraswami
  94. 94. Chapter – 11 Functions • • • • • Large programs are difficult to manage and maintain. A large program is broken down into smaller units called functions. A function is a named unit consisting of a set of statements. This unit can be invoked from other parts of the program. Two types • Built in – They are part of the libraries which come along with the compiler like strlen( ). • User defined – They are created by the programmer. Parts of a function in a Program • • • Function Prototype or Declaration (just after the iostream.h) Function Definition (below the main function) Function Call (in the main function ) Example #include “iostream.h” int calculateresult (int, int); int main( ) { int a, b, c, d, e, f; cin >> a; cin >> b; c = calculateresult (a, b); cin >> d; cin >> e ; f = calculateresult (d, e); cout << f; return 0; } 94  Function Prototype  Function call 1  Function call 2
  95. 95. int calculateresult (int p, int q) { int r; r = p + q + (p * q); return r; }  Function Definition Working of a function Function Prototype is just to announce the presence of a function later in the program. Function call in the main() (or some other function) makes the control go to the required function definition and do the work. The argument values in the function call are copied to the argument values in the function definition. Function Definition is the code which does the actual work and may return a result. The control goes back to the main() and the result can be copied to a variable or printed or used in an expression. Function Prototype Syntax • • Function prototype is the declaration of the function that tells the program about the type of the value returned by the function and the number and type of arguments. It enables a compiler to carefully compare each use of the function with the prototype to check whether the function is invoked properly i.e., • the right arguments are passed (number of arguments and type) • The right type is expected as return type CS WORKBOOK IX 95 Priya Kumaraswami
  96. 96. ReturnDatatype functionname ( datatype arg1, datatype arg2, ……) ; ReturnDatatype denotes the datatype of the return value from the function, if any. If the function is not returning any value, then void should be given. A function can return only one value. • • void data type specifies an empty value It is used as the return type of functions which do not return a value. Functionname denotes the name of the function and it has to follow the rules of naming the variables. Within brackets (), the argument list is present. For each argument, the datatype and name should be written. There can be zero or more arguments. If there are more arguments, they should be comma separated. Example 1. float func ( int a, int b ); func is the function name, a and b are the arguments with int datatype, float is the return datatype 2. int demo ( float x); demo is the function name, x is the argument with float datatype, int is the return datatype 3. void test ( float m, int n, char p); test is the function name, m is the first argument with float datatype, n is the second argument with int datatype, p is the third argument with char datatype, void is the return datatype 4. int example () example is the function name, there are no arguments, int is the return datatype Function Definition Syntax • 96 Function definition is just like Prototype declaration except that it has body and it does not have a semicolon
  97. 97. • The function prototype and the function definition must agree EXACTLY on the return type, function name and argument / parameter list (number and type) if the ReturnDatatype is not void ReturnDatatype functionname ( datatype arg1, datatype arg2, ……) { return ____ ; } if the ReturnDatatype is void void functionname ( datatype arg1, datatype arg2, ……) { return; // This is optional } CS WORKBOOK IX 97 Priya Kumaraswami
  98. 98. Example 1. float func ( int a, int b ) { float k = 0.5 * a * b; return k; } 2. int demo ( float x) { int n = x / 2; return n; } 3. void test ( float m, int n, char p) { cout << (m + n)* p; } 4. int example () { int k; cin >> k; k = k * 2; return k; 98
  99. 99. } Function call Syntax if the ReturnDatatype is not void ReturnDatatype variable = Functionname (arg1, arg2 …); if the ReturnDatatype is void Functionname (arg1, arg2 …); Note that the arguments do not have their datatypes. The returned value can be stored in a variable, printed or used in an expression as shown below • • • int c = calculateresult (a, b ); returned value stored in a variable cout << calculateresult (a, b); returned value printed directly int d = calculateresult (a, b) + m * n; returned value used in expression Example 1. 2. 3. 4. float ans = func (a, b ); int res = demo (x); test (m, n, p); int val = example (); Possible Function Styles 1. 2. 3. 4. Void function with no arguments Void function with some arguments Non void function with no arguments Non void function with some arguments CS WORKBOOK IX 99 Priya Kumaraswami
  100. 100. Function Scope • Variables declared inside a function are available to that function only Example Sample Programs 11.1 Program to calculate power ab using a function (returns a value) #include <iostream.h> long power (int a, int b); //Function Prototype void main() { int n1, n2; cin >> n1 >> n2; long p = power (n1, n2); //Function Call cout << p; } 100
  101. 101. long power (int a, int b) //Function Definition { long pow = 1; for (int i = 1; i <= b, i++) pow = pow * a; return pow; } 11.2 Program to calculate factorial n! using a function (void) #include <iostream.h> void factorial (int n); //Function Prototype void main() { int a; cin >> a; factorial (a); //Function Call } void factorial (int m) //Function Definition { long fact = 1; for (int i = 1; i <= m, i++) fact = fact * i; cout << fact; } 11.3 Program to calculate area of a triangle using a function (area = ½ x b x h) CS WORKBOOK IX 101 Priya Kumaraswami
  102. 102. 11.4 Program to calculate volume and surface area of a sphere using 2 separate functions (volume = 4/3 pi r3 , surface area = 4 pi r2) 11.5 Program to print the multiplication table of a given number upto x 20 using a function 102
  103. 103. 11.6 Program to check whether a given number is prime using a function CS WORKBOOK IX 103 Priya Kumaraswami
  104. 104. 11.7 Program to find the max in an int array of size 20 using a function Exercise 1. Find the output a. #include <iostream.h> int calc ( int x, int y); void main() { int m = 60, n = 44; int p = calc (m, n); 104
  105. 105. m = m + p; p = calc (n, m); n = n + p; cout << m << “ “ << n << “ “ << p; } int calc ( int x, int y) { x = x + 10; y = y – 10; int z = x % y; return z; } b. #include <iostream.h> int calc ( int x[6], int s); void main() { int arr[6] = { 12, 15, 3, 9, 20, 18 }; calc (arr, 6); } int calc ( int x[6], int y) { for(int i=0; i<6; i=i+2) { switch(i) { case 0: case 1: cout << x[i] * (i+1); break; case 2: case 3: cout << x[i] * 3; case 4: case 5: cout << x[i] * 5; break; } } } CS WORKBOOK IX 105 Priya Kumaraswami
  106. 106. 2. Rewrite the following program after correcting syntactical errors #include <iostream.h> void demo ( int a ; int b) void main() { float p, q; int r = demo(p , q); cout << r; } void demo ( int a ; int b); { p = p + 10; q = q – 10; r = p + q; return r; } 3. Write Programs using functions a. To find a3 + b3 given a and b b. To convert the height of a person given in inches to feet c. To print the sum of odd numbers in a given int array d. To convert the cases of a char array 106
  107. 107. Notes CS WORKBOOK IX 107 Priya Kumaraswami
  108. 108. Worksheet - 1 1. (C++ Datatypes, Constants, Variables, Operators, Input and Output) Match the following int a; a. An integer constant “c++” b. A floating point constant C = 20; c. A char constant 9.5 d. A string (char array) constant ‘n’ e. A variable declaration 100 f. A variable initialization 2. Give examples of your own for a. b. An integer constant c. A floating point constant d. A char constant e. A string (char array) f. g. constant A variable declaration A variable initialization 4. 5. 3. List the basic data types in C++ and explain their ranges. Identify constants, variables and data types in the following statements. a. b. int a = 10; e. cin >> d; c. char c = ‘d’; f. float f = 3.45; d. cout << c << “alphabet”; g. double d = m; 6. Find the mistakes in the following C++ statements and write correct statements. a. b. int a = 10,000; f. cout << the result is << “k”; c. char c = “f”; g. cout << a(b+c); d. char ch = ‘go’; h. float f$ = 5.49; e. cin >> “g”; i. int k = 40,129; 8. Identify the valid and invalid variables from the following giving reasons for invalid ones a. b. int My num; f. int num1; c. int my_num; g. int main; d. int my-num; h. int Main; 10. e. int 1num; Write C++ expressions (applying BODMAS) 7. 9. 11. 108
  109. 109. a. b. c. d. e. a 2 + 2ab n−b g. k = 1 h. z = ab + 3 (x – y)2 a2b 2ab pnr/100 a2 + 2ab + b2 f. sum = n(n + 1) 2 12. 13. Write a. b. c. d. e. f. g. 14. 15. 16. C++ statements for the following Initialize a variable c with value 10 Take an integer as input in variable k Print a floating point variable f Print a string constant “Programming is fun” Print a string constant “Result” and an integer constant 10 Print a string constant “Result” and an integer variable x Take 2 numbers as input and find their squares and print them with proper messages Write C++ programs for the following with proper messages wherever necessary a. Print the area and perimeter of a square whose side is 50 b. Print the sum, difference, product and quotient of any 2 numbers c. Interchange the values of 2 variables using a third variable d. To accept temperature in degree Celsius and convert it to degree Fahrenheit (F = 9/5 * C + 32) Evaluate the following if a = 88, b = 101, c = 34 a. b = (b++) + c; a = a – (--b); c = (++c) + (a--); b. a * b / c + 10 c. a / 2 + b * b + 3 * c d. a * b – a / b + c * 2 e. a = b + 20; c = (a++) + 10; b = b – (--a) Find the output of the following #include <iostream.h> #include <iostream.h> void main() void main() { { int x = 9, y = 99, z = 199; int p = 20; cout << x + 7 << endl; int q = p; x = x CS WORKBOOK IX + y; q = q + 3; 109 Priya Kumaraswami
  110. 110. 17. #include <iostream.h> #include <iostream.h> void main void main() { { int k; int s = 75; k = k + 10; int ____ = 100; p = p + 20; ____ t = 85; cin >> “k”; int tot = ___ + m + t; cin >> 10; int a = tot / 3; Find the mistakes in the following code sample 18. Fill in the blanks 19. List the types of operators. 20. Give examples of unary and binary operators. 110
  111. 111. Worksheet – 2 (if..else) 1. Write ‘if’ statements for the following a. To check whether the value of int variable a is equal to 100 b. To check whether the value of int variable k is between 40 2. and 50 (including 40 and 50) c. To check whether the value of int variable k is between 40 and 50 excluding 40 and 50) d. To check whether the value of int variable s is not equal to 50 e. To check whether the value of a char variable ch is equal to ‘lowercase a’ or ‘uppercase a’ Find the output of the following a. int i = j = 10; if ( a < 100) if( b > 50) i = i + 1; else j = j + 1; cout << i << “ “ << j ; Value supplied for a and b a = 30, b = 30 Value supplied for a and b a = 60, b = 70 b. int i = j = 10; if ( a < 100) { if( b > 50) i = i + 1; } else j = j + 1; cout << i << “ “ << j ; Value supplied for a and b a = 30, b = 30 Value supplied for a and b a = 60, b = 70 c. if (!3) { cout << “Tricky”; } cout << “Yes”; d. if ( 3 ) cout << “Tricky again”; else CS WORKBOOK IX 111 Priya Kumaraswami
  112. 112. cout << “Am I right?”; cout << “No??”; e. if ( 0 ) cout << “Third Time Tricky”; cout << “Am I right?”; f. if ( !0 ) cout << “Fourth Time Tricky”; cout << “No??”; g. if ( 0 ) cout << “Not again”; else cout << “Last time”; cout << “Thank God”; 3. Find the mistakes and correct them. int b; a) if (b = 10); cout << “Number of bats = 10” ; cout << “10 bats for 11 players… Not sufficient!”; else if ( b = 15) cout << “Number of bats = 15”; cout << “Cool… Bats provided for the substitutes too..” ; else (b = 20) cout << “Number of bats = 20” ; 4. Write complete C++ programs using if construct a. To find the largest and smallest of the given 3 numbers A, B, C b. To find whether the number is odd or even, if its even number check whether it is divisible by 4. c. To find whether a year given as input is leap or not d. To convert the Fahrenheit to Celsius or vice-versa depending on the user’s choice e. To create a four function calculator ( +, -, /, *) f. To calculate the commission rate for the salesman. The commission is calculated according to the following rates Sales Commission Rate 112
  113. 113. 5. 30001 onwards 15% 22001 – 30000 10% 12001 – 22000 7% 5001 – 12000 3% 0 – 5000 0% Illustrate Nested If with examples Worksheet – 3 (switch) 1. Convert the following ‘if’ construct to ‘switch’ construct 2. 3. char ch; cin >> ch; if( ch == ‘A’) cout << “Excellent. Keep it up.”; else if (ch == ‘B’) cout << “Good job. Try to get A grade next time”; else if (ch == ‘C’) cout << “Fair. Should work hard to get good grades”; else if (ch == ‘D’) cout << “Preparation not enough. Should work very hard”; else cout << “Invalid grade”; Find the output of the following int ua = 0, ub = 0, uc = 0, fail = 0, c; cin >> c; switch(c) { case 1: case 2: ua = ua + 1; case 3: case 4: ub = ub + ua; case 5: uc = uc + ub; default: fail = fail + uc; } cout << ua << “-“ << ub << “-“ << uc << “-“ << fail ; The above code is executed 6 times and in each execution, the value of c is supplied as 0, 1, 2, 3, 4 and 5. Find the mistakes and correct them. CS WORKBOOK IX 113 Priya Kumaraswami
  114. 114. 114
  115. 115. CS WORKBOOK IX 115 Priya Kumaraswami
  116. 116. 116
  117. 117. CS WORKBOOK IX 117 Priya Kumaraswami
  118. 118. int b; cin >> b; switch (b) { case ‘10’; cout << “Number of bats = 10” ; break; case ‘10’: cout << “Number of bats = 15” ; 4. Write complete C++ programs using switch construct a. To display the day depending upon the number (example, if 1 5. 118 is given, “Sunday” should be printed, if 7 is given, “Saturday” should be printed. b. To display the digit in words for digits 0 to 9 c. To calculate the area of a circle, a rectangle or a triangle depending upon user’s choice Convert the following ‘if’ construct to ‘switch’ construct int a; char b; cin >> a; cin >> b; if( a == 1) { cout << “Engineering”; if(b == ‘a’) cout << “Mechanical”; else if ( b == ‘b’) cout << “Computer Science”; else if ( b == ‘c’) cout << “Civil”; } else if (a == 2) { cout << “Medicine”; if(b == ‘a’) cout << “Pathology”; else if ( b == ‘b’) cout << “Cardiology”; else if ( b == ‘c’) cout << “Neurology”; } else if (a == 2) { cout << “Business”; if(b == ‘a’) cout << “Finance”; else if ( b == ‘b’) cout << “Human Resources”; else if ( b == ‘c’) cout << “Marketing”; }
  119. 119. 6. Find the output of the following if a gets values 0, 1 and 2 in 7. three consecutive runs. int a; cin >> a; switch (a) { default: cout << 'd'; case 0: cout << 0; case 1: cout << 1; } Find the output of the following if a gets values 0, 1 and 2 in three consecutive runs. int a; cin >> a; switch (a > 100) { default: cout << 'd'; break; case 0: cout << 0; break; case 1: cout << 1; break; } CS WORKBOOK IX 119 Priya Kumaraswami
  120. 120. Worksheet – 4 (Loops) 1. Write a program to print tables of 3,6,9,….n upto x15 2. ( multiplied by 15) Write Programs to print the following patterns using nested loops 1 2 23 242 456 24642 2468642 (*****) 1 1 97531 & (***) 13 31 7531 &$& (*) 135 531 531 &$$$& 1357 7531 31 &$$$$$& 3. How many times “hello” will be printed in the following code fragment: for (i=0; i<5; i++) for (j=0; j<4; j++) cout<< “hello”; 4. Find the output a. #include <iostream.h> void main() { int A = 5, B = 10; for (int c = 1; c <= 2 ; c++) { cout << “Line 1 “ << A++ << “ & “ << --B << endl; cout << “Line 2 “ << B + 3 << “ & “ << A + 5 << endl; } } b. #include <iostream.h> void main() { int m = -3, n = 1; while( m > -7 ) { m = m - 1; n = n * m; cout << n;; } } 5. What is wrong with the following while loops? a. int counter = 1; b. int counter = 1; while(counter < 100) while(counter < 100) { cout << counter; cout << counter); counter ++; counter --; } 6. What will be the output of the following code? Explain. for (int { 120 c = 0; c <= 10; c++)
  121. 121. if(c == 4) break; else cout << c; 7. 8. } cout << c; Convert the following nested for loops to nested while loops and find the output for(int i=0; i<5;i++) { for(int j=1;j<3;j++) { if( i != j) cout << i * j; } } Explain the steps and find the output. int a = 5, b = 15; int num = 12345; if ( (a + b) % 2 == 0) int d; { int s = 0; b = b % 10; while (num != 0) a = a + b; { cout << a << “ “ << b << endl; d = num % 10; } cout << d << endl; if ( a % 10 == 0) s = s + d; { num = num / 10; switch(a) 9. What will be the output? a. for (int c = cout << c; cout << c; b. for (int c = cout << c; cout << c; c. for (int c = { cout << c; cout << c; } d. for (int c = { cout << c; } cout << c; { 0; c <= 10; c++); 0; c <= 10; c++) 0; c <= 10; c++) 0; c <= 10; c++) CS WORKBOOK IX 121 Priya Kumaraswami
  122. 122. 10. Which out of the following will execute 5 times? a. for ( int j = 0; j <= 5; j++) b. for ( int j = 1; j < 5; j++) c. for ( int j = 1; j < 6; j++) d. for ( int j = 0; j < 6; j++) e. for ( int j = 0; j < 5; j++) 11. What is a nested loop? 12. What are the parts of a loop? 122
  123. 123. Worksheet – 5 Function related Programs 1. Write a C++ program with a function to find the volume of a cone. The function has the following prototype:- float vol (int radius, int height); volume of a cone = 1/3 pi r2 h 2. Write a C++ program with a function to find the simple interest. The function has the following prototype:- void calcinterest (int p, int q, float r); Char Array Programs 3. Write a C++ program to convert the string given as input as specified below a. All capital letters should be replaced with the next letter (for example – A should be changed as B, B should be changed as C …. Z remains Z etc) b. All small letters should be replaced with the previous letter (for example – a remains a, b should be changed as a, c should be changed as b etc) c. Example Input  Computer Example Output  Dnlotsdq Integer / Float Array Program 4. Write a program in C++ which takes single dimensional array and size of array and find sum of elements which are positive. If 1D array is 10 , 2 , −3 , −4 , 5 , −16 , −17 , 23 Then positive numbers in above array is 10, 2, 5, 23 Sum = 10 + 2 + 5 + 23 = 40 Output is 40 5. Write a program in C++ to combine the contents of two equi-sized arrays A and B by computing their corresponding elements with the fornula 2 *A[i]+3*B[i], where value I varies from 0 to N-1 and transfer the resultant content in the third same sized array. 6. Write a program in C++ which accepts an integer array and its size and replaces elements having even values with its half and elements having odd values with twice its value . eg: if the array contains 3, 4, 5, 16, 9 then the array should be rearranged as 6, 2,10,8, 18 Find the output of the following code snippets 7. void main() { int AY[5]={5,10,15,20,25}; int loop = 5; for(int m=0; m<loop ;m++) CS WORKBOOK IX 123 Priya Kumaraswami
  124. 124. { } switch (m) { case case case case } 0: 4: cout<<AY[m]*5; 2: 1: cout<<AY[m]<<endl; } 8. void main() { char Text[ ]= “Mind@Work#”; for (int I=0; Text[I] != ‘0’; I++) { if ( ! isalpha(Text[I])) Text[I]=’*’; else if (isupper (Text[I])) Text[I]=Text[I]+1; else Text[i]=Text[I+1]; } puts(a); } 9. int stock[ ]={ 10,22,15,12,18}; 10. 11. 124 int total=0; for(int I=0; I<5; I++) { if(stock[I]>15) total+=stock[I]; } cout<<total; void execute(int x,int y) { int temp = x+y; x = x + temp; if(y!=200) cout << temp << ” “ << x << ” “ << y; } void main( ) { int a=50, b=20; execute (b, 200); cout <<a << b << ”n”; execute (a,b); cout <<a << b << ”n”; } void arm(int n) { int number, sum=0,dg,dgg,digit; number=n; while(n>0) { dg=n/10; dgg=dg*10;
  125. 125. digit=n-dgg; cout<<digit+digit<<endl; sum=sum+digit*digit*digit; n=n/10; } cout<<digit<<endl<<sum; } void main( ) { int num =191; arm(num); } CS WORKBOOK IX 125 Priya Kumaraswami

×