PTCA_Chapter-1 Review of C++ Programming Notes

/
/
/
1030 Views

1.  OOPS means ……………………………

     Object Oriented Programming Language

2.  C++ is developed by …………………….

     Bjarne Stroustrup.( യാനേ)

3.  What is Character Set?

A character set is a set of characters a language can identify .It is also known as the alphabet of a programming language. Most C++ Compiler follows ASCII character set. They include letters, digits, special symbols, white spaces etc.

4.  What are token? What are different types of tokens used in C++?

Tokens are the fundamental building blocks of a program. They are also known as Lexical unit. There are five types of tokens in C++.

1. Key words: Key words are tokens that carry a specific meaning to the language compiler.

eg: for, int, do, if etc…

 2. Identifiers: Identifiers are user defined words that are used to name different program elements such as memory locations, statements, functions, classes etc.. Identifiers used for naming memory location is known as variables.

3. Literal: Literals are data items that never change their values during the program running. They are also known as constants. There are 4 types of literals

a)  Integer literal: Tokens formed only by digits. It must have at least one digit and must not have decimal point. It may contain +ve or _ve sign as first character. If there is no sign it is treated as positive. Other characters are not allowed. Eg. 15, -20, +40

b)  Floating Point Literal(Real constants):They have fractional part. They can be written in two forms: Fractional and exponential form. They have at least one digit and a decimal point. They have either +ve or –ve sign. If there is no sign it is treated as positive. In exponential form, there are two parts, Mantissa (Parts appearing before E)and Exponential(Power). Mantissa may be either integer or a valid fractional part. The Mantissa is followed by letter E or e and the exponent. The exponent must be an integer.

Eg: 52.15, -715.12, .458E04

c)  Character Literal : Single character enclosed with single quotes and that never changes its value during program run. Value of character constant is ASCII value of the character. Non graphical symbols can be represented by using  escape sequence which consists of a back slash(\) followed by one or more characters. (eg. \n, \a..). ( ‘,”, ? etc are also written with escape sequence because they carry special purpose). Eg. Valid Character Literal: ‘s’, ‘$’,’\n’ Invalid Character Literal: ‘82’, “k”, ‘\8’

d).  String Literals: Sequence of one or more characters enclosed with in a pair of double quotes. Eg. “computer”. Every string in C++ terminated by a null (\0) character.

4. Punctuators: Special symbols that have syntactic or semantic meaning to the compiler. Eg: #, : , ’ , ” ,() ,[]

5. Operators: Operators are the tokens that trigger some kind of operations. The operations applied on a set of data called operands.

 Based on the number of operands, operators are classified into three, Unary operator, Binary operator and Ternary operator .

A unary operator acts on a single operand. ( eg +(positive),-(negative)

 A binary operator acts on two operands. (eg. Arithmatic, relational etc..)

A ternary operator(? 🙂 acts on three operands. ( conditional ? 🙂

Based on the nature of operation operators are classified into three Arithmetic, Relational and Logical operator.

a). Arithmetic operator

These are used for addition, subtraction, multiplication and division(+,-,*,/).C++ provides a special operator modulus operator(%) for getting remainder of division operation. For example 10 % 2 returns 0.

b) Relational operators

Relational operators are used to compare values. They produces only ‘True’ of ‘False’ values. The following are the relational operators in C++. Eg: ( <,>, <=,>=, ==, !=)

c). Logical operator

Logical operators allow us to combine two or more conditions. and(&&):( Result will be true only if both the combined expressions have true value) or(||):Result will be true only if any of the combined expressions have true value ) not(!): To get the negation of the give expression

There are some other operators such as,

d). Input-Output operators

The Input-Output operators are used to take input and display output. The operator(>>) is used for taking input, and the operator(<<) is used to display the output. The >> operator is called extraction or get from operator. The operator << is called insertion or put to operator. It is a binary operator.

The input operator is used with standard input stream, cin and the output operator is used with standard output stream, cout.The input operator takes the value through cin and stores in a variable.

Cin >> number;

Cout << number+2;

Cascading of I/O operators

The multiple use of input or output operators in a single statement is called cascading of I/O operators.

Eg. cin>>a>>b;

e). Assignment operator (=)

The assignment operator is used to assign a value to a variable. For example a=10 Assigns the value 10 to a

The symbol = assigns a value, where as the symbol == compare two values.

5.  What are rules in naming of identifiers?

a). It may contain an arbitery long sequence of letters, digits and _(under score)

b). First character must be letter or _

c). White space and special characters are not allowed.

d). Key words can not be used.

e). Upper and Lower case letters are treated separately(case sensitive).

Eg. Valid identifiers: _dob, FOR, Count

        Invalid identifiers: sum of, 1styear, for…..

6.  What are Data Types? And Explain different data types in C++?

Data types are the means to identify the nature of the data and the set of operations that can be performed on the data. There are three types of data types C++,

a).Fundamental data type (built in Data types): They are defined in the C++ compiler. There are 5 types of Fundamental data types,

1). Char: They are symbols covered by the character set of C++ language. It uses only one byte  of memory (storing in memory with its ASCII value). Eg: ‘m’,’f’

2). Int : Whole numbers without fractional part. It can be positive or negative, or zero. It uses  two bytes of memory and can store whole numbers from -32768 to +32767.

3). Float : They are numbers with fractional part. It uses four bytes of memory. It can be represented either by scientific notation or mantissa exponential method.

4). Double: It is used for handling large floating point numbers. It uses 8 bytes of memory.

5). Void :uses zero bytes of memory.

b). Derived data types: They are derived from fundamental data types by some grouping or alteration in size. Eg. Array, pointer etc…

c). User defined data types:  The programmer can define there own data types. Eg. Struct, enum, union, class etc..

7.What is type conversion?

Type conversion means converting one data type to another data type. There are two types of type conversion, Implicit type conversion (Type Promotion)  and Explicit type conversion(Type Casting)

a). Implicit type conversion also known as automatic type conversion is performed by the compiler. The conversion is always from lower type to higher type, it is also known as type promotion.

b) Explicit type conversion Type casting refers to conversion that is performed explicitly using cast operator. The operator used for this purpose is  known as cast operator. The cast operator takes on the format cast type (expression)

for example : int a = (int) 10.5 , Here the value 10.5 is converted to integer type

8. What are variables?

Name given to a memory location is known as variable. It is use to store and retrieve data. It have three part:

 a) Variable name b). Memory address(starting address of the allocated memory)

c). Content

9. What are expressions?

An expression consists of operator and operand. There are different types of arithmetic expressions in C++: Some are,

a). Integer expression: All operands in the expressions are integers. An integer expression yields an integer result.

b). Floating point (decimal ) expression: All operands in the expression are floating points(decimals).A floating point expression yields a floating point result.

c). Relational expression ; The relational expression consists of relational operators. They are also called conditions.

d). Logical expression : A logical expression is an expression whose value is either True or False. For example x>y is a logical expression, since it can be either ‘True’ or ‘False’.

10.  What is a statement? And Explain different types of statements?

Statement is the smallest executable unit of programming language. It uses (;) as delimiter. All the statements except declaration statement are executable.

a). Declaration statements: It is used to declare the type of the variable or constant used in the program. Eg. Int x, y ; int a=10;

b).Assignment statement: It is used to assign a value to a variable eg. A=10; b=c+d;

c). Input statement: It allows the user to store data in the memory (RAM) during the program execution. In C++ get from or extract operator(>>) is used for it.

Eg. Cin >> a;

d).  Output statement: It allows the user to make available the results through any output device. In C++ put to or insertion operator(<<)is used for it. Eg. Cout >> a;

11.  What is mean by cascading of I/O Operator?

Multiple use of Input / Output operators in a single statement is called cascading of I/O Operator. Here the values are assigned to the variables from left to right.

Eg. Cout << x <<y <<z; cin >> x >> y;

12. Explain Increment and Decrement Operators?

In C++ there are two operators increment(++) and decrement (–).The increment operator increases the value by one and the decrement operator decreases the value by one.

Prefix increment and decrement operator

The Prefix increment operator increases the value by one, whereas the prefix decrement operator decreases the value by one before the operation. Here incremented or decremented value is used for other operations. So this method is called change, then use method.

Eg. a=++b here the value of b is incremented by one and assigned to a.

Postfix increment and decrement operator

The Postfix increment operator also increases the value by one, whereas the prefix decrement operator decreases the value by one after he operation. So this method is called use, then change method.

Eg. a=b++ here the value of  b is assigned to a then the value of b is incremented by one.

13.Explain C++ Shorthands. ?

C++ shorthands are used to simplify the coding of assignment statements.

Example x=x+20; can be written as x+=20;

a*=b is equivalent to a=a*b

sum- =n%10 is equivalent to sum=sum – n % 10;

14. What are Control Statements in C++?

Control statements are used to alter the normal sequence of execution of a program.

They are classified into two types, a)  Decision Statements b). Iteration Statements

a). Decision statements

The decision statements are based on a condition. They are also known as branching statements. The flow of control depends on the result of a particular condition. C++ supports three types of decision statements,

a) if statement

b) if – else statement

c) Switch statement

a). if statement

The if statement is a single path statement, which executes statement only if the condition is true.

Syntax :

if(condition or expression)

statement1;

If the condition is true then the statement1 will be executed.

Eg. # include <iostream>

int main( )

{

int mark;

cout <<”Enter your mark” ;

cin >> mark ;

if (mark >=18)

cout <<”You have Passed “ ;

return 0;

}

In the above example the message You have passed will be displayed only when the condition is true ie, mark >=18 is true.

b). if – else statements

The if… else statement is used to test a logical condition and choose one of the alternatives based on the result of logical condition.

The syntax :

If (condition or expression)

statement 1;

else

statement 2;

eg. Program to Find largest of two numbers.

# include <iostream>

int main( )

{

int a,b;

cout << “Enter the numbers: “ ;

cin >> a >> b;

if (a > b)

cout << “First number is largest: ” ;

else

cout <<”Second number is largest: ” ;

return 0;

}

c). Nested if

An if – else statement can be placed inside anotherif – else statement, is called nesting of if.

Example

if (mark >=80)

{

if (age>18)

cout<<”Eligible for higher studies” ;

else

cout <<”Not Eligible” ;

}

d). else-if ladder

The else-if ladder helps to select one out of many alternative block of statements.

Syntax :

If (test-expression)

{ Statement 1;}

else if (test-expression)

{ Statement 2; }

else if (test-expression)

{ Statement 3; }

else

{ Statements; }

Switch statement

The Switch enables to select one among several alternatives. It is a multipath statement.

Syntax:

Switch (expression)

{

case value1 :Statement 1;break;

case value2 :Statement 2;break;

case value3 :Statement 3;break;

default : Statement n;

}

The expression is evaluated and statements are executed according to the value .If no match is found, then default statement is executed.

Looping Statements

a). for statement :

The for statement is the most commonly used statement in C++.It is an entry controlled loop.

Syntax :

For(initialisation ; test expression ; updation)

{

Body of loop;

}

Example: Program to Print first 10 natural numbers

#include<iostream>

Int main()

{

int i;

for(i=0;i<10;i++)

{

cout<< i;

cout<<” “;

}

}

b). While Statement

The while … loop is an entry controlled loop. Thecondition is checked first and if it

is true the loop will be executed.

Syntax:

While (expression)

{

Body of loop;

Update expression;

}

Example: Program to print first 10 even numbers

#include<iostream>

int main()

{

int i;

i=2;

while(i<=10)

{

cout<<i;

i=i+2;

}

}

c). do … while loop

The do while loop executes statement before the expression is tested.

Syntax:

do

{

Statements ;

}

While (expression)

Example: Program to print first 10 even numbers

#include<iostream>

int main()

{

int i;

i=2;

do

{

cout<<i;

i=i+2;

} while(i<=10);

}

15.  What is the Difference between do …. while and while Loop

In the while loop the condition is tested and the body gets executed. In do..while loop the condition is checked at the end of the loop. The do…while loop executes at least one time even if the condition is false.

16. What is Conditional Operator (?:):

The conditional operator is a ternary operator(ie,it takes three operands).The general form is Condition? true-part: false-part;

The condition is a boolean expression. If it is true the result is the true part, else the result is the false-part .

If(Mark>18) ? cout<<”Pass” :cout<<”Fail”;

17.  What are Jump statements?

Jump statements are used to jump unconditionally to a different statement. It is used to alter the flow of control unconditionally. There are four types of jump statements in C++ : break, continue, go to and return.

a). return statement is used to transfer control back to the calling program or to come out of a function

#include<iostream>

using namespace std;

int fact(int n);          //function prototype

int main()

{

 int n=0, result=0;

 cout<<“Enter Number: “;

 cin>>n;

 result=fact(n);

 cout<<“Factorial of ” <<n <<” is: ” <<result <<endl;

}

int fact(int n)   //function definition

{

 int f=1;

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

 {

  f=f*i;

 }

 return f;

}

b).break statement is used to terminate a loop or switch statement.

#include <iostream>

using namespace std;

int main(){

   int num =10;

   while(num<=200) {

      cout<<“Value of num is: “<<num<<endl;

      if (num==12) {

         break;

      }

      num++;

   }

   cout<<“Hey, I’m out of the loop”;

   return 0;

}

Output:

 Value of num is: 10

Value of num is: 11

Value of num is: 12

Hey, I’m out of the loop

c).continue statement is used to continue to the beginning of a loop. When a continue statement is executed in a loop it skips the remaining statements in the loop and proceeds with the next iteration of the loop.

// C++ program to explain the use

// of continue statement

#include <iostream>

using namespace std;

int main()

{

    // loop from 1 to 10

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

        // If i is equals to 6, continue to next iteration  without printing

        if (i == 6)

            continue;

        else

            // otherwise print the value of i

            cout << i << ” “;

    }

      return 0;

}

Output:

1 2 3 4 5 7 8 9 10

d). goto statement is used for unconditional jump. It transfers the control from one part of the program to another.

Syntax: goto label: (A label is an identifier followed by a colon)

Syntax1      |   Syntax2

—————————-

goto label;  |    label: 

.                 |    .

.                 |    .

.                 |    .

label:         |    goto label;

Eg:

            #include <iostream> 

            using namespace std; 

            int main() 

            { 

            ineligible:   

                     cout<<“You are not eligible to vote!\n”;   

                  cout<<“Enter your age:\n”;   

                  int age; 

                  cin>>age; 

                  if (age < 18){   

                          goto ineligible;   

                  }   

                  else   

                  {   

                          cout<<“You are eligible to vote!”;    

                  }        

            } 

Output:

You are not eligible to vote!

Enter your age:

16

You are not eligible to vote!

Enter your age:

7

You are not eligible to vote!

Enter your age:

22

You are eligible to vote!

18. When a C++ program is compiled, the following errors are reported:

a) Undefined symbol cin

b)  Undefined symbol cout

(i) What can be the reason for these errors? (ii) How can it be solved?

19. What are the selection statements of C++?

Ans: If and Switch

20. What are the four components of a loop?

Ans: Initialization expression, Test expression, Update expression and Loop body

21. Give examples for entry-controlled loop.

Ans: For and While

22. Which control transfer statement is equivalent to the conditional operator (?:)?

Ans: If-else Statement

 23. All switch statements can be replaced by any form of if statement. State whether it is true or false.

Ans: False,  In C++ all switch statements can be replaced by else-if ladder, but all else-if ladders cannot be substituted by switch.

24. What is wrong with the following code segment?

 for (short i=1; i<5; ++i)

for (i=5; i>0; –i)

cout<<i<<“\t”;

Ans: The loop control variables for the two loops should be different. Here same variable (i) is used

25. The default case in switch is equivalent to the else block of else if ladder. Justify this statement with the help of example.

Ans: In switch statement, when no match is found ,default statement is executed.

Switch(day)

{

case 1: cout<<”Sunday”;

break;

case 2: cout<<”Monday”;

break;

.

.

.

default: cout<<”Wroung Input”;

}

In else if ladder ,when no expression evaluates to True, else block is executed

If(day==1)

cout”Sunday”;

Else if (day==2)

cout <<”Monday”;

.

.

.

else

cout<<”Wroung input”;

26. What will be the output of the following code fragment?

for (outer=10; outer>5; –outer)

 for (inner=1; inner<4; ++inner)

 cout<<outer<<“\t”<<inner<<endl;

Iteration   OuterLoop InnerLoop              Output

  1. 10                  1                      10         1         
  2. 10                  2                      10         2                     
  3. 10                  3                      10         3
  4. 9                    1                      9          1
  5. 9                    2                      9          2
  6. 9                    3                      9          3
  7. 8                    1                      8          1
  8. 8                    2                      8          2
  9. 8                    3                      8          3
  10. 7                    1                      7          1
  11. 7                    2                      7          2
  12. 7                    3                      7          3
  13. 6                    1                      6          1
  14. 6                    2                      6          2
  15. 6                    3                      6          3         

28. Write a program to produce the following output using nested loop:

 A

 A B

 A B C

 A B C D

A B C D E

Ans: #include<iostream>

using namespace std;

int main()

{

int x, y, n;

char ch;

cout<<“Enter the number of Rows:”;

cin>>n;

for(x=1; x<=n; x++)

cout<<“\n”;

ch= ‘A’;

for(y=1; y<=x; y++)

{

cout<<“\t”<<ch<<\t”;

ch++;

}

 29. Read the following C++ code snippet:

for (n=1; n<5; ++n) {

 cout<<i;

if (i==2) continue;

if (i%3==0) break;

cout<<“Hello”; }

 Choose the correct output of this code from the following:

  1. 1Hello2Hello3Hello4Hello b. 1Hello2Hello3 c. 1Hello23 d. 1Hello23Hello

Ans: a. 1Hello23

30. Read the following C++ code segment and replace it with a looping statement:

cin>>n;

 loop: r=n%10;

 s=s*10+r;

n=n/10;

if (n!=0) goto loop;

cout<<s;

Ans: int n;

cin>>n;

 while (n! =0)

{

r=n%10;

s=s*10+r;

n=n/10;

}

cout<<s;

31. Which of the following is not a character constant in C++?

 a. ‘\t’ b. ‘a’ c. ‘9’ d. ‘9a’

Ans: d.9a

32. Some of the following identifiers are invalid. Identify them and give reason for the invalidity.

 a. unsigned  b. cpp c. 2num d. cout

Ans: unsigned and cout is a keyword , 2num  digit is used as the first character.

33. What happens if break is not used in switch statement?

Ans: Switch case statements are used to execute only specific case statements based on the switch expression. If we do not use break statement at the end of each case, program will execute all consecutive case statements until it finds next break statement or till the end of switch case block.

34. Read the following tokens and identify the type of token to which each of these belongs:

i. number ii. 23.98 iii. “\0” iv.cin v.++ vi. void vii. ‘\\’ viii. ; ix. = x. a

Keywords: void ,cin

Identifier: number, a

Character Literal:’\\’

String Literl:”\0”

Floating-point Literal: 23.98

Operater: ++,=

Punctuators: ;

35. What is the role of #include statement in C++ program?

The Preprocessor directive # include is used to link the header files available in the C++ Library by which the facilities required in the program can be obtained.

36. What is wrong in the statement: cin>>25; ?

The second operand is strictly a variable.

37. List the type modifiers of C++.

signed , unsigned shot and long are the type modifiers

Leave a Comment

Your email address will not be published. Required fields are marked *

This div height required for enabling the sticky sidebar
Copyright at 2021. eStudyWorld All Rights Reserved
error: Content is protected !!