You are on page 1of 21

C++ ASSIGNMENT NO: 1

Q1: a) Preprocessor Directives: Preprocessor directives are lines included in the code of our programs that are not program statements but directives for the preprocessor. These lines are always preceded by a hash sign (#). The preprocessor is executed before the actual compilation of code begins, therefore the preprocessor digests all these directives before any code is generated by the statements. No semicolon (;) is expected at the end of a preprocessor directive. e.g. #include<iostream.h>, #include<conio.h>, #define etc. b) Main () Function: The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it - the instructions contained within this function's definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function. e.g. int main (), void main () etc. The statements in the main function are enclosed with in the parenthesis { }. All the statements inside these parentheses are executed first then the other user defined functions statements. c) C++ Statements: A statement is a simple or compound expression that can actually produce some effect. In fact, this statement performs the only action that generates a visible effect in our first program. An output stream is used cout is declared in the iostream standard file, so that's why we needed to include that specific file and to declare that we were going to use this specific output stream earlier in our code. All the statement ends with a semicolon character (;). This character is used to mark the end of the statement and in fact it must be included at the end of all expression statements in all C++ programs (one of the most common syntax errors is indeed to forget to include some semicolon after a statement).

Q2: Variables: A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer. There are two types of global variables:

Local variables Global variables

Local variables The scope of local variables is limited to the block enclosed in braces ({ }) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa. Global variables Global variable is a variable declared in the main body of the source code, outside all functions. Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration. I-Naming Variables The name of variable can be called identifier or variable name in a friendly way. It has to follow these rules: The name can contain letters, digits and the underscore but the first letter has to be a letter or the underscore. Be avoided underscore as the first letter because it can be clashed with standard system variables. The length of name can be up to 247 characters but 31 characters are usually adequate. Keywords cannot be used as a variable name. Of course, the variable name should be meaningful to the programming context.

II-Declaring Variables To declare a variable you specify its name and kind of data type it can store. The variable declaration always ends with a semicolon, for example:
int a; char ch;

You can declare variables at any point of your program before using it. You should declare your variables closest to their first point of use so the source code is easier to maintain. In C++ programming language, declaring a variable is also defining a variable. III-Initializing Variables You can also initialize a variable when you declare it, for example:
int a=10;

char ch= a;

Q3: Data Types: When we store data in a C++ program, such as a whole number or a character, we have to tell the compiler which type of data we want to store. The data type will have characteristics such as the range of values that can be stored and the operations that can be performed on variables of that type. Types and Capacity of data types: There are five basic data types in C++: Integer (int) short int long int unsigned int (float) {16 bits(2 bytes) -32768 to 32767} {16 bits(2 bytes) -32768 to 32767} {32 bits(4 bytes) -2147483648 to 2147483647} {16 bits(2 bytes) 0 to 65535} {32bits(4 bytes) 3.4x10-38 to 3.4x10+38} {64 bits(8 bytes) 1.7x10-308 to 1.7x10+308} {64 bits(8 bytes) 1.7x10-308 to 1.7x10+308} {80 bits(10 bytes) 3.4x10-4932 to 3.4x10+4932} {8 bits(1 byte) capacity from 1-65535 bytes}

Floating point long float

Double precision (double) long double

Character (char)

Q4: Declaration of AB and YZ as integer type, D as float, LMN as string with 15 characters and sum as double.
#include<iostream.h> void main() { int AB, YZ; float D; char LMN[15]; double sum; }

Q5: Constants: A quantity that cannot change its value during execution is known as constant. They are used to express particular values within the source code of a program. We use these to

give concrete values to variables or to express messages we wanted our programs to print out.

Constants have four types in C++: i) ii) iii) iv) Integer constants Floating point constants Character constants String constants

Integer constants are constant data elements that have no fractional parts or exponents. They always begin with a digit. You can specify integer constants in decimal, octal, or hexadecimal form. They can specify signed or unsigned types and long or short types. Floating-point constants specify values that must have a fractional part. These values contain decimal points (.) and can contain exponents. Floating-point constants have a "mantissa," which specifies the value of the number, an "exponent," which specifies the magnitude of the number, and an optional suffix that specifies the constant's type. The mantissa is specified as a sequence of digits followed by a period, followed by an optional sequence of digits representing the fractional part of the number. Character constants are one or more members of the "source character set," the character set in which a program is written, surrounded by single quotation marks ('). They are used to represent characters in the "execution character set," the character set on the machine where the program executes. String literal consists of zero or more characters from the source character set surrounded by double quotation marks ("). A string literal represents a sequence of characters that, taken together, form a null-terminated string. String literals may contain any graphic character from the source character set except the double quotation mark ("), backslash (\), or newline character. They may contain the same escape sequences described in C++ Character Constants. C++ strings have these types: Array of char[n], where n is the length of the string (in characters) plus 1 for the terminating '\0' that marks the end of the string. Array of wchar_t, for wide-character strings. Q6: Errors
#includ<iostraem.h> Main() [ int r; //include and iostream //Parenthesis is wrong

const float a=5.6; //a is declared but not used r=2; abc=2*p*r; //p is used but not declared cout>>"Result is ="<<abc;//put to function is wrong ]

Q7: Program which adds 19+31 and subtracts 23-67 and multiply 5*3 and divide 5/15 and remainder of 5%3.
#include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b, c, d, e, f, i, j; float g, h, div; int add, sub, mpy, rem; a=19; b=31; c=23; d=67; e=5; f=3; g=5; h=15; i=5; j=3; add=a+b; sub=c-d; mpy=e*f; div=g/h; rem=i%j; //header files //main function //declaration of int type variables //declaration of float type variables //declaration of int type variables //assigning 19 to a //assigning 31 to b //assigning 23 to c //assigning 67 to d //assigning 5 to e //assigning 3 to f //assigning 5 to g //assigning 15 to h //assigning 5 to i //assigning 3 to j //assigning addition of a & b //assigning subtraction of c & d //assigning multiplication of e & f //assigning division of g & h //assigning remainder i & j //displaying //displaying //displaying //displaying //displaying addition subtraction multiplication division remainder

cout<<"Addition of 19+31 = "<<add<<endl; cout<<"Subtraction of 23-67 = "<<sub<<endl; cout<<"Multiplication of 5*3 = "<<mpy<<endl; cout<<"Division of 5/15 = "<<div<<endl; cout<<"Remainder of 5%3 = "<<rem<<endl; getch(); }

Q8 Escape Sequences: Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant. Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark ("). e.g. \n, \t, \a, \b etc. Program:
#include<iostream.h> #include<conio.h> void main() { clrscr(); cout<<"Press enter to continue......"; getch(); cout<<"\n\n\n\tHello!\n\t\tWelcome to\n\t\t\tCusit Peshawar\b\a"; getch(); }

Q9 Manipulators: Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects. They are still regular functions and can also be called as any other function using a stream object as argument. Manipulators are used to change formatting parameters on streams and to insert or extract certain special characters. Program for this output: 1 2 C Program:
#include<iostream.h> #include<conio.h> #include<iomanip.h> void main() { clrscr(); cout<<setw(5)<<"CITY"<<setw(11)<<"UNIVERSITY"; getch(); }

3 I

4 T

5 Y

2 U

3 N

4 I

5 V

6 E

7 R

8 S

9 I

0 T

1 Y

Q10 Input stream cin: Cin is an object of class istream that represents the standard input stream. By default, most systems get their standard input from the keyboard; therefore cin is generally expected to get information from the user, although there are many cases where this can be redirected to some other source. Because cin is an object of class istream, we can retrieve characters from cin either as formatted data using the extraction operator (>>) or as unformatted data using the read member function, among others. Program:
#include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b, c, sum, pro; cout<<"\n\tEnter first number : "; cin>>a; cout<<"\n\tEnter second number : "; cin>>b; cout<<"\n\tEnter third number : "; cin>>c; sum=a+b+c; pro=a*b*c; cout<<"\n\n\tSum of these numbers is = "<<sum<<endl; cout<<"\n\tProduct of these numbers is = "<<pro<<endl; getch(); }

Q11 Increment and Decrement Operator: Increment operator is used to increase the value of variable by one. It works with single operator. This can only increase the value of variables. It cannot increase the value of constants and expressions. x++ and y++ are valid statements but 5++ is an invalid statements. The functionality of the following statements is same. All these statements are equivalent. These statements increase the value of x by 1. x++; x=x+1; x+=1; Prefix Form: In the prefix form of increment operator, the increment operator is written before the variable. ++x; Let a = ++x. In this situation the meaning of this statement is this, that it increases the value of x by 1 and after that it assigns that value to a. Postfix Form: In the postfix form of increment operator, the increment operator is written after the variable. x++; Let a = x++. In this situation the meaning of this statement is this, that it assigns the value of x to a and after that increases the value of x. Decrement operator is used to decrease the value of variable by one. It works with single operator. This can only decrease the value of variables. It cannot decrease the value of constants and expressions. a-- and b-- are valid statements but 10-- is an invalid statements. The functionality of the following statements is same. All these statements are equivalent. These statements decrease the value of x by 1. x--; x=x-1; x-=1; Prefix Form: In the prefix form of decrement operator, the decrement operator is written before the variable. --x; Let a = --x. In this situation the meaning of this statement is this, that it decreases the value of x by 1 and after that it assigns that value to a.

Postfix Form: In the postfix form of decrement operator, the decrement operator is written after the variable. x--; Let a = x--. In this situation the meaning of this statement is this, that it assigns the value of x to a and after that decreases the value of x. Program:
#include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b; //decleration of a & b as integer type variables a=7; //Assigning 7 to a b=5; //Assigning 5 to b cout<<"\n\n\t\ta "<<a<<" b "<<b<<endl; //value before inc & dec cout<<"\n\n\t\t++a "<<++a<<" --b "<<--b<<endl;//prefix inc & dec cout<<"\n\n\t\ta "<<a<<" b "<<b<<endl; //value after inc & dec cout<<"\n\n\t\ta-- "<<a--<<" b-- "<<b--<<endl;//postfix inc & dec cout<<"\n\n\t\ta "<<a<<" b "<<b<<endl; //value after inc & dec getch(); }

Q12 Relational Operators: (= =, <=, >=, <, >,! =) There is often need to compare two values in program. Such as whether the value in one a variable is greater than the value in the other variable. Depending upon the situation we can perform different operation for different cases. Relational Operators (also known as Comparison Operators) are used to compare two values. The result of comparison is a Boolean value. The Boolean value can either be true or false. In c and c++, 1 represents true and 0 represent false. However in c++ the data type bool has been introduced, which holds only two values either true or false. The value true in bool corresponds to 1 and 0 corresponds to false. Program In this program 1 means that it is true and 0 means it is false
#include<iostream.h> #include<iomanip.h> #include<conio.h> void main () { clrscr(); cout<<"\n\t5 < 10"<<setw(3)<<" cout<<"\n\t5 <= 10"<<setw(3)<<" cout<<"\n\t5 > 10"<<setw(3)<<" cout<<"\n\t5 >= 10"<<setw(3)<<" cout<<"\n\t5 == 10"<<setw(3)<<" cout<<"\n\t5 != 10"<<setw(3)<<" getch(); }

: : : : : :

"<<(5 "<<(5 "<<(5 "<<(5 "<<(5 "<<(5

< 10)<<endl; <= 10)<<endl; > 10)<<endl; >= 10)<<endl; == 10)<<endl; != 10)<<endl;

Q13 IF statement: The ability to control the flow of your program, letting it makes decisions on what code to execute. The if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false. One of the important functions of the if statement is that it allows the program to select an action based upon the user's input. For example, by using an if statement to check a user entered password, your program can decide whether a user is allowed access to the program. Without a conditional statement such as the if statement, programs would run almost the exact same way every time. If statements allow the flow of the program to be changed, and so they allow algorithms and more interesting code. Output of Program
#include<iostream.h> main() { int a,b; a=100; b=50; if(a>b) cout<<"Pakistan"<<endl; cout<<"OK"<<endl; }

This program will show: Pakistan OK Q14 Program to input two numbers to find whether it is divisible by 2 or not:
#include<iostream.h> #include<conio.h> void main() { int num; cout<<"\n\tEnter any number : "; cin>>num; if(num%2==0) { cout<<"\n\tThe entered number is divisible by 2"<<endl; } cout<<"\n\tThe entered number is not divisible by 2"<<endl; getch(); }

Q15 If-else statements: The if else statement is a type of control structure. A control structure is a instruction, statement or group of statements which determines the sequence of execution of other statements. The basic operation of if else statement is that a statement or group of statements is executed under if, if the value of expression is true and if the expression is false, statements under else are evaluated. Statement associated either with if or else are executed not both group of statements are executed. The else clause is optional. Program to find greater value
#include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b , i; char ch; i=1; do{ cout<<"\n\tEnter the first value : "; cin>>a; cout<<"\n\tEnter the second value : "; cin>>b; if(a>b) cout<<"\n\tFirst value is greater than second"<<endl; else if(b>a) cout<<"\n\tSecond value is greater than first"<<endl; else cout<<"\n\tBoth vales are equal"<<endl; cout<<"\n\n\n\tNext ......(Y/N) : "; cin>>ch; } while(ch=='Y'||ch=='y'); getch(); }

Q16 Program to input a number then print it is an odd number, if it is an odd number. Else print it is an even number. #include<iostream.h> #include<conio.h> void main() { clrscr(); int num1, num2; cout<<"\n\tEnter first number : "; cin>>num1; if(num1%2==0) cout<<"\n\t"<<num1<<" is an even number"<<endl; else cout<<"\n\t"<<num1<<" is an odd number"; cout<<"\n\n\n\tEnter second number : "; cin>>num2; if(num2%2==0) cout<<"\n\t"<<num2<<" is an even number"<<endl; else cout<<"\n\t"<<num2<<" is an odd number"; getch(); }

Q17 Nested If statement: If statement inside the body of another if statement is called the nested if statement. The first if statement is called the outer if statement and the second if statement inside the outer if statement is called as inner if statement. First the outer if condition is checked and if it is correct then the control goes in the inner if condition and if this is correct too then the inner statement respective output is generated. Syntax: if(condition) { if(condition) { statements to execute } statements to execute } Program to find greater value in three entered values
#include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b, c; cout<<"\n\tEnter the 1st value : "; cin>>a; cout<<"\n\tEnter the 2nd value : "; cin>>b; cout<<"\n\tEnter the 3rd value : "; cin>>c; if(a>b) if(a>c) cout<<"\n\t1st value is greater"<<endl; else cout<<"\n\t3rd value is greater"<<endl;

else if(b>c) cout<<"\n\t2nd value is greater"<<endl; else cout<<"\n\t3rd value is greater"<<endl; getch(); }

Q18 Logical operators (OR, NOT, AND): The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true and false otherwise. The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Program
#include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b, c; char op; do { cout<<"\n\tEnter first value : "; cin>>a; cout<<"\n\tEnter the second value : "; cin>>b; cout<<"\n\tEnter the third value : ";

cin>>c; if(a>b && a>c) cout<<"\n\tFirst number is greater"; else if(b>a && b>c) cout<<"\n\tSecond value is greater"; else if(c>a && c>b) cout<<"\n\tThird value is greater"; else cout<<"\n\tAll values are equal"; if(a%2 !=0) cout<<"\n\t"<<a<<" is Odd number"<<endl; else if(b%2 !=0) cout<<"\n\t"<<b<<" is Odd number"<<endl; else if(c%2 !=0) cout<<"\n\t"<<c<<" is Odd number"<<endl; else cout<<"\n\n\t"<<a<<" "<<b<<" "<<c<<" are Even numbers"<<endl; cout<<"\n\n\tNext......(Y/N) : "; cin>>op; } while(op=='Y'||op=='y'); getch(); }

Q19 Loop: Loop means that the set of statements are executed repeatedly until and unless the condition is true. The execution will continue until the condition goes false. There are three types of loop: While loop Do-while loop For loop I: While loop It is a conditional loop, it is used to execute a set of statements which are in the parenthesis of the while condition. It will execute the statements to a given condition comes false. Syntax:
int i=5; While(a>0) { Statement Statement Statement Statement i++; }

For example: In the above syntax i is initialized and assigned a value of 5. The given condition is that the value entered in a is greater than 0, so the loop will continue executing the following statements until the value of a become 0 the loop will terminate and execute the statements outside the loop. II: Do-while loop This is also a conditional loop, it is just like while loop but first the statements are executed then the condition is tested either true or false. If true it will again execute the statements under the do but if it is false it will terminate and execute the outer statements. Syntax:
do { Statement(s) } while(condition);

The condition in the while will be ended with a statement terminator otherwise it will not execute the statements and give error. In this loop at least on time the statements are executed.

III: For loop For loop is also conditional loop, in this loop the statements are executed at a given condition. It is just like while loop but syntax is change. This loop is also known as counter loop. Syntax:
for(initialization ; condition ; increment or decrement) { Statement(s) }

The variable is initialized then condition and then increment or decrement according to the need. If a variable is declared before the loop there is no need of initialization again in the loop. The loop will start from the initializes value and continue executing the statements inside the loop until the given condition goes false. Q20 Program to print City University five times using while loop.
#include<iostream.h> #include<conio.h> void main() { int a=1; while(a<=5) { cout<<"\n\n\tCITY UNIVERSITY"; a++; } getch(); }

Q21 Convert the given number into octal Do-while loop.


#include<iostream.h> #include<conio.h> void main() { clrscr(); int num, res; cout<<"\n\tEnter any number : "; cin>>num; do { res=num%8; cout<<"\n\t"<<res<<endl; num=num/8; } while(num>=1); getch(); }

Q22 Execute set of statements by using while loop, break and continue statements while loop must contain constant value.
#include<iostream.h> #include<conio.h> #include<stdio.h> void main() { clrscr(); int age, dob; char name[15], fname[15], ch; while(1) { cout<<"\n\tEnter your name : "; gets(name);

cout<<"\n\tEnter your father name : "; gets(fname); cout<<"\n\tEnter your age : "; cin>>age; cout<<"\n\tEnter your dob : "; cin>>dob; cout<<"\n\n\tNAME : "<<name<<endl; cout<<"\n\n\tFATHER NAME : "<<fname<<endl; cout<<"\n\n\tAGE : "<<age<<endl; cout<<"\n\n\tDOB : "<<dob<<endl; cout<<"\n\n\tNext record.....(Y/N) : "; cin>>ch; if(ch=='Y'||ch=='y') continue; else break; } getch(); }

You might also like