Class 8 Computer Science Booklet 2021-2022
Class 8 Computer Science Booklet 2021-2022
Class 8 Computer Science Booklet 2021-2022
2021-2022
C++ INDEX
1 INTRODUCTION TO C++ 3
REVISION WORKSHEET 1 40
SAMPLE PAPERS 42
REVISION WORKSHEET 2 50
2 RELATE 60
3 PURPOSE 67
4 POSSIBILITIES 73
5 AI ETHICS 80
2
CHAPTER-1:
INTRODUCTION TO C++ LANGUAGE
1.1 INTRODUCTION
Learning C++ language is very interesting and challenging. It supports both procedural and object oriented
programming (OOP). Now, let us dive into the sea of C++!!!
Industrial Applications of C++: Used in games, operating systems, graphics and video editors, office
applications.
Blank spaces may be inserted between two words to improve the readability of the statement. (c)However, no
blank spaces are allowed within a variable, constant or keyword.
(d) All statements are entered in small case letters.
(e) C++ has no specific rules for the position at which a statement is to be written. That’s why it is often called a
free-form language.
(f) Every C++ statement must end with a ;. Thus ; acts as a statement terminator.
Example Program-1:
Program to print “Welcome”.
Alphabets A, B, ….., Y, Z
a, b, ……, y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols ~‘!@#%^&*()_-
+=|\{}
[]:;"'<>,.?/
1.7 OPERATORS:
The following tokens are the operators used in C++:
+ - * / % >
< >= <= = == !=
&& || += -= *= /=
%= ++ --
4
1.8 SPECIAL SYMBOLS:
The following are used as special symbols in our coding like ( ) { } [ ] < >.(Refer to C++ character set)
int
- Used to define integer numbers. The size of integer varies as
16-bit machine (2 bytes) and 32 bit machine (4 bytes).
char
- Used to define single character or a sequence of characters called string. The size of char is
fixed as 16-bit machine / 32 bit machine (1 byte)
float
- Used to define floating point or real numbers. The size of float varies as
16-bit machine (4 bytes) and 32 bit machine (8 bytes).
1.10 VARIABLES/IDENTIFIERS
In programming, a variable is a container (storage area) to hold data. To indicate the storage area, each
variable should be given a unique name (identifier). Variable names are just the symbolic representation of a
memory location. For example: int age=95;
Here age is a variable of integer type. The variable is assigned a value: 95.
The value of the variable can be changed, hence the name ‘variable’.
In C++ programming, you have to declare a variable before you can use it.
C++ Variables
In any language, the types of variables that it can support depend on the types of constants that it can
handle. This is because a particular type of variable can hold only the same type of constant. For example, an
integer variable can hold only an integer constant, a real variable can hold only a real constant and a character
variable can hold only a character constant.
The rules for constructing different types of constants are different. However, for constructing variable names of
all types the same set of rules apply. These rules are given below.
Rules for Constructing Variable Names
A variable name can be a combination of alphabets, digits or underscores
Maximum length of the variable name can be 31 characters (some compilers allow up to 247
characters)
The variable names can be as short as a single character.
The first character in the variable name must be an alphabet or an underscore (_).
Variable name should not be a reserved word.
No blank spaces are allowed within a variable name.
No special symbol other than an underscore (as in gross_sal) can be used in a variable name.
For example:
int p , n ,r ;
float si;
The variables p , n , r are integer variables and si is float variable.
Initialization of variables
An initial value may be specified in the definition of a variable.
Ex: int r =4; char x= ‘A’; float w =3.2;
Dynamic initialization
The expression after evaluating, initializes a variable is called dynamic initialization.
Ex: int a =8 , b = 9 ;
int c = a + b ;
The variable c is dynamically initialized to the sum of a and b (8+9 =17).
6
auto double inint ststruct
break else long switch
case e enum register tytypedef
char extern return union
c const float short unsigned
continue for signed void
default g goto sizeof volatile
do if static while
We have already learnt about variables, constants, operators and special symbols.
1.13 CONCEPT OF STREAMS IN C++
The iostream library provides input and output functionality using streams. A stream can basically be considered
as a source or destination of characters of varying length. Every C++ compiler provides a standard library to
support predefined input and output functions which we use in our program. To use those functions we need to
include some files at the beginning of each program with its extension .h. The most commonly used header file is:
STREAM
The #include directive gives directions to the compiler to place specified header files at the beginning of the
program during compilation.
Example: #include<iostream.h>
Sample Program-2
Program to add the numbers 10 and 5
#include<iostream.h>
void main( )
{ Declaration of variables
int a, b, c ;
Initialization of variables
a = 10;
b= 5;
Dynamic Initialization
c = a + b;
Printing the output
cout << “sum=” << c;
1.14 STRUCTURE
} OF A C++PROGRAM
7
The general structure of a C++ program is shown below:
Every C++ program has a primary (main) function that must be named main. The main function serves as the
starting point for program execution. It usually controls program execution by directing the calls to other
functions in the program. All statements that belong to main( ) are enclosed within a pair of braces { } as shown
below.
main( )
{
statement 1 ;
statement 2 ;
}
8
Example Program-3
#include <iostream.h>
/* Calculation of simple interest */
// Date: 25/05/2004
main( )
{
int p, n ; float r, si ;
p = 1000 ;
n=3;
r = 8.5 ;
/* formula for simple interest */
si = p * n * r / 100 ;
cout < < “simple Interest is: “ < < si;
}
9
Parts of C++ Editor window
10
1.18 ESCAPE SEQUENCE CHARACTERS
It begins with backslash and is followed by one character.it give rise to special print effects.
Character Escape Meaning
character
Horizontal tab \t Cursor moves right by 8
positions
Newline character \n Move the cursor next line.
The backslash constants are also called character constants and are non-printable characters.
Example program 4
Program to print a character
#include<iostream.h>
main( )
{ Declaration of variables as characters.
char alphabet1,alphabet2,alphabet3; Command to clear the screen.
clrscr( );
alphabet1= ‘d’;
alphabet2= ‘p’;
alphabet3= ‘s’;
cout < < alphabet1 < < alphabet2< <alphabet3; Printing characters
}
Example program 5
Program using escape sequence characters
#include<iostream.h>
main( )
.
{
char ch1,ch2,ch3;
clrscr( );
ch1= ‘d’; Note this
ch2= ‘p’;
ch3= ‘s’; Use of newline character \n.
cout < < ch1 < < “\n” < < ch2 < < “\n” < < ch3; Use \t and \b instead of \n
}
11
ostream: This is one of the output stream class. It adds put ( ) and write ( ) functions. It contains the
overloaded operator < <, called stream insertion operator, to write data from memory variables to
standard output devices (screen/monitor)
o The cout object: The cout (see-out) object sends to the standard output device, which is the screen.
Following is the format of the cout command:
cout < < data [ < < data]
The data can be variables, constants, expressions etc. The operator < < is used as output redirection
and called as put to operator.
istream: This is one of the input stream class.It adds get ( ), getline( ) and read( ) functions. It contains the
overloaded operator > >, called stream extraction operator, to read data from a standard input device
(keyboard) and assign to memory variables.
o The cin object: The cin (see-in) object gets input from the keyboard. Following is the format of the
cin command:
cin > > variablename [ > > variablename >> ..]
Both the ‘istream’ and ‘ostream’ are included in the ‘iostream.h’ header file. Hence it is necessary to include
the header file at the beginning of the program.
Example program 6
Program to accept any 2 numbers and add them
#include<iostream.h>
main( )
{
int a, b, sum;
cout < <“Enter two numbers”;
cin > > a > > b;
sum = a + b;
cout < < “sum=” < < sum;
}
12
WORKSHEET 1.1
I. 1) Do you agree that there is a close analogy between learning English language and learning C++
language?
ENGLISH LANGUAGE
Alphabets Words Sentences Paragraphs
C++ LANGUAGE
Digits
Special symbols
Tokens
14
WORKSHEET 1.2
II. Complete the C++ program to find area of a triangle given base and height :
#include <iostream.h>
main ( )
{
float base, height, area;
// Reads base and height of the triangle from user
cout < <______________________ ;
cin > >_____________________;
cout < <_________________________;
cin > >______________________;
// Calculates area of a triangle
area = (base * height) / 2;
cout < <_____________________________________________________;
return 0;
}
III. WRITE THE OUTPUT & EXPLANATION FOR THE FOLLOWING CODE
#include <iostream.h>
void main( )
{
int y = 10000;
y = 34;
count < < "Hello World!” < < y < <” \n";
}
Output: _______________________________________________________
Explanation: _________________________________________________________________
IV. Assignment:
1)
int c, a=8, b=10;
c=a+b;
V. Lab Activity:
Write C++ programs for the following:
1) To print the area of a rectangle by asking the user to enter the length and the breadth
( Given a = l * b)
2) To perform all arithmetic operations on any 2 numbers entered by the user.
3) To find the quotient and remainder of two numbers entered by the user.
4) To find the simple interest by asking the user to enter the principal, rate of interest and number of
years.(given si = p*r*t /100)
5) To convert km to m, feet and inches. The output must come one below the other. The command to
clear the screen must be used.
Given: m= km *1000;
Feet= km* 3280.84; inches= km * 39370.1;
16
CHAPTER 2:
OPERATORS AND EXPRESSIONS
2.1 Introduction:
An operator is a symbol that specifies the operation to be performed. For example + is to add , * is to multiply and
so on. The types of operators are as ,
ARITHMETIC OPERATOR
Operation Symbol
Multiply *
Divide /
Find remainder %
Add +
Subtract -
RELATIONAL OPERATOR
The relationship between 2 operands results in true or false.
Operation Symbol
Less than <
Greater than >
Greater or equal to >=
Lesser or equal to <=
Equal to ==
Not equal to !=
LOGICAL OPERATOR
ASSIGNMENT OPERATOR
It is used to copy the data or result of an expression into a memory location (which is identified by
a variable name) is called an assignment operator and is denoted by = sign. Ex a = 10
Also assigning a value or a set of values to different variables in one statement is called multiple
assignment statement.
Ex: i= j =k =20;
17
Short hand Short hand Meaning Explanation
operator statements
+= a +=2 a = a+ 2 Perform a+2 and store the
result in a
-= a-=2 a=a-2 Perform a-2 and store the
result in a
*= a*=2 a=a*2 Perform a*2 and store the
result in a
/= a/=2 a=a/2 Perform a/2 and store the
result in a
2.2 Expression:
An expression is a combination of operands, operator and constants. In the expression a+b , a and b are operands
and + is the operator.The operands can hold integer ,floating values.
Based on the type of the operands in the expression,there are 3 modes of expressions namely,
Integer Expressions 4/ 2 = 2
4/3 = 1
3/4 = 0
18
2.3 OPERATOR PRECEDENCE
It determines the order in which expressions are evaluated,so you can predict the output for the given
values.For ex,
Y= 6+4/2
Here, 4/2 is evaluated i.e 2 and it is added with 6.So the result is 8.In general , the precedence is as
follows.
Operator Associativity
() Left to Right
++ -- Right to left
* / % Left to Right
+ - Left to Right
<> <= >= Left to Right
== != Left to Right
&& Left to Right
|| Left to Right
= += -= *= /= %= Right to Left
Example: Determine the hierarchy of operations and evaluate the following expression:
i=2*3/4+4/4+8-2+5/8
Stepwise evaluation of this expression is shown below:
i=2*3/4+4/4+8-2+5/8
i=6/4+4/4+8-2+5/8 operation: *
i=1+4/4+8-2+5/8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i=1+1+8-2+0 operation: /
i=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
i=8 operation: +
Note that 6 / 4 gives 1 and not 1.5. This so happens This so happens because 6 and 4 both are integers and
therefore would evaluate to only an integer constant. Similarly 5 / 8 evaluates to zero, since 5 and 8 are integer
constants and hence must return an integer value.
19
WORKSHEET 2.1
LESSON – 2: OPERATORS
Expression Solution
1.float j;
j=5.0/2.0 *4
2. int k
k= 5*8/4 +2
3. int p
p=6+3*2/2
4.float k;
k = 3.0 / 2.0 * 4 + 3.0 / 8.0 +3
5.int p ;
p = 10 / 2 * 3 + 3 /4 – 8 / 5
20
III. WRITE THE OUTPUT & EXPLANATION FOR THE FOLLOWING CODE
1)
#include <iostream.h>
Output: ________________ void main( )
{
Explanation: int i = -3;
int k = i % 2;
cout << k;
}
21
WORKSHEET 2.2
LESSON – 2: INCREMENT & DECREMENT OPERATORS
2) Output: ___________
#include <iostream.h>
Explanation: void main( )
{
int i=2;
int j =++i+ i;
cout <<"\n" << j;
}
#include<iostream.h>
void main( )
3) Output: ___________ {
int x=4, y, z;
Explanation: y = --x;
z = x--;
cout << x <<"\n" << y << “\n” << z;
}
II. Assignment:
What is the value for the following expressions.
Note: The statements are not related to each other.
int a =10;
1. cout < < a++;
23
CHAPTER 3:
DECISION CONTROL STRUCTURE
3.1 INTRODUCTION:
A statement is the smallest element of a programming language. It is used to inform the computer to perform an
action when a program is executed. The types are
a) Simple statement
i =0; /* statement 1 */
sum = 5 ; /* statement 2 */
b) Compound statement
The set of statements enclosed within a pair of braces as { and }.
{
base = 3.0 ;
height = 5 ;
}
c) Control statements
The order in which the statements are executed is called control flow. The statements that are used
to control the flow of execution of the program are called control statements. They are classified as
Branching statements
Conditional branch statements
-Simple if , if-else , nested if ,switch
Unconditional branch statements
- Goto , break , continue
Looping statements
For loop,do while
3.2 BRANCHING STATEMENTS
The statements that alter the sequence of execution of the program are called branching statements.
Normally all the statements are executed one after the other. The computer can skip the execution of some
statements based on some condition are called conditional statements.
For example: if , switch
If the user wants to transfer the control from one point to another point during execution without any condition are
called unconditional control statements.
For example: goto , break etc
It is a two–way statement which executes the different set of statements based on the given condition. The syntax
is
if (condition)
{
St-1; When given condition is true
St-2;
}
else
{
St fa1; When given condition is false
St fa1;
}
Example program 10
Program to print whether a person is eligible to vote or not
#include<iostream.h>
void main( )
{
int age;
cout << “Enter your age\n”;
cin >> age;
if (age>=18)
cout << “You are eligible to vote”;
else
cout <<“You are not eligible to vote”;
}
25
Type – II (if - else if)
if (cond1)
{ When cond1 is true
St -1; }
else if (cond2)
{
st-2; When cond1 is false and cond2 is true
}
else if (cond3)
{ When cond1 and cond2 are false and cond3 is true
st-3;
}
For ex:
Example program 11
Program to print the remarks by checking the marks
#include<iostream.h>
void main( )
{
float a;
cout << “Enter your marks”;
cin >> a;
if (a >=80 && a <=100)
cout << “Distinction”;
else if (a >=65&& a< 80)
cout <<“First Class”;
else
cout <<“Second Class”;
26
Type -I
if(cond 1)
{
if (cond2 )
{
Part -A When cond2 is true
} When cond1 is true
else
{
Part -B When cond2 is false
}
else
{
Part -C When cond1 is false
}
}
Example program 11
Program to find the greatest of the three numbers using Nested if
#include<iostream.h>
main ( )
{
int n1, n2, n3;
cout << “Enter three numbers: ”;
cin >> n1 >> n2 >> n3;
if (n1>= n2)
{
if(n1 >= n3)
cout << n1 << “ is the largest number”;
else
cout << n3 << “ is the largest number”;
}
else
{
if (n2>=n3)
cout << n2 << “ is the largest number”;
else
cout << n3 <<“ is the largest number”;
}
return 0;
}
3.3 The switch statement
It provides a way to select an alternative out of several alternatives based on the choice. The choice can be
any integer value or a character .The choice can also be an expression which results in an integer value. Based on
this , the control is transferred to a particular case value.
27
The syntax is
switch (choice/expression)
{
case value -1:
Block -1;
Break;
case value -2:
Block -2;
Break;
...
default:
Block -1;
}
Example Program 12
Program to print the menu card of an ice cream parlor and to print the price of the chosen flavor
#include<iostream.h>
void main( )
{
int choice;
cout << “Menu card\n”;
cout << “1.chocolate \n2. Vanilla \n3. Mango \n”);
cout << “Enter your choice as 1, 2 or 3”;
cin >> choice;
switch(choice)
{
case 1:
cout << “price of chocolate flavor – Rs.80”;
break;
case 2:
cout << “Vanilla – Rs.40”;
break;
case 3:
cout << “Mango flavor – Rs.60”;
break;
default:
cout <<“Invalid entry”;
}}
28
The following are valid and invalid ways of writing switch expression and case constants:
29
WORKSHEET 3.1
LESSON – 3: IF, IF-ELSE, NESTED IF
The if, if...else and nested if...else statement are used to make one-time decisions in C++
Programming, that is, to execute some code/s and ignore some code/s depending upon
the test expression.
30
3) Observe the code and answer the questions:
.....
if(num>10)
cout << “num is greater than 10”;
else
cout << “num is less than or equal to 10”;
.....
a) What is the output if num=5______________________________________
b) What is the output if num=100 ____________________________________
31
5) ASSIGNMENT
Write the syntax difference between IF-ELSE IF and IF-ELSE.
a. Any year is input through the keyboard. Write a program to determine whether the year is a leap
year or not.
b. Any integer is input through the keyboard. Write a program to find out whether it is an odd number
or even number.
c. A program to display the grade obtained by a student based on the marks. The relation between the
grades and marks is shown below:
Marks Grades
91 to 100 A
81 to 90 B
71 to 80 C
61 to 70 D
51 to 60 E
Else F
d. Any character is input through the keyboard. Write a program to check if the entered character is
uppercase or lowercase.
f. Any age is input through the keyboard. Write a program to determine if eligible to vote or not.
g. Any 2 numbers are input through the keyboard. Write a program to compare the two numbers.
32
WORKSHEET 3.2
1. If a programmer has to choose one block of statement among many alternatives, nested if...else can be used
but, this makes programming logic complex.
What is the simple and better way to do so? Also give syntax.
2. In a switch statement, what will happen if a break statement is omitted?
3. When is a “switch” statement preferable over an “if” statement? And what are its limitations
4. Rewrite the given code snippet using switch-case-break statement...
#include <iostream.h>
void main( )
{
char code = 'd';
cout <<"Enter your transaction code, d - deposit, w - withdrawal: \n";
cin >>code;
float balance = 0.0, amount = 0.0;
if(code == 'd')
{
cout << "Your deposit...\n";
balance = balance + amount;
}
else if(code == 'w')
{
cout << "Your withdrawal...\n";
balance = balance - amount;
}
else
cout << code << "code not allowed\n"; return 0;
}
SWITCH
CASE
BREAK
DEFAULT
33
LAB ACTIVITY:
1. Write a program that asks user input for an arithmetic operator ('+','-','*' or '/') and two operands and
perform the corresponding calculation on the operands.
2. Enter a Character and check whether it is Vowel or a Consonant. Use Switch case.
3. Using switch case, write a program to print the gender as male or female.
4. Write a program to check if the number entered is even or odd using switch case.
5. Write a program to check if the year is a leap year or not using switch case.
6. Write a program to read week day number and print weekday name. Use switch case.
7. Write a program to print number of days in month, given the month number as input.
8. Write a program to compare two numbers.
Assignments
1. Identify the errors and provide reasons, also write the corrected statements:
35
CHAPTER 4:
THE LOOP CONTROL STRUCTURE
4.1 INTRODUCTION
The statements that enable the programmer to execute a set of statements repeatedly until a certain condition is
reached are called Looping statements. The various types of looping statements are as,
for statement
while statement
do-while statement
Example program 9
Program to print the numbers from 1 to 5
#include<iostream.h>
void main( )
{
int i;
Now, let us see what will happen when the above for-loop is executed.
o When the for loop is executed for the first time, initial value of i=1
o The condition is i<=5 is checked and is true since i=1
o So, control enters into body of the loop and displays 1 on the screen using printf statement.
o Then i is incremented by 1 and the condition i<=5 is verified again.The loop is repeatedly executed
for i= 1,2,3,4 and 5 and all these are displayed one after the other.
o Finally, when i is 6,the condition i<=5 fails and control comes out of the loop and the message
“Out of the loop” is displayed on the screen.
The following statement shows a logical error since the loop statement ends with a ;
for (i=1 ; i<=n ; i++) ; { }
36
Worksheet-4.1
Chapter 4-The Loop Control Structure
The statements that enable the programmer to execute a set of statements repeatedly until a certain condition is
reached are called Looping statements
Based on the above code which of the following statements are Invalid and why?
a. When the for loop is executed for the first time,initial value of j=5
b. The condition is j<=20 is checked and is false since j=5.
c. Control enters into body of the loop and displays 15 on the screen using printf statement.
d. J is incremented by 1 and the condition j<=20 is verified again.
In which case will the control come out of the loop, and what output will b expected.
2. Give the syntax for the FOR loop. And explain each argument of For loop.
37
c. int i;
for (i=1; i<=3; i++)
{
cout < <"hello, World";
}
4. Debug the code given and write only the corrected statements.
1 #include <iostream.h>
void main( )
{ int i;
For (i=1: i<=10; i++)
cout << “Number: “ << i;
}
2 #include <iostream.h>
void main( )
{ int p;
for (p= =20; p>10; p-)
cout << “Number: “ << p;
}
3 #include <iostream.h>
void main( )
{ int k;
for (k=100; k=<110; k++) ;
cout << “Number: “ << k;
}
LAB ACTIVITY:
1. Write a program using for loop to print the numbers from 10 to 20.
2. Write a program to print the numbers from 50 to 40 in reverse order.
3. Write a program to find the sum of first 10 natural numbers.
4. Write a program to print the first 10 odd numbers.
5. Write a program to print the multiplication table.
38
REVISION WORKSHEET 1
Topics: Lesson 1 to 3
I. Questions:
1) Define the C++ character set.
2) Give any 3 examples of keyword
3) 10 is stored in a memory location and a name a is given to it. Then a new value 20 is stored to the same
memory location. What happens now? Why?
5) int a, b=10,c=20;
a=b*c;
Explain the initializing of the variable a here.
6) Write the names of header files used in C.
7) What is incorrect in the following statement : x*y= z
8) cout <<“I study in DPS”
What type of error do we get?
9) a=b=c=100
Explain this concept.
10) a*=2 Implies _____________
11) Identify the type of constant and correct them if they are invalid:
a. 1. 42,000 b. 2.5E3.6 c. ‘DPS’
IV. Write C++statements to declare and accept values for the following:
1. Accept your age.
2. Enter your gender.
3. Accept temperature in your city.
39
V. Write the output for the following code:
a)
#include <iostream.h>
int main( )
{
float k =10 ;
cout <<“Value of k is: “ << k;
return 0;
}
#include <iostream.h>
int main( )
{
float a = 5 , b =2 ;
int c;
c = a % b;
cout << c;
}
b)
#include <iostream.h>
main ( )
{ int i =2 , j= 3 , k ,l;
float a, b;
k = i / j * j;
a = j /i * i;
cout << “k = “ << k<< “\n”;
cout << “a= “ << a << “\n” ;
}
40
DELHI PUBLIC SCHOOL, BANGALORE SOUTH
Pre-Midterm Assessment
Subject: Computers
Total Marks: 20
IV. Identify the valid variables. If not valid, give reason. (3 x 1=3)
1. Delhi%Public*School
2. Bangalore 560050
3. 123Start
41
VI. Do as directed.
1. Write an algorithm to display multiples of 7. (3 x 1=3)
42
DELHI PUBLIC SCHOOL, BANGALORE SOUTH
Midterm Assessment
Subject: Computers
Class: VIII Sec: Total Marks: 20
II. Answer the following questions with reference to the given list of operators. (4 x 1=4)
+ < && % == / ++
43
3. Name the operator that has least priority.
4. Identify and name the operator that operates upon true or false as input values.
Working: Output:
44
V. Do as directed.
a. Write a program to calculate the Lateral Surface Are of a cuboid by accepting values
for required variables. Display all the input and output values on different lines.
Lateral Surface Area = 2h(l+b) (3 x 1 = 3)
45
DELHI PUBLIC SCHOOL, BANGALORE SOUTH
ANNUAL EXAMINATION
Subject: Computers
Total Marks: 20
I. Give the output of the following code snippet and also mention the number of times the loop executes.
1. int i=3, j; (2 x 1=2)
for(i=6;i<=2;i--)
{ j=i--;
cout<<“Value of j:”<<j<<“\n”;}
Working: Output:
II. Solve and give the output for the following expressions.
1. int i=4, j=2, k; (2 x 1=2)
k=i++ / j + j--;
cout<< “i=”<<i<< “\tj=”<<j<< “\tk=”<<k;
Working: Output:
46
2. int a=2,b=3,c; (2 x 1=2)
c=a*b-a/b;
cout<< “Value of c is=\t”<<c;
Working: Output:
III. Identify and debug the errors in the following code snippet and rewrite the correct code. Assume
header files and main is present.
1. int m; (3 x 1 = 3)
For(m=2:m<=4:m++)
cout<<„DPS‟;
IV. Do as directed
1. Define the term variable. Give any two rules to name a variable. (2 x 1 = 2)
47
2. Explain the different types of initialization of variables in C++ with examples. (2 x 1=2)
48
REVISION WORKSHEET
Lesson 4
1) Define Switch Case statement.
2) What are the limitations of switch case
3) What is the use of break in Switch case
4) Write the syntax difference between Simple IF and IF-ELSE.
5) Give the syntax of IF-else
6) Give syntax of nested if-else
7) What is the use of Default in Switch case
8) What is the value for the following expression if.
h =5;
a. cout << h++;
b. cout << h--;
c. cout << h% =2;
d. cout << h - =2;
A. Character B. Integer
C. Float D. enum
a.
#include <iostream.h>
void main()
{
int x = 5;
if (x < 1)
cout <<"hello";
if (x == 5)
cout <<"hi";
else
cout <<"no";
}
49
#include <iostream.h>
b.
int main () {
switch(grade) {
case 'A' :
cout <<"Excellent!\n";
break;
case 'B' :
case 'C' :
cout << "Well done\n" ;
break;
case 'D' :
cout <<"You passed\n";
break;
case 'F' :
cout << "Better try again\n" ;
break;
default :
cout <<"Invalid grade\n" ;
}
return 0;
}
50
LAB ACTIVITY:
1. Determine the value of total after each of the following loops is executed.
3. Give the syntax of FOR LOOP and explain what each element mean.
4. Determine the value of total after each of the following loops is executed.
a. Total=0;
for(i=1;i<=10;i++)
Total=total+1;
b. Total=50;
for(i=1;i<=10;i++)
Total=total-i;
c. Total=1.0;
for(i=1;i<=5 ; i++)
Total=total/2.0;
51
CHAPTER-1
EXCITE
Introduction to Artificial Intelligence or AI
52
Google lens in scanning the items in real world.
Google search allows web search through voice.
While typing in a document/excel, Microsoft automatically suggests word & grammar
corrections and suggestions.
Alexa taking our voice commands & reciprocating accordingly.
Shopping sites like Amazon, Flipkart offering recommendations by understanding your
previous choices.
Self-driving cars.
Weak AI: Current AIs are weak Artificial Intelligence programs, i.e., these programs act
intelligently but are not intelligent. For example, advanced chess programs, personal assistants,
translator’s etc. The responses given by these systems are a part of their programming.
Strong AI: Strong AI systems, on the other hand, will not be limited to programmed responses.
They will use clustering and association for processing data. Such systems will not act
intelligent but will be intelligent. They will act more like the human brain.
Decision making can be biased. Decision making can be free from biased.
It is general purpose intelligence, i.e., Performs tasks only for which they are
capable of performing different tasks. developed.
53
FIELDS RELATED TO ARTIFICIAL INTELLIGENCE
Machine Learning: Machine learning systems are those which improve their performances with
more experience or information. This is sometimes regarded as sub-field of AI and at other
times a separate sub-field of Computer Science.
Deep Learning: Deep Learning or Deep Neural learning are systems that are capable of learning
from unstructured or unlabeled data. For example all family photographs in your house. Emoji
Scavenger game is based on deep learning neural networks.
Data Science: It is the term that is used for referring to different related sub-disciplines. These
sub-disciplines include machine learning, statistics, data storage, web development, etc.
Robotics: The field of robotics deals with construction and programming of robots. Robots are
computing machines that have both hardware and software. The artificial intelligence is used
for the software or programming part of the computer.
Applications of AI:
1. Games: Game developers are using Al technology to
improve the strategic aspects of games. These games
learn and adapt themselves, providing better gaming
experience.
2. Natural Language Processing: This helps computer-based
system to understand the natural language that human
beings use. The game Mystery Animal is based on this
technology.
3. Expert Systems: These systems are used to provide advice,
explanations, solutions, etc. to the users. These are based
on the integration of a number of different programs and
sources.
54
4. Vision Systems: These systems use Al technology to understand the images. These include
identification of faces, diagnosing of patients, identifying damages to buildings and fields, etc.
6. Intelligent Robots: Artificial Intelligence is widely being used to improve the working of the
robots so that they are better able to perform the tasks assigned by human beings.
Disadvantages of AI
1. High Cost:
Creation of artificial intelligence requires huge costs as they are very complex machines. Their
repair and maintenance require huge costs. It needs constant updates with new data points to
keep learning else, system will become obsolete with old data and might actually give wrong
answers or decisions.
2. Can’t Replicate Humans level of decision yet?
Machines do not have any emotions and moral values. They perform what is programmed
and cannot make the judgment of right or wrong. Even cannot take decisions if they encounter
a situation unfamiliar to them. They either perform incorrectly or breakdown in such situations.
3. No Improvement with Experience:
Unlike humans, artificial intelligence cannot be improved with experience. With time, it can
lead to wear and tear. It stores a lot of data but the way it can be accessed and used is very
different from human intelligence.
AI cannot improve with one data or experience, like humans cannot learn from one mistake or
correctness. Need lot of data points to understand and find a pattern.
4. No Original Creativity:
5. Unemployment:
Replacement of humans with machines can lead to large-scale unemployment. Many low end
jobs like factory worker, drivers can become obsolete.
6. Wrong decisions
AI can be trained by people with wrong intent to do harm to people or influence people to take
wrong decisions.
7. Wrong conclusion with inadequate data
Since AI data and Algorithms are given by humans, they can give data or they will act
accordingly to the data given by us to them. This might lead to wrong conclusion.
55
8. Ethical values
AI can be trained to do ethical and moral things as well as unethical things. E.g cameras installed
in all shops and public places can track where we are going every day and understand without
our knowledge which is immoral.
Resources:
56
Worksheet 1.1
I. Which of the following are AI and which are not? State Yes, No or Maybe
1. An Excel spread sheet that determines batting averages and other predefined parameters on
a given data set. ________________
2. Google Maps, navigation system, for finding the fastest route from home to your school.
_________
3. Application such as CorelDraw that allow you to edit the brightness, colour, and contrast in a
picture. ___________________
4. An online books recommendation platform such as Flipkart that suggests books based on the
buyer’s reading and buying behavior. ___________________
5. Huge data storage solutions like YouTube that can store videos and stream them to many
users at the same time. _____________
57
a. Sound data b. Text data c. Image data d. All of these.
5. Which of the following technology is used by games like Emoji Scvanger Hunt?
a. Natural Language Processing
b. Natural Image Processing.
c. Computer vision
d. Neural Data Images.
6. Which of the following is not one of the three domains of artificial intelligence?
a. Data b. Natural Language Processing
b. Neural Networks c. Computer vision
7. What was the name of the computer that defeated World Champion Gary Kasparov in 1997?
a. Deep Sea b. Ocean Blue c. Old sea d. Deep Blue
58
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________
____________________________________________
2. ____________________________________________
____________________________________________
____________________________________________
3. ____________________________________________
____________________________________________
____________________________________________
59
CHAPTER-2
RELATE
Today AI has become a part of our life. Both big and small companies are using this technology
to reduce work pressure and increase productivity. This translates into better customer
experience and comforts. AI has revolutionised every industry and field. Some of the examples
inclue:
60
SMART HOME
Smart home is a technology which provides homeowners security, comfort, convenience and
energy efficiency by allowing them to control smart devices, often by a smart home app on
their smartphone or other networked device.
In other words, a smart home is a residence that uses internet-connected devices to enable the
remote monitoring and management of appliances, devices and systems, such as lighting and
heating.
A part of the internet of things (IoT), smart home systems and devices often operate together,
sharing consumer usage data among themselves and automating actions based on the
homeowners' preferences.
A Smart home has a smart devices along with AI-powered technology to provide new
possibilities
61
A smart home is a term used to describe a home that makes use of
many connected technologies, such as:
Heating Systems.
TV with AI.
Smart door bells.
Smart power switches.
Smart kettles.
Smart vacuum cleaners.
Smart scales.
Smart security cameras.
SMART CITY
A smart city is an urban development vision to integrate information and communication
technology (ICT) and Internet of things (IoT) technology in a secure way to manage a city. This
can include management of local departments' information systems, schools, libraries,
transportation systems, hospitals, power plants, water supply networks, waste management,
law enforcement, and other community services.
In addition to the regular urban infrastructure that is there in any city like office buildings,
residential areas, hospitals, schools, transportation, police and so on, you also need something
in addition to make the cities smart. So, smart means the services that are given to the
respective stake holders of these cities. So, citizens are able to do things in a better
and improved manner than usual. It is possible through the ICT technologies (information and
communication technologies).
Some of the basic components of smart city are:
Hospitals
Railways
Police
Traffic Control
Bank
School
Waste Management
An urban system
Uses Information and Communication Technology (ICT)
Makes infrastructure more interactive, accessible and efficient.
Need for smart city aroused because of
Rapidly growing urban population & its demands
62
Fast depleting natural resources
Rapid change in environment & climate.
Resources:
63
Worksheet 2.1
64
IV. Answer in brief:
1. What are the different appliances/equipments that you think can be added to Smart
buildings?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. What are the few AI-based technologies that you are using in your day-to-day life?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
4. Write a few points on how living in Smart Cities will change your life.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
5. Write about Smart Home?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
65
Draw your new Smart Floor Plan here:
66
CHAPTER-3
PURPOSE
SUSTAINABLE DEVELOPMENT GOALS (SDGs)
The term ‘Sustainable development’ can mean different things to different people in different
situations. One of the most frequently used definition of sustainable development is
‘Sustainable development is the development that meets the needs of the present without
compromising the ability of future generations to meet their own needs’.
67
GOAL 6: Clean Water and Sanitation – Ensure availability and sustainable management of water and
sanitation for all
GOAL 7: Affordable and Clean Energy – Ensure access to affordable, reliable, sustainable and modern
energy for all
GOAL 8: Decent Work and Economic Growth – Promote sustained, inclusive and sustainable
economic growth, full and productive employment and decent work for all
GOAL 9: Industry, Innovation and Infrastructure – Develop quality, reliable, sustainable and resilient
infrastructure, including regional and trans-border infrastructure to support economic development
and human well-being, with focus on affordable and equitable for all.
GOAL 10: Reduced Inequality – Reduce inequality within and among countries
GOAL 11: Sustainable Cities and Communities – make cities and human settlements safe, resilient and
sustainable
GOAL 12: Responsible Consumption and Production – achieving economic growth and sustainable
development requires that we urgently reduce our ecological footprint by changing the way we
produce and consume goods and revenues
GOAL 13: Climate Action – Take urgent actions to combat climate change and its impacts
GOAL 14: Life Below Water – The world’s oceans – their temperature, chemistry, currents and life-
driven global systems that make Earth habitable for humankind
GOAL 15: Life on Land – protect, restore and promote sustainable use of terrestrial ecosystems,
ecologically manage forests, combat desertification, halt and reverse land degradation, and halt
biodiversity loss
GOAL 16: Peace and Justice Strong Institutions – promote peaceful and inclusive societies for
sustainable development, provide access to injustice for all and build effective, accountable and
inclusive institutions at all levels
GOAL 17: Partnerships to achieve the Goal – the SDGs can only be realised with a string commitment
to global partnership and cooperation
68
WORKSHEET 3.1
I. Take a look at the pictures and try to give the theme of each picture:
69
13 …………………………………………. 14 …………..…………………………. 15 ………….…………………………
16 ………..………………………………….. 17 …………………………….………………………..
70
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
What thoughts and actions of yours will help to make the world a better place?
Write your thoughts here… Write the actions you will take...
71
WORKSHEET 3.2
MULTIPLE CHOICE QUESTIONS (MCQs)
1. Which of the following is NOT one of the three main domains of the Sustainable Development
Goals?
a. Environment c. Economy
b. Social d. Political
2. In which of the following years were the Sustainable Development Goals adopted?
a. 2010 b. 2012 c. 2015 d. 2018
4. Which of the following goals mainly deals with cities and human settlements?
a. Goal 11 b. Goal 12 c. Goal 13 d. Goal 14
(i) The Sustainable Development is aimed at satisfying the needs of the present generation.
(ii) The Sustainable Development is aimed at ensuring that the needs of the future generation will be
satisfied.
a. Only (i) b. Only (ii) c. Both (i) and (ii) d. Neither (i) nor (ii)
72
CHAPTER-4
POSSIBILITIES
Possibilities of AI in various fields: Everyday influences of AI globally –
Life-Saving AI
Healthcare industry is using AI to improve the quality of life and save it. The developments in this field
include personalised drug treatments based on 24x7 monitoring using various sensors. Robot assisted
surgeries improve diagnosis. In the field of disaster management, these techniques are helping in
both reducing the impact of disasters and managing the post disaster rescue.
Entertaining AI
Entertainment industry is experimenting with AI to produce original music, books, recipes, etc.
Companies, like, Netflix and Spotify use Al to predict what the users would like to watch or listen.
SETTING 1:
You walk into the reception area of the hospital. The hospital Al controller recognises you based on
your earlier visits to the hospital. It already knows the patient you have come to see. It checks and
sees if your name is still on the list of visitors who are allowed to see the patient. You approach the
reception and the AI notices that you are breathing hard and you are empty handed. The reception
robot asks you if you would like to go directly to meet the patient. get something to drink at the
canteen or visit the gift shops in the hospital. You tell the robot that you would like to visit the
canteen and then go to the gift shop before visiting the patient.
73
SETTING 2:
The hospital AI updates your smart device with the directions to the canteen and gift shop.
You visit the canteen and pick up a soda from the beverages section. The payment for the soda is
automatically deducted from your account. The cafeteria AI system records different things like the
weather, time, your reason for visiting. etc. This data will be used to make your future visits even
more comfortable.
SETTING 3:
The gift shop AI talks to the Hospital AI and finds out that the patient you are visiting is a five years
old girl and that you arrived empty handed to the Hospital. The AI also checks with the Hospital AI to
find out the items that are appropriate for the patient (for example due to allergies, medications,
etc.) The robot at the gift shop shows you a different range of items suited for a five-year old girl.
SETTING 4:
You use the smart device to check the route to the patient's room and head towards it. On reaching
the patient room you are informed that the visiting hours would end at 6:00 PM. You are unable to
access the latest charts of the patient because you are not a close relative.
The growth and development of Artificial Intelligence (AI) has increased the demand for specific jobs
in the industry. It has created a situation in which there is critical shortage of trained individuals in
certain areas. Most of the artificial intelligence related jobs require knowledge of computers and
math. The entry level jobs require graduation. Advanced jobs require post-graduation or doctorates.
The field of study depends on the category of jobs.
TYPES OF AI CAREERS
AI careers can be of two types. The first relates to developing and deploying AI systems. These are
highly specialised jobs that require advance training and education. The second are related to
operating AI systems. For these kinds of jobs the entry level requirements are comparatively lower.
The careers related to the core development and deployment of AI systems include:
Software analysts Computer engineers
Software developers Algorithm specialists
Computer scientists
In addition, the development and deployment of AI Systems need specialists from different areas and
fields. These careers help in the development of AI systems related to their fields.
Mechanical, manufacturing, electrical engineers Graphic designers
Medical professionals Musicians and other entertainment specialists
74
Defence specialists Architects
Companies that hire top AI talent range from start-ups like Argo AI to tech giants like IBM. Following
are the leading employers who have hired top AI talent over the past years.
1. MACHINE LEARNING ENGINEER: These engineers develop and manage machine learning projects.
2. DATA SCIENTIST: Data scientists are scientists who work with data. They collect, analyse, and draw
interpretations from huge datasets.
3. BUSINESS INTELLIGENCE DEVELOPER: They analyse data to identify business and market trends.
This involves designing, modelling, analysing interpretation, maintenance, etc., Of data sets.
4. RESEARCH SCIENTIST: Research scientist is related to research in the field of artificial intelligence.
They research and advance our knowledge of Als.
75
WORKSHEET 4.1
____________________________________________________
____________________________________________________
HEALTH
____________________________________________________
____________________________________________________
____________________________________________________
___________________________________________________
SECURITY
____________________________________________________
_____________________________________________________
____________________________________________________
____________________________________________________
EDUCATION
____________________________________________________
____________________________________________________
_____ ___________________________________________________
___________________________________________________
TRANSPORTATION
___________________________________________________
___________________________________________________
_______ ___________________________________________________
___________________________________________________
ENTERTAINMENT
___________________________________________________
___________________________________________________
76
Activity 2. [Group Activity – Groups of 4]
To make a Poster for a Future Job Advertisement in which you need to mention what job are you
recruiting for and what skill sets is expected in the candidate. Make the poster as creative as possible.
It should be futuristic and should talk about the period 10 years in the future.
● Search for current and emerging trends in employment to make a Future Job
Advertisement.
● The job description is for a job which will exist ten years from now, i.e. the current date.
● To help you, the job advertisement must include the following information.
List the kinds of futuristic job opportunities that Write the skills you require to do these jobs?
would be available for you?
77
Make a Job Advertisement for the Future here:
78
Activity 3. SMART LIVING – Studying in an AI enabled smart school.
You have already seen an illustration about visiting an AI enabled hospital in a Smart City. Now
imagine that you are studying in an AI-enabled smart school. What will be your experience of
studying in such an institution?
SETTING 1: YOU ENTER THE SCHOOL AND ATTEND THE FIRST PERIOD (MATHEMATICS):
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
79
CHAPTER-5
AI ETHICS
ETHICAL CONCERNS RELATED TO AI ACCESS
AI ethical concerns can be divided into two parts:
One of the most serious implications of data collection is related to Privacy Concerns. Take a simple
example of your Android Smart Phone. The following is a list of some information that Google
possesses about you (if you have given it permission).
1. Contact List: All of the numbers on your phone along with the names. Google knows who are
your
favourite (based on the amount of time you spend talking to them), the best time to call you, the
people who you do not like to talk to (i.e., you do not take their calls, or you cut them) etc.
2. Location: Google knows when you leave for school, the route which you take, the time you spend
in school, the route you take back, the shops that you like to visit, the park where you go for walk,
the restaurant where you eat, etc.
3. E-mail: The complete list of all the mails sent and received by you (including the ones you
deleted). Every personal and official mail.
4. Hangout: All Of your chat records.
5. Photos: All the images of you and your friends along with their names. Linked with contact list
Google knows their phone numbers, email-IDs, addresses, etc. Linked with calendar it also knows
about important events like their birthdays, marriage anniversaries. birth of their children, etc.
Most of the time, we accept lengthy user agreements without even realising the implications of
these agreements on our privacy rights. Data related to us is stored somewhere in some large
databases. This data can be used for a number of purposes.
The information is collected in lieu of providing us with helpful services, but the potential risk here
is very high. For example, take the facial recognition system. The AI system can use this technology
along with the information provided by Apps like Contact and Photos to create a wide surveillance
network that can monitor you 24 X 7.
2. INCREASING INEQUALITIES: The current economic system provides economic rewards based on
contributions to the economy. The AI era will reduce the number of people required for doing
jobs. This will also reduce economic remuneration given to them. In this case. most of the
economic benefits will go to companies who own AI systems. This will further widen the already
wide income gaps.
3. NEGATIVE ADOPTIONS: AI technologies, like all the other technologies, can be used for both
good and evil. This technology in the hands of terrorists, can be used to spread terror. They can
use AI based technologies to make attacks that can do most damage in terms of life and
infrastructure losses. Cyber criminals can use AI technology to hack into more systems and for
doing more damage. Countries can use this technology to increase war damages inflicted by
them.
4. BLACK BOX PROBLEM: Black Box problem refers to inherent problems of the AI systems.
Sometime what happens in the AI system is normally not easily understood by common
individuals and not even by the programmers. This problem stems out of the fact that AI systems
do not provide reasoning for decisions made by them
Every technological development can be used for the benefits of the mankind as well as for its
destruction. We Can use dynamites to make mining easy and we can also use them as weapons.
Nuclear power can be used to create energy and it can also be used to destroy cities and countries.
Advancement in medicines can be used to heal and improve the quality of life of human beings as
well as to create biological weapons. AI technology is no different. It can be used for the good of
the mankind or for its destruction.
Overall, the society will have to Come up with ethical guidelines on data and A1 Systems as it has
done for many of the other technologies. The violations of these guidelines. rules or regulations
will have to be punished appropriately.
81
WORKSHEET 5.1
I. True or False
1. Ethics is only concerned with what is good for the individuals. _______________
2. The facial recognition system can be used for creating 24 X 7 wide surveillance systems.
________
3. In a good Al system. consumers have a right to adopt out of the system. ________________
4. Al ethics are the system of moral principles which guide the Al in decisions making.___________
5. Widescale adoption of Al technologies can lead to widening of income gap in the society.______
6. The benefits of the Al systems are always more than the ethical concerns related to them.
______
II. MULTIPLE CHOICE QUESTIONS(MCQs):
1. What is Al Black Box problem?
a. Al systems do not explain their reasoning.
b. Al system design is difficult to understand.
c. Al system data is stored in black boxes which can be easily hacked.
d. Al systems cannot differentiate between right and wrong.
3. A good Al system
a. Must not be transparent
b. Must not delete data even upon the consumer requests
c. Must not allow consumers to leave the system
d. Must not collect information to which it does not have a right
82
WORKSHEET 5.2
THEME : ________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
83