C++ publish copy

132
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

description

C++ Basics - Study Material for IX standard

Transcript of C++ publish copy

Page 1: C++ publish   copy

C++ Handbook for Class IXComputer 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 Kumaraswami10/27/2013

Page 2: C++ publish   copy

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

CS WORKBOOK IX1

Priya Kumaraswami

Page 3: C++ publish   copy

Table Of Contents

Chapter – 1...........................................................................................................................3Introduction to Programming..............................................................................................3Chapter – 2...........................................................................................................................6First Program in C++...........................................................................................................6Chapter – 3.........................................................................................................................10C++ Variables and Constants............................................................................................10Chapter – 4.........................................................................................................................16C++ Datatypes...................................................................................................................16Chapter – 5.........................................................................................................................24Operators and Expressions................................................................................................24Chapter – 6.........................................................................................................................30Input and Output................................................................................................................30Chapter – 7.........................................................................................................................36Chapter – 7.........................................................................................................................36Conditions (if and switch).................................................................................................36Chapter – 8.........................................................................................................................57Loops.................................................................................................................................57Chapter – 9.........................................................................................................................78Number Arrays..................................................................................................................78Chapter – 10.......................................................................................................................91Char Arrays........................................................................................................................91Chapter – 11.....................................................................................................................102Functions..........................................................................................................................102Worksheet - 1..................................................................................................................118Worksheet – 2 (if..else)....................................................................................................120Worksheet – 3 (switch)....................................................................................................122Worksheet – 4 (Loops)....................................................................................................124Worksheet – 5..................................................................................................................126

CS WORKBOOK IX2

Priya Kumaraswami

Page 4: C++ publish   copy

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 Development1. 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.)

CS WORKBOOK IX3

Priya Kumaraswami

Page 5: C++ publish   copy

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 Programming2. 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 IX4

Priya Kumaraswami

Page 6: C++ publish   copy

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

CS WORKBOOK IX5

Priya Kumaraswami

Page 7: C++ publish   copy

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 commentspanning three lines to demonstratethe 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.• The syntax of main function is given below.

void main(){

……

CS WORKBOOK IX6

Priya Kumaraswami

Page 8: C++ publish   copy

}• 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• Execution is the process of running the instructions

one by one in the CPU and getting the results.

Integrated Development Environment

CS WORKBOOK IX7

Priya Kumaraswami

Page 9: C++ publish   copy

• 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 writteno a compiler  o a provision to run the programo a provision to debug the program

Exercise1. 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 IX8

Priya Kumaraswami

Page 10: C++ publish   copy

Notes

CS WORKBOOK IX9

Priya Kumaraswami

Page 11: C++ publish   copy

Chapter – 3

C++ Variables and ConstantsBefore 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.

String Constants Examples

String or character array constants should be always enclosed in double quotes.

• “123” (character array )

CS WORKBOOK IX10

Priya Kumaraswami

Page 12: C++ publish   copy

• “Abc” (character array )• “This is some text.” (character array )• “so many $” (character array )

char Constants Examples

Character constants should be always enclosed in single quotes.

• ‘A’ (character)• ‘z’ (character)

integer constants Examples

• 123 (integer)• 34 (integer)

floating point constants Examples

• 34.78 (floating point)• 5666.778 (floating point)

A sample program using constants

CS WORKBOOK IX11

Priya Kumaraswami

Page 13: C++ publish   copy

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.ExampleA = 10; A contains 10 nowA = A + 1; A contains 11 nowA = 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.

The type (i.e., datatype) of a variable will be covered in next chapter.

CS WORKBOOK IX12

Priya Kumaraswami

Page 14: C++ publish   copy

Rules for naming the variables• All variable names should begin with a letter and

further it can have digits or underscores or letters.

• A variable name should not contain space or any other special character.

• 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:

• 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.

CS WORKBOOK IX13

Priya Kumaraswami

Page 15: C++ publish   copy

Exercise1. Identify the type of constants

a. 123.45b. 145.0c. 1166d. “1166”e. “123.45”f. ‘3’g. “*”

2. Indicate whether the following variable names are valid or not

a. fghb. Mainc. 5god. var namee. var_namef. var*name

3. Identify the errorsa. ‘abc’b. 14.c. .45d. 50,000

CS WORKBOOK IX14

Priya Kumaraswami

Page 16: C++ publish   copy

Notes

CS WORKBOOK IX15

Priya Kumaraswami

Page 17: C++ publish   copy

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• With 1 bit, we can represent 2 numbers (21)

Bit Combination Decimal Value0 01 1

CS WORKBOOK IX16

Priya Kumaraswami

Page 18: C++ publish   copy

• With 2 bits, we can represent 4 numbers (22)Bit Combination Decimal Value00 001 110 211 3

• With 3 bits, we can represent 8 numbers (23)Bit Combination Decimal Value000 0001 1010 2011 3100 4101 5110 6111 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, called ASCII code. The ASCII table for the alphabet and digits are given below.

Char ASCII codeA to Z 65 to 90a to z 97 to 1220 to 9 48 to 57

CS WORKBOOK IX17

Priya Kumaraswami

Page 19: C++ publish   copy

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 Example data that can be stored using the given datatype

char 1 byte -128 to 127 ‘a’, ‘A’, ‘$’, ‘1’, ‘0’, ‘%’(Any single character on the keyboard)

int 2 bytes -32768 to 32767 12, 9489float 4 bytes Approx 7 digits 12.43, 6789.566double 8 bytes Approx 15 digits 56789.66666long 4 bytes -2147483648 to

214748364745674, 998304

void None

Variable Declaration • Any variable should be declared before we use it.

• Associating a variable name with a datatype is called declaration.

int a;

CS WORKBOOK IX18

Priya Kumaraswami

Page 20: C++ publish   copy

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; (ch occupies 1 byte)long num; (num occupies 4 bytes)double d; (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

previous statement

Variable Initialization • Giving an appropriate value for a variable is known as

initialization

• Examplesint a = 10;float b = 12.5;

CS WORKBOOK IX19

Priya Kumaraswami

Page 21: C++ publish   copy

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}

Exercise1. Write correct declarations for the following

a. A variable to store 13.5b. A variable to store Helloc. A variable to store grade (A / B / C / D / E)d. A variable to store 10000

2. Convert the following decimal numbers to binarya. 1024b. 255c. 1189d. 52

3. Draw the table to show the bit combination and decimal value for 4 bits binary.

4. Identify the errors in the following

CS WORKBOOK IX20

Priya Kumaraswami

Page 22: C++ publish   copy

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 IX21

Priya Kumaraswami

Page 23: C++ publish   copy

Notes

CS WORKBOOK IX22

Priya Kumaraswami

Page 24: C++ publish   copy

Chapter – 5

Operators and ExpressionsTwo Categories• Binary operators – operators which take 2 operands.

Examples +, - , > , <, =• Unary operators – operators which take 1 operand.

Examples ++, --, !

Operations and the OperatorsArithmetic 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 < 100b == 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).

Assignment Operator = Assignment operator is used to assign a value to a variablea = 10;b = b + 20;c = b;

CS WORKBOOK IX23

Priya Kumaraswami

Page 25: C++ publish   copy

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 expressionExample a = 10, b = 20C = (++a) + (++b) = 11 + 21 = 32

Post increment – First the current value is used in the expression and then the values are incrementedExample a = 10, b = 20C = (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 expressionExample a = 10, b = 20C = (--a) + (--b) = 9 + 19 = 28

Post decrement – First the current value is used in the expression and then the values are decrementedExample a = 10, b = 20C = (a--) + (b--) = 10 + 20 = 30 then a becomes 9 and b becomes 19

Sample Problem

int a = 20 , b = 40;int c = a++ + ++b; 20 + 41 = 61 (a becomes 21)a = a + b++; 21 + 41 = 62 (b becomes 42)b = c - --a; 61 – 61 = 0cout << a << b << c; 61 0 61 will be printed

CS WORKBOOK IX24

Priya Kumaraswami

Page 26: C++ publish   copy

ExpressionsC++ 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 < 90a != 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 IX25

Priya Kumaraswami

Page 27: C++ publish   copy

Expressions with char variableWhen char is used in an expression, its ASCII number equivalent is taken.Examplechar 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

Exercise1. 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

b. A is greater than 0 and less than 100c. Grade is A or Bd. Increment the value of X by 20

3. Find the output for the following code snippetsa. 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 IX26

Priya Kumaraswami

Page 28: C++ publish   copy

Notes

CS WORKBOOK IX27

Priya Kumaraswami

Page 29: C++ publish   copy

Chapter – 6

Input and OutputThe output operation is already illustrated in Chapter 2 – “First Program in C++”. A recap of the same is given below.

Output using coutcout is used along with the insertion operator, which is written as << (two "lesser than" signs).

cout << "Output sentence"; // prints Output sentence on screencout << 120; // prints number 120 on screencout << 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"; // prints Hellocout << 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.

cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;

CS WORKBOOK IX28

Priya Kumaraswami

Page 30: C++ publish   copy

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 90064It 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. 

Input using cin

CS WORKBOOK IX29

Priya Kumaraswami

Page 31: C++ publish   copy

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.Exampleint 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; 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.

CS WORKBOOK IX30

Priya Kumaraswami

Page 32: C++ publish   copy

Exercise1. 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 numbersc. 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)

CS WORKBOOK IX31

Priya Kumaraswami

Page 33: C++ publish   copy

Notes

CS WORKBOOK IX32

Priya Kumaraswami

Page 34: C++ publish   copy

CS WORKBOOK IX33

Priya Kumaraswami

Page 35: C++ publish   copy

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• 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.

CS WORKBOOK IX34

Priya Kumaraswami

Page 36: C++ publish   copy

Operators used in conditions• >, <, >=, <=, ==, !=, &&, ||, !

• Examplesgrade == ‘A’a > b!xx >=2 && x <=10grade == ‘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• Also called conditional or decision statement• Syntax of if statement

if ( condition )statement ;

CS WORKBOOK IX35

Priya Kumaraswami

Page 37: C++ publish   copy

• 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;

• If x value is 100, x is 100 will be printed.• 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.

CS WORKBOOK IX36

Priya Kumaraswami

Page 38: C++ publish   copy

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 ; // Note the tab space

else statement2 ; // 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) 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.

CS WORKBOOK IX37

Priya Kumaraswami

Page 39: C++ publish   copy

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 positive"; cout << “ and its value is “ << x ;}else if (x < 0){ cout << "x is negative"; cout << “ and its absolute value is “ << -x ;}else{ cout << "x is 0"; cout << “ and its value is “ << 0 ;}

Points to remember

• If there is only one statement for ‘if’ and ‘else’, no need to enclose them in curly braces { }

• Exampleif ( grade == ‘A’)

cout << “Good grade”;else cout << “Should improve”;

• In an if statement, DO NOT put semicolon in the line having test conditionif ( y > max) ; if the condition is true, only null

statement will be executed.{

max = y;}

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.

CS WORKBOOK IX38

Priya Kumaraswami

Page 40: C++ publish   copy

if (condition 1){if (condition 2) statement 1;else statement 2;}elsestatement 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;}

• Syntax

Dangling else problem

• Which if the else belongs to, in the above case?• The else goes with the immediate preceding if

if ( ch >= ‘A’)if(ch <= ‘Z’) upcase = upcase + 1;

elseothers = others + 1;

CS WORKBOOK IX39

Priya Kumaraswami

Page 41: C++ publish   copy

• The above code can be understood as shown below

• If the else has to be matching with the outer if, then use brackets { } as below

Difference between if…else if ladder and multiple ifs

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.

if ( ch >= ‘A’) {

if(ch <= ‘Z’) upcase = upcase + 1;

}else

others = others + 1;

if ( ch >= ‘A’){

if(ch <= ‘Z’) upcase = upcase + 1;

else others = others + 1;

}

int a = 10;if( a >= 0) cout << a;else if ( a >= 5) cout << a + 5;else if (a >= 10) cout << a + 10;else cout << a + 100;

int a = 10;if( a >= 0) cout << a;if ( a >= 5) cout << a + 5;if (a >= 10) cout << a + 10;else cout << a + 100;

CS WORKBOOK IX40

Priya Kumaraswami

Page 42: C++ publish   copy

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 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.

switch (expression){ case constant1:

statements;break;

case constant2:statements;break;

default:statements;

}

CS WORKBOOK IX41

Priya Kumaraswami

Page 43: C++ publish   copy

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;

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”;

CS WORKBOOK IX42

Priya Kumaraswami

Page 44: C++ publish   copy

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• 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()

CS WORKBOOK IX43

Priya Kumaraswami

Page 45: C++ publish   copy

{int x;cout << “Enter the mark”;cin >> x;if (x >= 40){ cout << “Pass J” ;}else{

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”;

CS WORKBOOK IX44

Priya Kumaraswami

Page 46: C++ publish   copy

grade = ‘N’;}cout << “The grade for your mark is” << grade;

}

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.

CS WORKBOOK IX45

Priya Kumaraswami

Page 47: C++ publish   copy

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

int n , r;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){

case 2:

CS WORKBOOK IX46

Priya Kumaraswami

Page 48: C++ publish   copy

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;

} }

Exercise

CS WORKBOOK IX47

Priya Kumaraswami

Page 49: C++ publish   copy

1. Find the output for the following code snippetsa. 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’: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;

CS WORKBOOK IX48

Priya Kumaraswami

Page 50: C++ publish   copy

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 = 5when a = 9 and b = 3when 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 << aelse ( 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”;

elsecout << “improve”;

}else if( m1 >= 40){

if( m2 >= 80)cout << “Good”;

else if (m2 >= 40)cout << “Fair”;

elsecout << “improve”;

}

CS WORKBOOK IX49

Priya Kumaraswami

Page 51: C++ publish   copy

else{

if( m2 >= 80)cout << “Good”;

else if (m2 >= 40)cout << “improve”;

elsecout << “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 ChargesUpto 100 units Rs 1.35 / unit> 100 units and upto 200 units

Rs 1.50 / unit

> 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

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

CS WORKBOOK IX50

Priya Kumaraswami

Page 52: C++ publish   copy

Notes

CS WORKBOOK IX51

Priya Kumaraswami

Page 53: C++ publish   copy

Chapter – 8

LoopsA 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;

The statement can be simple or compound.

CS WORKBOOK IX52

Priya Kumaraswami

Page 54: C++ publish   copy

• 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 -3.So 10 7 4 1 get printed.

• Example 3

for (int c= 10; c >= 1; c=c-2){

cout << ‘*’;}

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)

CS WORKBOOK IX53

Priya Kumaraswami

Page 55: C++ publish   copy

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 loopNull statement in a loopfor (a= 10; a >= 0; a=a-3); Note the semicolon herecout << a;

This means the null statement gets executed repeatedly. cout << a; is independent.

Multiple initialization and update in a for loopfor (int a= 1, b = 5; a <= 5 && b >= 1; a++, b--)cout << a << “ “ << b << endl;

The output of the above code will be1 52 43 3

CS WORKBOOK IX54

Priya Kumaraswami

Page 56: C++ publish   copy

4 25 1

Note:for(int c = 0; c < 5; c++) correctfor(int c = 0; c < 5; c=c++) wrongfor(int c = 0; c < 5; c=c+2) correctfor(int c = 0; c < 5; c+2) 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 expressionwhile (test expression)Loop body containing update expression

• Example 1

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;

CS WORKBOOK IX55

Priya Kumaraswami

Page 57: C++ publish   copy

}

This code prints 10 to 0 with a step of -3.So 10 7 4 1 get printed.

Variations in while loopInfinite 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 2int a= 10;while (a >= 0){

cout << a; }

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 loopint a= 1, b = 5; while (a <= 5 && b >= 1){

cout << a << “ “ << b << endl; a++;b--;

}

The output of the above code will be1 52 43 34 2

CS WORKBOOK IX56

Priya Kumaraswami

Page 58: C++ publish   copy

5 1

Quick Comparison of for and while

for loop syntax

while loop syntax

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;}

}

CS WORKBOOK IX57

Priya Kumaraswami

Page 59: C++ publish   copy

Here, the i loop has j loop inside. For each i value, the j value ranges from 2 to 4.

i value j value outputi = 1 j = 2 1

j = 3 3j = 4 4

i = 2 j = 2 4j = 3 6j = 4 8

i = 3 j = 2 6j = 3 9j = 4 12

• Example 2

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 j value k value outputi = 1 j = 3 k = 5 15

k = 6 18j = 4 k = 5 20

k = 6 24i = 2 j = 3 k = 5 30

k = 6 36j = 4 k = 5 40

k = 6 48

• Example 3

for(int i= 1; i<=2; i++)

CS WORKBOOK IX58

Priya Kumaraswami

Page 60: C++ publish   copy

{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 j value k value outputi = 1 j = 3 3

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

i = 2 j = 3 6j = 4 8

k = 5 10k = 6 12

In the syllabus, we learn to use nested loops for printing

• Tables• Patterns

Jump StatementsWe 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.

Examplefor(int c = 9; c < 30; c = c + 2){

if(c%7 == 0)

CS WORKBOOK IX59

Priya Kumaraswami

Page 61: C++ publish   copy

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 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;

}}

CS WORKBOOK IX60

Priya Kumaraswami

Page 62: C++ publish   copy

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;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.

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

for (int i = 1 ; i <= 5; i++){

for (int j = 1 ; j <= i; j++)cout << j;

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

112123123412345

CS WORKBOOK IX61

Priya Kumaraswami

Page 63: C++ publish   copy

cout << endl;}

}

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(){

}

AABABCABCDABCDE

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

CS WORKBOOK IX62

Priya Kumaraswami

Page 64: C++ publish   copy

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 IX63

Priya Kumaraswami

Page 65: C++ publish   copy

}

8.9 Program to print the pattern.

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

}

8.10 Program to print the pattern.

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

1 121 123211234321

2 242 246422468642

CS WORKBOOK IX64

Priya Kumaraswami

Page 66: C++ publish   copy

}8.11 Program to print the pattern.

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

}

8.12 Program to print the pattern.

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

2468642 24642 242 2

$$$$$$ $$ $$ $$$$$$

CS WORKBOOK IX65

Priya Kumaraswami

Page 67: C++ publish   copy

}8.13 Program to print the pattern.

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

}

Exercise1. Find the outputs

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;

$$$$$$&&&$$&&&$$&&&$$$$$$

CS WORKBOOK IX66

Priya Kumaraswami

Page 68: C++ publish   copy

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 programsa. To print the odd number series till 999b. To print the sum of natural numbers from 1 to 100c. To print the factorial of a given numberd. To check whether a number is prime or note. to generate the Fibonacci and Tribonacci seriesf. to accept 10 numbers and print the minimum out of

themg. to print the following patterns

123451234123121

543214321321211

122333444455555

555554444333221

121321432154321

1 131 135311357531

1357531 13531 131 1

%%%%%%%% %% %%%%%%%%

1123123451234567

CS WORKBOOK IX67

Priya Kumaraswami

Page 69: C++ publish   copy

Notes

CS WORKBOOK IX68

Priya Kumaraswami

Page 70: C++ publish   copy

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.

CS WORKBOOK IX69

Priya Kumaraswami

Page 71: C++ publish   copy

Declaration of an arraydatatype arrayname [size];Exampleint 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.

Calculation of bytesThe memory occupied by an array is calculated as size of the element x number of elements

CS WORKBOOK IX70

Priya Kumaraswami

Page 72: C++ publish   copy

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 outputUsually, 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++) // input loop

cin >> a[i];

for(i = 0; i < 6; i++) // processing loopa[i] = a[i] * 2;

for(i = 0; i < 6; i++) // output loopcout << a[i];

Combining the input and processing loopsint 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++) // output loopcout << a[i];

Note: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;

CS WORKBOOK IX71

Priya Kumaraswami

Page 73: C++ publish   copy

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++) // output loopcout << a[i];

OperationsThe 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 IX72

Priya Kumaraswami

Page 74: C++ publish   copy

}

9.2 Program to sum up all the elements.

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

}

9.3 Program to find the max and min in the given array.

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

CS WORKBOOK IX73

Priya Kumaraswami

Page 75: C++ publish   copy

}

9.4 Program to replace an element.

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

CS WORKBOOK IX74

Priya Kumaraswami

Page 76: C++ publish   copy

}

9.5 Program to reverse the array.

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

}

9.6 Program to swap the first half with the second half.

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

CS WORKBOOK IX75

Priya Kumaraswami

Page 77: C++ publish   copy

}

9.7 Program to swap the adjacent elements.

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

}

9.7 Program to search for a given element using flag.

CS WORKBOOK IX76

Priya Kumaraswami

Page 78: C++ publish   copy

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

}

Exercise1. Fill in the blanksThe 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;

CS WORKBOOK IX77

Priya Kumaraswami

Page 79: C++ publish   copy

int count = 0;

for(__________________________){

if(____________)count++;

}

if(count ______)cout << “found in the array”;

elsecout << “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 30c. A float array of size 50

3. Write Programsa. To count the number of elements divisible by 4 in

the given array of size 20b. To sum up the even elements in the array of size 10c. To combine elements from arrays A and B into array C

Notes

CS WORKBOOK IX78

Priya Kumaraswami

Page 80: C++ publish   copy

Chapter – 10

Char ArraysChar 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 arraychar arrayname [size];Examplechar A [8];

• We give the arrayname and it has to follow the rules of naming the variables.

CS WORKBOOK IX79

Priya Kumaraswami

Page 81: C++ publish   copy

• 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 stringInput 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);

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>

CS WORKBOOK IX80

Priya Kumaraswami

Page 82: C++ publish   copy

char array not as a stringInput 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 FunctionsWe 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• toupper() to convert to uppercase• isalpha() to check if the char is alphabet• isdigit() to check if the char is digit• isalnum() to check if the char is alphanumeric

Usage of ctype.h functions

char ch;cin >> ch;if(islower(ch))if(isupper(ch))

CS WORKBOOK IX81

Priya Kumaraswami

Page 83: C++ publish   copy

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 lengthif(strcmp(s, c) == 0) // if s and c are equal, it

will give 0strcpy(s, c); //copies c to sstrcat(s, c); //Joins s and c and stores in s

char manipulation inside the loopAll character manipulations take place inside the loop.Example

char arr[40]; // declare char array of required sizegets (arr); // take input for char arrayint 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

}

CS WORKBOOK IX82

Priya Kumaraswami

Page 84: C++ publish   copy

OperationsThe 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” //for cout and cin#include “string.h” //for strlen()#include “stdio.h” //for gets() and puts()#include “ctype.h” //for char functions(isupper()etc)void main(){

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

CS WORKBOOK IX83

Priya Kumaraswami

Page 85: C++ publish   copy

10.3 Program to take a string as input and replace a given char with another char

CS WORKBOOK IX84

Priya Kumaraswami

Page 86: C++ publish   copy

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

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

CS WORKBOOK IX85

Priya Kumaraswami

Page 87: C++ publish   copy

Exercise1. Find the output

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]);

elseif (isupper(msg[i]))if( i % 2 != 0)

msg[i] = tolower (msg[i-1]);else

msg[i]=msg[i-1];

CS WORKBOOK IX86

Priya Kumaraswami

Page 88: C++ publish   copy

}cout << msg << endl;

2. Write Programsa. To convert the vowels into upper case in a stringb. To replace all ‘a’s with ‘e’s (consider case)c. To count the number of digits and alphabet in a

stringd. To find the longest out of 3 strings

Notes

CS WORKBOOK IX87

Priya Kumaraswami

Page 89: C++ publish   copy

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); Function Prototype

int main( ){

int a, b, c, d, e, f;cin >> a;cin >> b;c = calculateresult (a, b); Function call 1cin >> d;cin >> e ;f = calculateresult (d, e); Function call 2cout << f;return 0;

}

CS WORKBOOK IX88

Priya Kumaraswami

Page 90: C++ publish   copy

int calculateresult (int p, int q){

int r;r = p + q + (p * q); Function Definitionreturn r;

}

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

ReturnDatatype functionname ( datatype arg1, datatype arg2, ……) ;

ReturnDatatype denotes the datatype of the return value from the function, if any. If the function is not

CS WORKBOOK IX89

Priya Kumaraswami

Page 91: C++ publish   copy

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• Function definition is just like Prototype declaration

except that it has body and it does not have a semicolon

• 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, ……)

CS WORKBOOK IX90

Priya Kumaraswami

Page 92: C++ publish   copy

{

return ____ ; }

if the ReturnDatatype is void

void functionname ( datatype arg1, datatype arg2, ……) {

return; // This is optional}

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;

CS WORKBOOK IX91

Priya Kumaraswami

Page 93: C++ publish   copy

}

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;

}

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. float ans = func (a, b );2. int res = demo (x);3. test (m, n, p);4. int val = example ();

CS WORKBOOK IX92

Priya Kumaraswami

Page 94: C++ publish   copy

Possible Function Styles1. Void function with no arguments2. Void function with some arguments3. Non void function with no arguments4. Non void function with some arguments

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>

CS WORKBOOK IX93

Priya Kumaraswami

Page 95: C++ publish   copy

long power (int a, int b); //Function Prototypevoid main(){

int n1, n2;cin >> n1 >> n2;long p = power (n1, n2); //Function Callcout << p;

}

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 IX94

Priya Kumaraswami

Page 96: C++ publish   copy

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)

CS WORKBOOK IX95

Priya Kumaraswami

Page 97: C++ publish   copy

11.5 Program to print the multiplication table of a given number upto x 20 using a function

11.6 Program to check whether a given number is prime using a function

CS WORKBOOK IX96

Priya Kumaraswami

Page 98: C++ publish   copy

11.7 Program to find the max in an int array of size 20 using a function

Exercise1. 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);m = m + p;p = calc (n, m);n = n + p;cout << m << “ “ << n << “ “ << p;

CS WORKBOOK IX97

Priya Kumaraswami

Page 99: C++ publish   copy

}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;

}}

}

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);

CS WORKBOOK IX98

Priya Kumaraswami

Page 100: C++ publish   copy

cout << r;}

void demo ( int a ; int b);{

p = p + 10;q = q – 10;r = p + q;return r;

}

3. Write Programs using functionsa. To find a3 + b3 given a and bb. To convert the height of a person given in inches to

feetc. To print the sum of odd numbers in a given int arrayd. To convert the cases of a char array

CS WORKBOOK IX99

Priya Kumaraswami

Page 101: C++ publish   copy

Notes

CS WORKBOOK IX100

Priya Kumaraswami

Page 102: C++ publish   copy

Worksheet - 1(C++ Datatypes, Constants, Variables, Operators, Input and Output)

1. Match the followinga. An integer constant int a;b. A floating point

constant“c++”

c. A char constant C = 20;d. A string (char array)

constant9.5

e. A variable declaration ‘n’f. A variable

initialization100

2. Give examples of your own fora. An integer constantb. A floating point

constantc. A char constant

d. A string (char array) constant

e. A variable declarationf. A variable

initialization3. List the basic data types in C++ and explain their ranges.4. Identify constants, variables and data types in the following

statements.a. int a = 10;b. char c = ‘d’;c. cout << c << “alphabet”;

d. cin >> d;e. float f = 3.45;f. double d = m;

5. Find the mistakes in the following C++ statements and write correct statements.

a. int a = 10,000;b. char c = “f”;c. char ch = ‘go’;d. cin >> “g”;

e. cout << the result is << “k”;

f. cout << a(b+c);g. float f$ = 5.49;h. int k = 40,129;

6. Identify the valid and invalid variables from the following giving reasons for invalid ones

a. int My num;b. int my_num;c. int my-num;d. int 1num;

e. int num1;f. int main;g. int Main;

7. Write C++ expressions (applying BODMAS)a. a2bb. 2abc. pnr/100d. a2 + 2ab + b2

e. sum =

n(n+1 )2

f. k =

a2+2abn−b

g. z = ab +

13 (x – y)2

8. Write C++ statements for the followinga. Initialize a variable c with value 10b. Take an integer as input in variable kc. Print a floating point variable fd. Print a string constant “Programming is fun”e. Print a string constant “Result” and an integer constant 10f. Print a string constant “Result” and an integer variable x

CS WORKBOOK IX101

Priya Kumaraswami

Page 103: C++ publish   copy

g. Take 2 numbers as input and find their squares and print them with proper messages

9. 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

numbersc. Interchange the values of 2 variables using a third variabled. To accept temperature in degree Celsius and convert it to

degree Fahrenheit (F = 9/5 * C + 32)10. Evaluate the following if a = 88, b = 101, c = 34

a. b = (b++) + c;a = a – (--b);c = (++c) + (a--);

b. a * b / c + 10c. a / 2 + b * b + 3 * cd. a * b – a / b + c * 2e. a = b + 20;

c = (a++) + 10;b = b – (--a)

11. Find the output of the following

12. Find the mistakes in the following code sample

13. Fill in the blanks14. List the types of operators.15. Give examples of unary and binary operators.

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

int s = 75;int ____ = 100;____ t = 85;int tot = ___ + m + t;int a = tot / 3;cout << “total is “ << ___ ;cout << “avg is “ << ____ ;

}

#include <iostream.h>void main{

int k;k = k + 10;p = p + 20;cin >> “k”;cin >> 10;cout << “k + p”;cout << hello;

}

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

int x = 9, y = 99, z = 199;cout << x + 7 << endl;x = x + y;cout << “random” << y + z;cout << z % 8;

}

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

int p = 20;int q = p;q = q + 3;p = p + q;cout << p << “ “ << q;

}

CS WORKBOOK IX102

Priya Kumaraswami

Page 104: C++ publish   copy

Worksheet – 2 (if..else)1. Write ‘if’ statements for the following

a. To check whether the value of int variable a is equal to 100b. To check whether the value of int variable k is between 40

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

50e. To check whether the value of a char variable ch is equal to

‘lowercase a’ or ‘uppercase a’2. Find the output of the following

a. int i = j = 10;if ( a < 100)if( b > 50)i = i + 1;elsej = j + 1;cout << i << “ “ << j ;Value supplied for a and b a = 30, b = 30Value 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 = 30Value supplied for a and b a = 60, b = 70

c. if (!3){

cout << “Tricky”;}cout << “Yes”;

d. if ( 3 )

cout << “Tricky again”;else

cout << “Am I right?”;cout << “No??”;

e. if ( 0 )

cout << “Third Time Tricky”;cout << “Am I right?”;

CS WORKBOOK IX103

Priya Kumaraswami

Page 105: C++ publish   copy

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.

4. Write complete C++ programs using if constructa. To find the largest and smallest of the given 3 numbers A,

B, Cb. 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 notd. To convert the Fahrenheit to Celsius or vice-versa depending

on the user’s choicee. To create a four function calculator ( +, -, /, *)f. To calculate the commission rate for the salesman. The

commission is calculated according to the following ratesSales Commission Rate30001 onwards 15%22001 – 30000 10%12001 – 22000 7%5001 – 12000 3%0 – 5000 0%

5. Illustrate Nested If with examples

int b;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” ; cout << “Hurray…We can provide bats to the opponents also” ;

a)

CS WORKBOOK IX104

Priya Kumaraswami

Page 106: C++ publish   copy

Worksheet – 3 (switch)1. Convert the following ‘if’ construct to ‘switch’ construct

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”;elsecout << “Invalid grade”;

2. Find the output of the followingint 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.

3. Find the mistakes and correct them.

4. Write complete C++ programs using switch constructa. To display the day depending upon the number (example, if 1

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 9c. To calculate the area of a circle, a rectangle or a triangle

depending upon user’s choice5. Convert the following ‘if’ construct to ‘switch’ construct

int a; char b;

int b;cin >> b;switch (b){ case ‘10’;

cout << “Number of bats = 10” ;break;

case ‘10’:cout << “Number of bats = 15” ;

case ‘20’cout << “Number of bats = 20” ;

}

CS WORKBOOK IX105

Priya Kumaraswami

Page 107: C++ publish   copy

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”;}

6. Find the output of the following if a gets values 0, 1 and 2 in three consecutive runs.int a; cin >> a;switch (a){

default:cout << 'd';

case 0:cout << 0;

case 1:cout << 1;

}7. 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 IX106

Priya Kumaraswami

Page 108: C++ publish   copy

}

CS WORKBOOK IX107

Priya Kumaraswami

Page 109: C++ publish   copy

Worksheet – 4 (Loops)1. Write a program to print tables of 3,6,9,….n upto x15 ( multiplied

by 15)2. Write Programs to print the following patterns using nested loops

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 c = 0; c <= 10; c++){

if(c == 4) break;else cout << c;

( * * * * * ) ( * * * ) ( * )

2 242 246422468642

12345678910

131531753197531

113135135713579

& &$& &$$$& &$$$$$&&$$$$$$$&

975317531531311

CS WORKBOOK IX108

Priya Kumaraswami

Page 110: C++ publish   copy

}cout << c;

7. Convert the following nested for loops to nested while loops and find the outputfor(int i=0; i<5;i++){

for(int j=1;j<3;j++){

if( i != j)cout << i * j;

}}

8. Explain the steps and find the output.

9. What will be the output?a. for (int c = 0; c <= 10; c++); cout << c; cout << c;b. for (int c = 0; c <= 10; c++) cout << c; cout << c;c. for (int c = 0; c <= 10; c++) { cout << c; cout << c; }d. for (int c = 0; c <= 10; c++) { cout << c; } cout << c;

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?

int num = 12345;int d;int s = 0;while (num != 0){

d = num % 10;cout << d << endl;s = s + d;num = num / 10;

}cout << s;

int a = 5, b = 15;

if ( (a + b) % 2 == 0){

b = b % 10;a = a + b;cout << a << “ “ << b << endl;

}if ( a % 10 == 0){

switch(a){

case 10:cout << “AA”;

case 20:cout << “BB”

}}

CS WORKBOOK IX109

Priya Kumaraswami

Page 111: C++ publish   copy

Worksheet – 5

Function related Programs1. 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 Programs3. Write a C++ program to convert the string given as input as

specified belowa. 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 DnlotsdqInteger / 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 = 40Output 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 contains3, 4, 5, 16, 9then the array should be rearranged as6, 2,10,8, 18

Find the output of the following code snippets7. void main()

{int AY[5]={5,10,15,20,25};int loop = 5;for(int m=0; m<loop ;m++){

switch (m){ case 0:

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

}}

}

CS WORKBOOK IX110

Priya Kumaraswami

Page 112: C++ publish   copy

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};

int total=0;for(int I=0; I<5; I++){

if(stock[I]>15)total+=stock[I];

}cout<<total;

10. 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”;

}11. void arm(int n)

{int number, sum=0,dg,dgg,digit;number=n;while(n>0){

dg=n/10;dgg=dg*10;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 IX111

Priya Kumaraswami

Page 113: C++ publish   copy

}

CS WORKBOOK IX112

Priya Kumaraswami