Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
128 views
89 pages
Chap 1 To 4
chapter 1 to 4 by Pakistani writer CM Aslaam
Uploaded by
Mariyah Axix
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save chap 1 to 4 For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
128 views
89 pages
Chap 1 To 4
chapter 1 to 4 by Pakistani writer CM Aslaam
Uploaded by
Mariyah Axix
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save chap 1 to 4 For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save chap 1 to 4 For Later
You are on page 1
/ 89
Search
Fullscreen
pele crater) INTRODUCTION PART-II BASIC INPUT/OUTPUT The statements that are used to get data and then to assign it to variables are known as input statements. The statements that are used to receive data from the computer memory and then to send it to the output devices are called output statements. Following are commonly used input/output statements: The “cout” object — Output Stream The ‘cout’ is pronounced as ‘See Out’. The ‘cout’ stands for console output. The console represents the computer display screen. The ‘cout’ is a C++ predefined object. It is used as an output statement to display output on the computer screen. It is a part of iostream header file. Flow of data from one location to another location is called stream. The ‘cout’ is the standard output stream in C++, This stream sends the Output to the computer screen, The syntax of ‘cout’ is cout << constl/varl [<< consts2/var2 .... Where- 28 Aikman Series D Progr, x ————____—_—_— rm Se ee ee Nin Chap ig " name of output st cout Obje cy e put to operator or 4 : operator. It directs the inser the output device Uta : fy constl/varl, const2/var2 list of constants, Variaby, arithmetic EXPressions. 8 variable or constant,” operator ‘<<’ is useg “Parag The string constants are double quotation marks Nua in constants, variables expressions are given ing ; wit quotation marks, hou For example: cout<<"One kilobyte = "<<1024<<™ bytagr, In the above output statement, two string constants, one numeric constant and three put to operators (<<) have been used. The output of the above statement will be: One kilobyte = 1024 bytes PROGRAM FA 01-05 White a program to print a message on screen using “cout” object. f#include
#include
main ( ) { clrser( ); cout<<"C++ is a powerful programming language cout<<"UNIX operating system is written in C++Enapter 10 Introduction cout<<"It is an easy to learn language"; } Note: In the above program, the elrser() function has been used to clear the computer screen, This function is a part of the “conio.h” header file. This file has been included as preprocessor directive. PROGRAM FH 01-06 Write a program to print “I Love Pakistan” on the screen using “cout” with three put to (<<) operators. #include
main( ) { cout<<"I"<< " Love"<< " Pakistan"; } The Escape Sequence Special non-printing characters are used to control printing on the output device. These are called escape sequence. These charac are not printed. These are used inside string constants or independently. These are written in single or double quotes. An escape sequence is a combination of backslash *\’ and a code character. The backslash is called the control character. For example, to transfer the printing control to the next line the scape sequence is written as \n. Thus to transfer printing control to next line, the output statement is written as; cout<<”I Love Pakistan\n";Aikman Series > Program mi Chapa Tate, In the above statement \n is an escape sequen cil i 5 4 cr the printing control to the next line after the string is printeg It sig An escape sequence can be used anywhere in the oyt can be used at the beginning of the string, in the middle or at string. Put st, ¢ a the eng te If it is used at the beginning of the string then the string printed after printing a blank line. To print the above string in three the statement is written as: i, cout<<”I \n Love \n Pakistan”; Other commonly used escape sequence characters are: ] a a | Escape Sequence EXPLANATION SaaEanas aE ——— | \a “a” stands for alert or alarm. This character causes a beep sound in the computer internal speaker. [tis usually used to draw attention during execution of a program. \b “b” stands for backspace. This escape sequence] causes the print control on the output device to) | move one space back. | For example. | | cout<< “Pakistan\b”; | | After printing the string “Pakistan”, the cursot a move one space back and will be under character ‘n’ of the word “Pakistan”. | If “\b” is not used, then the cursor will be at be end of string. \a atement | In the above example, if another output statemet | f snting Will § is used after the above statement, its na 1a start from character ‘n’ and the last charac’ will be deleted. = Piecepixman Series > Programming with C++ EA} ee wireoueton - ee Thus in the following example; cout<< “Pakistan\b”; cout<< “Punjab”; The output will be as under: PakistaPunjab \t “t” stands for tab. This escape sequence causes the print control on the output device move one tab forward. For example; cout<<“A\tB\tC\tD”; The output of the above statement will be as under: A B c D \n n” stands for new line. It moves the printing control to the beginning of the next line. \f stands for form feed. The escape sequence escapes one blank paper on the printer attached with computer. It is normally used to print the output on the printer after feeding a blank form. \r “r” stands for carriage return. It moves the cursor to the beginning of the current line, \\ These are two backslash characters. One is used as_ control character and second is used to print a backslash ‘\’ character, For example; cout<<"A:\\X¥2"; The output will be as under A:\XYZ If a single backslash character is used, then there will be no effect on the output for example;2 pimnan Series > Prograuniny yur ¢ Chagas cout ce"As \ZI0" ; The output will be as under PITAL | | 4 x | This escape sequence is similar to the, used to print double quotation ma example; coute\" PAK”; The output will be as under “PAK If the above statement is written av shi syntax error will occur, cout<" Pak”; To print word “Pakistan” in double output statement is written as: cout<<*\*Pakistan\ t 2 | v This escape sequence is same as “\” but | fo print a single quotation mark (*), | For example, to print Pakistan as ‘Paki | output statement is written as: | The “endl” Manipulator Manipulators are operators that are used with the put to (<<) to control format of data, The “end!” is an important and commonly used manipulator in C++, The “ends” stands for end of line. It has same eff sequence “\n", This is a predefined iostream Manipulator.man Series [> Programming with C++ : » jor 0 reduction For example cout<«<"C++ \n”<<"Programming \n”<<" anguage” ; Ts equivalent to: coutc<"C++ "
main() { } cout <<”I am a "“<
[e[s[olajals|«[slelvlelelolalalslals | [elalx[a[s[efalal I} s/1] alm alb| ala If the width of the field set by the“: width of the output then the actual output one output items then separate “setw" ma data item. Setw” manipulator is less than the is printed, If there are more than nipulator is used for each output The “setw” manipulator is a part of “i manipulator is to be used in the program, th at the beginning of the program using inclu fomanip.h” header file. If this his header file must be included ide statement,OE Se Geant 1 intron AN FH 01 o8 Program that uses “setw" manipulator (0 print output on the EE ORAPULOE KEKERH #inelude
main ( ) int a,b,c; a=200; b=100; cma; a=b; bec; Cout<<*valuetor ia a cout<<" <
Programming with C++ Chapter folnoduction = as 37 int year, month; year%= 20; month = year*12; cout<<"years = "
> varl [>>var2 where cin represents the object name used as an input stream. This stream represents data coming from input device keyboard. >> extraction operator or get from operator. It gets an input from the input device and assigns it to the variable. varl, var2 represent list of variables. Each variable is separated by extraction operator “>>”, Usually a separate statement is used for each variable, At least one variable on the, right-hand-side of the “>>” operator must be used. The use of other variables is optional. For example, to input data into variables a, b and o, the inputAikman Series > Programming with, c 38 Chapter to toa statement is written as ecin>>a>>b>>ci When this statement is executed, “Enter” key is pressed after typ; data for each variable. PROGRAM M0111 Write a program in C++ to get two numbers from keyboard duri program execution. Calculate the sum and product of the numbers and th print the result on the computer screen. #include
#include
main ( ) { int nl, n2, s, Bi elrser(); cout<<"Enter first number ? "; cin>>n1; cout<<"Enter second number ee cin>>n2; s=nl+n2; p=nl*n2; cout<<"Sum of numbers = "ccs<
> name; - cout<<"Enter age of the person in years"; cin >>age; age_mon = age*12; cout<<"Name of the person = "<
>name; cout<<"Enter marks obtained in C++"; cin >>cpp;Aikman Serios D Programming with cy, i Chapter 16 Introd coutce"Enter marks obtained in Operating Systems cin >>08; cout<<"snter marks obtained in ® cin >>edp; total=cpp+os+edp; avg=total/3.0; cout<<"Name of the student = cout<<"Total Marks cout<<"Average Marks } DP"; PROGRAM Ff 01-14 #include
#include
main ( ) i float c,f; clrscr(); cout<<"Enter temperature in Fahrenheit ?"; cin>>f; c=(£-32)*5.0/9.0; cout<<"Temperature in Celsius = acer } PROGRAM FM 01-15 Write a program in C++ to compute and pri ; ‘ ees i Print the volume o cylinder when its radius ‘r’ and height th’ are given using “ein” (Hint: m hr? and n=3.14) Biven using “cin” (Hint: vo #include
#include
float r,h,v; elrscr(); cout<<"Enter the Radius"; cin >>r; cout<<"Enter the Height"; cin >>h; vea3.14*r*r*h; cout<<"Volume of the cylinder = "<
main () a. int x, y, a, b, c, 8} x= ysasbecs 515) pex+t+ytatbec cout<<"sum = " << 8} ea ee eee elAikman Series D Programming with c4, Chapter ¥ 0 Invoducios Compound Assignment Expression ression is used to add, subtract, multiply Compound assignment exp! ble without writing the variable on eithe; or divide a value to or from a varial side of the assignment operator "=. In this assignment expression, the arithmetic operator is combined with the assignment operator. Its syntax 1s: var op = expression; where var represents the variable to which the value is to be added, subtracted, multiplied or divided. op represents the arithmetic operator i.e. +, -, * and / etc. expression represents the arithmetic expression whose value is to be assigned to the variable. It may be an expression, a variable or a constant. For example, to add 10 to a variable xy that already has a value, the simple arithmetic statement is written as: xy = xy + 10; The above statement can Expression as: xy + = 10; be written as Compound Assignment Following are some examples of Compound assignment erntessina: x += 9; // mame aa x = x 4 9; mone 2y // same Oe pe) ee ea // same x* 7; x /a3) // same as xe x / 3,Thapter 10 Introduction PROGR. Write a program in C++ to assign three values to three integer type variables a, b & c. Add variables a & b and multiply their sum to variable c. se compound assignment statement. #include
main() { ant a, “be cy = 3; = 6; = 9; *= a+b; out <<"Result = "<
Programming with c,, 44 Chapter ¥0Intvoduay The increment operator can be written either Sipe or ater t variable. IF itis written before the variable, itis known as prefixing, 1f i written after the variable, it is known as postfixing. Rian eld Postfi operators have different effects when they are used in expressions Prefix Increment Operator When an increment operator is used in prefix mode in an expressioy it adds | to the value of the variable before the value of the variable is us in the expression. For example, PROGRAM F§l 01-18 #include
main() { int a, b, c, sum; a=l; b= 1; c = 3; sum = a + b + (+#4c); cout <<"Sum = "<
main() { int a, b, c, sum; ael; bel; c= 3; sum = a+b + --c; cout <<"Sum = "<
4 > Programming with o, 46 a SMO 8 Wrogacae acte the value of ¢ he In the above program, | will be subtracted he HN oe ae Ootone nthe above eg axec he sum will be equa it is used in the expression, Thus after execution, t Wal to 4 and value of ¢ will be 2 Postfix Decrement Operator When a decrement operator is used in postfix pe ed Bees on, it subtracts | from the value of the variable after the value of the Variable has been used in the expression For example, if in the above example, decrement operator is used in postfix mode, the result will be different. The statement will be as shown below sum = a + b + c--; In this case, | will be subtracted from the value of c after its existing value has been used in the expression. Thus after execution, the sum will be equal to 5 and the value of ¢ will be 2. The Comment Statement The comment statement is a non-executable statement. It is used to add remarks or comments in a program. The comments are usually given to explain logic of the program. The compiler ignores the comments given in the program In C++, double slashes *//" For example: are used to mark the comment statement. // This is my firs © program in c // Java language i “ie 8 similar to C++ : In the above cxample, two lines indicate the comment statements: The comments can be given at any place in the Source program. example, the comments can also be Kiven afier Wei Low Statement as show below: '‘Aikman Series > Programming with C++ 5 Fraster 1 ereaoction gum = a + C++; //An example of postfix operator eae ee //An example of prefix operator In C, comments are given in a different style. The comments or remarks afe enclosed within symbols ‘/** and ‘*/’. This notation can also be used in C++ programs. procraM White a program to initialize a value to a variable. Calculate the cube of the given value. Also use the comments in the program. #include
main() { // declare the variables int a, c; // a&c are variable names a= 10; // value 10 is assigned to a ¢ = atata;//assignment statement to calculate cube /* next statement is output statement to print the cube of 10 */ cout <<"cube of "<
6 is a relational expression. It indicates a relation between two constants, Since the constant value 10 is greater than 6, this relational expression returns a true value. The operator ‘>’ used between the two values is called the relational operator. It specifies relation between two arithmetic expressions or values. Relational Operators The operators that are used to specify a relation between two expressions or values are known as relational operators,u Aikman Series > Program, Chapter 25 Cone "on Following is a list of C++ relational operators: > GREATER THAN em it is used to test if one expression is greater than the or expression. ther For example, if el and e2 are two expressions then: e1>e2 ifel is greater than e2 then this expression returns TRUE value If el is less than e2 then this expression retums FALSE value >= GREATER THAN OR EQUAL TO it is used to test if one expression is greater than or equal to the | other expression. For example, if el and e2 are two expressions then: e1 >=e2 If el is greater than or equal to c2 then this expression returns TRUE value. Ifel is less than e2 then this expression returns FALSE value. | ef < LESS THAN | It is used to test if one expression is less than the oti | &*Pression. | | For example, if el and ¢2 are two expressions then: e1
Programming with C++ Ghapter 20 Conditional Statements value. " " expre e1 <=e2 EQUAL TO e1==e2 ssion returns FALSE value. For example, if el and e2 are two expressions then: For example, if e1 and e2 are two expressions then: | Ifel is equal to e2 then this expression returns TRUE value. Ifel is greater than e2 then this expression returns FALSE value. 55 Ifel is less than or equal to ¢2 then this expression returns TRUE It is used to test if one expression is equal to the other expression. If el is not equal to (less than or greater than) e2 then this != | NOT EQUAL TO e1 !=e2 For example, if e1 and e2 are two expressions then: If el is not equal to (less than or greater than) 2 then this expression returns TRUE value. If el is equal to e2 then this expression returns FALSE value It is used to test if one expression is not equal to the other expression. Example If x=10, y=20 and z=5 then find out the output of the following relational expressions. Relational Expression Output Returned xy False y
Programming with C++ 57 conditional Statements = The syntax of the “if statement” for executing a set of statements is if (condition) { Statement-1 Statement -2 Statement -3 Statement -m } Statement-n In the above syntax, the set of statements (from Statement-1 to Statement-m) has been enclosed in curly braces. These are called compound statements. If the condition given in the “if statement” is true, the compound statements given in the curly braces are executed. If the condition is false, the control shifts to the Statement-n and the set of statements that follows the “if statement” is ignored. The flowchart for the “if statement” is shown below: FALSE TRUE ae ey [set of statements _ CS ae) aye statements after if structure Flowchart ; The “if statement”mij PROGRAM Fl 02-01 The following program executes a single Statement if the gi condition is true. #include
main( ) { int a, b; a=100; b=50; if(a>b) cout<<"Islamabad"<
main ( ) f int n; cin>>n; ‘eaAikman Series > Programming with C++ 59 Chapter Z0 Conditional Statements if(n>10) { cout<<"Islamabad"<
main() { int n; cout<<"Enter a Number? "; cin>>n; if (n%3==0) { cout<<"The number "<
Programmin, 19 wi 60 Chapter 26 Conditionsr #include
main() { int a,b; cout<<"Enter first value? cin>>a; coutc<"Enter second value? ” i na) cin>>b; if (a>b) cout<<"First value is greater"; if (b>a) cout<<"Second value is greater"; } PROGRAM FM 02-05 Write a program to calculate the electricity bill. Th clectricity per unit are as follow: i 1. If the units consumed are equal or less than 300, then Rs. 3/- per unit. i 2. If units consumed are more than 300, then the cost is per unit and a surcharge of 5% of bill is added. #include
main ( ) { ; float cu, pu, units, bill; cout<<"Enter the current reading ? cin>>cu; cout<<"Enter the Previous cin>>pu; units=cu-pu; if (units>300) billeunits*3 +St+units*0.05/10 if (units<=300) billsunites3 +0; reading ?Aikman Series > Programming with C++ a raptor 2 © Conditional Statements coute<"Electricity bill="<
#include
main() { float a, b, c, rl, r2, disc, real, imag; cout<<"Enter value of A?"; cin>>a; cout<<"Enter value of B?"; cin>>b; cout<<"Enter value of C?"; cin>>c; disc =b*b-4.0*a*c; if (disc<0) real.= -b/(2.0*a); imag = sqrt (-disc)/(2.0*a);8 Aervan Settee > Progra ‘Chapter d even an cout<<*Roote are imaginary"<
0) { cout<<"Roots are real & different "<
lee® wi (*cedmagce) ag Note: In the above program “sqrt” as a libra rary function has bee! to find out the square root of dise. It is a member funet math header file, Therefore “math.h” header file m included at the beginning of the program. The “if-else” Statement This is another form of the “if statement”, It is used for makin: way decisions. In this statement, one condition and two. bloc! statements are given. Either one of the two blocks of statements is after evaluating a condition, The “if-else” statement tests the given relational condition: condition is true then the first block of statements is executed. | condition is false, the first block of statement is ignored and the se block following the else is executed,‘Chapter 2 © Conditional Statements The syntax of “if-else” statement is: Syntax-1 if (condition) Statement -1; else Statement -2; Syntax-2 In case of multiple or block written as: if (condition) { Statement-1; Statement -2; Statement -m; } else { Statement-1; Statement -2; Statement-n; } block-2 of statements, the syntax is First block Second blockPROGRAM F02-07 Write a program to input a number from the keyboard Statement to find out whether the number is less than Or gre; ‘ater tha #include
main ( ) { aint n; cout<<"Enter an integer value ? "3 cin>>n; if(n>100) cout<<"number is greater than loon, else cout<<"number ig less than 100 } In the program, if the entered number is greater than 100, then Siven condition becomes true, the statement following the “if? is execu and the statement following the “else” is ignored, If the entered number becomes false and the stat statement follow; is less than 100 itement following th ing the “else” is executed. , then the given conditi he “if” is ignored and PROGRAM FA 02-08 Write a Program ‘© input two value: print the larger number o} n the computer se #include
main() S from the keyboard and then Teen, int a, b; cout<<"Enter Pirg 9 t number? Bs cin>>a; cout<<"Enter seconq number? «; cin>>b; if (a>b) cout< <"First number ig greater"; elseAikman Series > Programming with C++ Thapter2 © Conditional Statements cout<<"Second number is greater"; } Note: If both numbers are equal, even then the above Program will print the message that “Second number is greater” PROGRAM Fl 02-09 Wnite a program to calculate the net pay of an employee. Input the basic pay and calculate the net pay as follows: © House rent is 45% of the basic pay. ¢ Medical allowance is 2% of basic if basic is greater than Rs. 5000/-. It is 5% of basic pay if the pay is less than Rs. 5000/- * Conveyance allowance is Rs. 96/- if basic pay is less than Rs. 5000/-. Itis Rs. 193/- if the basic pay is more than Rs. 5000/- ¢ Net pay is calculated by adding basic pay, medical allowance, conveyance allowance and house rent. #include
main() float basic, ma, ca, net, hr; cout<<”Enter basic pay?”; cin >> basic; if (basic > 5000) ma basic * 2/100.0; ca 193.0; hr = basic *45.0/100.0; } else { ma = basic * 5.0/100.0; ca = 96.0; hr = basic *45.0/100.0; net = basic + matcathr; cout <<"Net pay = “<
Programmin, 66 CRB? © Contig ee PROGRAM Fl 02-10 Write a program to input a number from the keyboard and ther the message “It is an Odd Number” if it is an odd number, Els message “It is an Even Number”. (A number is even if it is divisible #include
main() { int n; cout <<”Enter an integer value 2”, cin >>n; if (n%2 == 1) cout <<"It is an Odd Number”; else cout <<“It is an Even Number”; } PROGRAM F§l02-11 Write a program to input two integers and then to find out w these numbers are equal or different. #include
main() { int a,b; cout <<”Enter first value ? %; cin >>a; cout <<”Enter secona value ? %; cin >>b; if (a%2 == b%2) cout <<”Both values are equal"; cout << “values are different”; }ae ‘Aikman Series > Programming with C++ ‘Chapter 20 Conditionsl Statements The “nested if” Statement When an “if statement” is used within another “if statement called the “nested if statement”. The “nested if statement” is used way decision-making. The syntax of “nested if statement” is: if (condition-1) if (condition-2) { } Statement-3; Statement-2; Flowchart : The “nested-if” statement 2; | i ; ‘| Sal Aikman Series > Progra 68 Chapter 2 Conder In the above syntax, if the condition-I is true then the ‘ Contra} to the next “if statement” and the condition-2 is tested, s If the condition-2 is true then Statement-2 is executed Th will then pass to Statement-3 and this statement will be executed If condition-2 is false, then Statement-2 is skipped an, shifts to Statement-3 and it will be executed. The “if statement” for testing conditoin-2 is wif Statement”. This “if statement” is called the “nested if state PROGRAM F§02-12 Write a program to input three integer values, Com values to find out if they are equal. Use “nested if statement” message “All values are equal” if they all are equal. Other message “These values are different”, #include
main() { int a, b, c; cout <<"Enter first value 2" cin >> a; cout <<"Enter second value 2"; cin >> b; cout <<"Enter third value 2"; cin >>c; if (a==b) { if (as=c) cout <<"All values are e else cout <<"These values ar.japter 2.0 Conditional Statements ROGRAM FH 02-13 Write a program to input three integer values from the keyboard. ind out the greatest number and print it on the screen. #include
main() { int a,b, CF cout <<"Enter first no. ?"; cin >>a; cout <<"Enter second no. ?"; cin >>b; cout <<"Enter third no. ?"; cin >>c; at if (a>b) if (a>c) | cout <<"1lst number is greater "; else cout <<"3rd number is greater "; else (b>c) cout <<"2nd number is greater "; else cout <<"3rd number is greater "; . PROGRAM Ff 02-14 Write a program to find out the grade of a student based on the marks obtained in three subjects. The grade is calculated as: If average is greater than 80, grade is ‘A’, | Is average is less than 80 and greater than 50, grade is *B’. If average is less than 50 and greater than 33, grade is *C’. | If average is less than 33, grade is *F” eo ee. Aixman Series #include
main() { int 81, 82, 83, avg; char grade; cout <<"Enter the marks of subject 3 | cin >>s1; cout <<"Enter the marks of subject 2". cin >>s2; cout <<”Enter the marks of subject cin >>s3; avg=(s1+s2+s3) /3; if (avg>33) if (avg>50) if (avg>80) grade=’A’; else grade='B’; else grade='c’; else grade='F’; : cout <<"Grade = “
Programming with C++ ‘Chapter 2.0 Conditional Statements 71 Statement -3 else if (condition-m) Statement-m else Statement -n; TRUE condition [eli | a | | FALSE statements after e structure Flowchart: “nested if-else” Statement PROGRAM Ff 02-15, Write a program to perform simple arithmetic operation by using “nested if-else” structure.- 4 - Aikman Series > Programming Chapter 2» Cong . onal ay #include
main() int a,b; char op; cout <<"Enter ist integer, operator integer\n"; cout <<"Press Enter Key "; Cin >>a>sop>>b; if (op == '+") cout<< "Addition = " <<(a+b); else if (op=='-") cout<< "subtraction= " <<(a-b); else if (0 /*) cout<< "Division = " <<(a/b); else if (0 9) cout<< "Remainder = " <<(a%b); else cout<<"Invalid input"; e The “switch” Statement The “switch statement” is used as a substitute of Statements. It is used when multi be selected. nested ple choices are given and one choice is The “nested if-else” structure becomes, iP choices. The “switch statement” is used in Such situations. Only on condition is given in the “switch Statement” and multiple choices are give inside the main body as cases. The “switch statement” One of the choices or cases in t complicated in mul evaluates an expression and returns a value he “switch statement” is executed dependi The syntax of switch is; he ins) Oei lls Ghapter 2 « Conditional St switch (expression) { case const-1: statements; break; case const-2: statements; break; case const-n: statements; break; default: statements; The conts-1, const-2, efc. are numeric constants or character constants. In the above syntax of the switch statement, one test expression appears within the switch statement. The body of the switch statement contains many cases. When the switch statement is executed, the given expression is first evaluated and then the value returned by the expression is compared with the values of constants given in cach case. If the value matches with constant value of a case then the statements of that case are executed. Keyword default is also used in the body of switch statement. If no case is matched then the statements under the default are executed. Its use is optional. If it is not used then the control exits from the body of the switch statement and goes to the first statement following the end of the switch structure, The break Statement The break statement is used to exit from the body of the switch structure (or the loop structure).14 Aikman Series D Programm) Chapter? » Conan a tional In the switch statement, the break statement is normally Use end of statements in each case. It exits the control from the body oj structure. If it is not used then the statements of other cases that or the matching case will also be executed. PROGRAM F¥ 02-16 Write a program to input an integer value. Test the integer y, the value is divisible by 2, then print the message “Divisible otherwise “Not divisible by 2” by using switch statement. #include
main() { int n; cout <<"Enter any value"<
>n; switch (n%2) { case 0: cout <<"Divisible by 2"<
Programming with C++ roa Staterneit 75 PROGRAM 02-17 Write a program to perform simple arithmetic operation by using switch statement #include
#include
main() { int a,b; char op; elrscr (); cout<<"Enter lst #, operator & 2nd #"<
>a>>op>>b: switch (op) { case '+': cout<< "Addition =" <<(a+b); break; case, '-': cout<< "subtraction=" <<(a-b); break; case '*': cout<< "Multiplication="_ <<(a*b); break; case '/ cout<< "Division =" <<(a/b); break; case '%': cout<< "Remainder =" <<(a%b); break; default: cout<< "Invalid-input";Note: In the above program, the character constants have in cases consists of a single value. The keyword do, constant value to match with the expre 3 statements under “default” are executed if a y, those mentioned in the cases is s I. variable op. There is no need to use “break Stater body of default or in the last case of the switch st PROGRAM F¥02-18 Switch statement. #include
#include
main() { int choice; clrscr (); cout <<"1: cout «<<"2: cout <<"3: cout «<<"4: cout <<" cin >>choice; switch (choice) case 1: cout<< break; case 2: cout<< break; case 3: been ye althouys “t fault hag i ton Value No alue oth igned to the The “op” represents the expression, her an Charag Ment in ‘atement lay a menu to perform variou: functions. Use Program to input data"<
Programming with C++ Chapter 7 » Conditional Statements cout<< "You have select the 3rd option; break; case 4: cout<< "You have select to Exit"; break; } cout<< "\n Ok" ; The “nested if-else” & “switch” Statements Both the nested “if-else” and switch statement are used for multiple selections but following are the differences between these statements: ‘ | + | Nested if-else Statement © Switch Statement i. |\t becomes complicated for | It is easy to understand for | multiple selections. multiple selections. ii. | It an independent | It uses a single expression for | expression for each case. | all cases. but each case must have a constant value of integer type or character type. iii. | The test condition can be given | Only a single expression is in a specified range of values. | given in the switch Statement which retums a single value. | The test condition cannot be | given in a specified range. It is {the major drawback of the | switch statement, ed | If the given condition matches. then the statements under it will be executed,& The Conditional Operator The conditional operator is used as an alternative of q Sim statement. Ple j The conditional operator consists of “?” (question-mark) and (colon). Its syntax is: {condition}?{Exp1}:{exp2} where condition represents the test condition. If this condition is then the value of “exp1” is returned after evalu; Otherwise the value of “exp2” is returned, expl & exp2 represent the two expressions. It may be arith expressions or constant values. Input/output state can be used. For example, if a=10 and b=5 and res is an integer type va then an assignment statement is written as: res=(a>b) ?a:b The above statement is equivalent to: if(a>b) res=a; else res=b; PROGRAM Fl 02-19 Write a program to input two val 7 ues. Use conditional ope! find out which value is greater, Print a Message on the screen to indic greater value.Chapter > Condniansl Meements #inelude «
a; cout <<"Enter 2nd value ") ein »>b; max=(a>b) ?arb; cout <<"Greater value ia = "<«
main () { > dint a; cout <<"Enter an integer value "; cin >>a; cout<<(a%2 == 0)?7"Yeo":"No"; LOGICAL OPERATORS The logical operators are used to combine relational expressions or relational conditions, The expression containing logical operators is called logical expression or logical condition. It is also called compound condition Or compound expression.Chapter? The output of a logical expression is also in logical form. Ii cither true or false. In C++, following logical operators Sy are used ‘tug iy i) aa. 4 AND operator ii) ll ab: OR operator ii) | — NOT operator The && (AND) Operator The && (AND) operator is used to combine two or more Telatiog expressions. If all relational expressions are true then the Output retumeg _ the compound expression is true. If any one of relation al expression in the compound expression is false, the output is false. For example, if x= 10, y = 15,2 = 5 then the com pound EXDression (x
y) & (z = = 5) and (xcy) && (z>x) will retum false values. PROGRA 21 Write a pro: gram to find out the largest no. numbers. from three given | #include
! main() 2 int a,b,c; cout << "Enter first value"; cin >>a cout << "Enter 2nq value"; cin >> b; cout << "Enter 3rq value"; cin >> c; if ((a>b) && (a>c)) cout << "lst value is greater";‘Aikman Series > Programming with C++ a a Grapes 2 Conditional Statements else if ((b>a) && (b>c)) cout << "2nd value is greater"; else cout << "3rd value is greater"; } The || (OR) Operator i The || (OR) operator is used to combine more than one relational expressions. If any one of the given relational expressions is true, the output will be true otherwise the output will be false. For example, if x = 0, y = 15, z = 5 then the compound expression (x>y) || (z 5) returns true because (z 5) is true. Similarly, (x t= y) || (x = = y) || ( 2 > 10) retums true because (x!=y) is true. If all the relational expressions in the compound condition are false then the output will be false. PROGRAM Fl 02-22 Write a program in C++ to implement the ‘OR’ operator. #include
main () { int a; char op; cout << "Enter an integer value"; cin >> a; cout << "Enter any character"; cin >> op; if ((a<0) | | (op== y') || (op=='n'))Chi —g 26 Candee eh cout << "OK, condition is true"; else cout << "All relational xPression, false"; ay } The “&&” and “\l” operators can be used in.a Single co, 0 logical expression. They are evaluated from left to right in the followin BS ny order: i) “SE” a) aS] [ The ! (Not) Operator The ! (NOT) operator is also known as the unary the value retumed by the relational expression or the co} For example, if x = 5 and y = 10 then the logical expression + (x>y) returns true. It is because (x>y) returns false and the “!” (NOT; perator inverts the result into true. Y Operator. It invers Mpound expression I, sah / Wnite a program to find out the greater value from two given values #include
main() * { int a, b; cout << "Enter 1gt integer value «; cin >> a; cout << "Enter 2nd’ inte cin >> b; 1(a
main() it cout<< "This program explains the "; cout<< “use of goto statement"<
main() { int a, b; cout << "Enter lst integer "; cin >> a; cout << "Enter 2nd integer "; cin >> b; if (a>b) { cout << "1st integer is greater"; goto xyz; } cout << "2nd integer is greater"; xyz: } Write a program to print first ten natural numbers. Use “: goto” al “if” statements, # include
main() . int c = 1; abe: cout <
Programming with C++ Do Loop Stmements he While loop for more than one statement is written as: while (condition) { } statement (s); When “while” loop statement is executed, the computer first evaluates the given condition. If the given condition is truc, the statement or set of statements in the body of the "while” is executed. After executing the Statements under “while”, the control shifts back to “while” and the condition is again tested. If the given condition becomes false at any stage during execution. the execution of the body of loop is terminated and control shifts to the statement that comes immediately after the body of the loop. The body of the loop must contain a statement so that the condition ‘on the loop becomes false during execution of the loop. If the condition of the loop never becomes false, the loop never ends. It becomes an infinite loop. PROGRAM Fl 03-01 Print “I Love Pakistan” five times using the “while” loop. #include
main () { int ¢c; Cues while (c<=5) cout<<“I love Pakistan”<
Prog, Min, Chapter yo ith, ‘a In this example, the variable *c’ is assigned a vg alue 1 tg ia condition truce. When the given condition (c<=5) is tested, it wilt ¢ TRUE value, so the body of the loop will be executed Ml te In the body of the loop, the statement “c = ¢+];” of vanable during program execution. After executing five times, the of “c” becomes 6 and the loop is terminated and Control shifts statement “cout<<"Program ends”. This statement comes after the p, the loop. changes the The flowchart of “while” loop is given below: statement immediately after while Loop Flowchart: The “while” Loop PROGRAM FA 03-02 #include
main () {HARE A (ns MhatesHnine Anh my ony ae 0) heky while (Weel) { feaeny eOUubl eeneeendl; hoe ney ) Boul eefaum =e " eeay } PROGKAM FH ovo Welle a programy to print the multiplication table ofa number entered from the keyboard Hinelude «
Progra IM MVin Meee Progra mans #include
— main () { int nr; cout <<“Enter the integer, cin >> n; while (n>=1) { Voy. 2) QD = n/2; cout
main () { long int fact, nic ; Sout <<"Enter any value”; cin >> n,; fact = 1, while (n>=1) fact = fact * n;‘Chapter 5 © Loop Statements cout <<”Factorial = “ <
| main () ( | float 8, c; . s = 0.0; | Cy 1707 a while (c<=45) se 8 = 8 + 1.0/c; C++; x cout <<”Sum of series = “ <
main () f int n = 10; while (n!=0) cout <
main () int n; ne= 1; do { cout <
| body of loop TRUE FALSE statement immediately after while Flowchart; The do-while Loop ee98 PROGRAM FW 03-09 Write a program to input and print the record of a Student this process for other students until the given condition remains true #include
#include
main () { int marks; char name[25], address[15], op; { clrscr (); do cout<<”Enter name of student”; cin >>name; cout<<”Enter Address of student”; cin >>address; cout<<”Enter Marks Obtained”; cin >> marks; cout<
> op; while (op == sy: || op sey); cout <
Program aca 99 ibewer 30 Loop statererss ia SiS main () int n, x; clrser (); cout <<”"Enter any integer no.”; cinssn; do ren % 8; cout
= 1); cout <
#include
main () { long int £, m, n; clraecr () 7 cout <<”Enter any no.”; cin>>n; mM =n} f=l; doAikman Barlow [> while (n y= 1)) ¢ cout <«<’Pactorial of samenn, © The “continue” Statement The “continue” statement shifs the control back to the beginnin the loop. It is used inside the body of the loop. When this staal executed inside the body of the loop, the control shifts to the firgt st of the body of the loop. Ment jg tery Its syntax is: continue; For example #include
main () { int o; eal} while (c<=5) { cout << “Pakitan” << endl; CH; continue; cout<<"Islamabad”; cout<<"Peshawar”; } } In the above program, only first three statements inside the “whi loop are executed 5 times, The two statements after “continue” stateme” are not executed because each time the “continue” statement returns control back to the beginning of body of loop,Series > Programming with C++ Grae d= Loop Stormers 101 The “break” Statement The “break” statement terminates the execution of the loop when it js used inside the body of the loop. The difference between the “break” statement and the “continue” Statement is that ¢ The “break” statement terminates the loop during execution, The other “break! atements of the body of the loop that comes under the statement are not executed * The “continue” statement does not terminate the loop but it shifts the control at the beginning of the body of the loop. The atements of the body of the loop that come under the ‘ontinue™ statement are not executed, PROGRAM FM 03-12 Write a program to execute a set of statements repeatedly by using “while” loop, “break” and “continue” statements, The test condition of the while loop must be a constant value, #include
#include
main () { char name [15], op; int age; while (1) { elrscr (); cout << “Enter Name”; cin>>name; cout << “Enter age “) cin >> age; cout<< “Names"<
You might also like
Course Curriculum of EEE Department 2
PDF
No ratings yet
Course Curriculum of EEE Department 2
59 pages
Lab 02 (CSE251)
PDF
No ratings yet
Lab 02 (CSE251)
19 pages
(Ilene J. Busch-Vishniac (Auth.) ) Electromechanica
PDF
No ratings yet
(Ilene J. Busch-Vishniac (Auth.) ) Electromechanica
349 pages
Combinational Vs Sequential Circuit
PDF
No ratings yet
Combinational Vs Sequential Circuit
8 pages
Electronic Devices 9th Edition
PDF
No ratings yet
Electronic Devices 9th Edition
15 pages
Digital Circuits - Anand Kumar
PDF
No ratings yet
Digital Circuits - Anand Kumar
4 pages
E M T Complete e Notes
PDF
No ratings yet
E M T Complete e Notes
121 pages
Chapter 2.2 4pic16f877 Instruction Set Programming
PDF
No ratings yet
Chapter 2.2 4pic16f877 Instruction Set Programming
39 pages
Chapter 4
PDF
No ratings yet
Chapter 4
30 pages
Notes Fourier Series PDF
PDF
0% (1)
Notes Fourier Series PDF
73 pages
Butterworth Filters - I
PDF
No ratings yet
Butterworth Filters - I
12 pages
Tut-2-KVL and KCL
PDF
No ratings yet
Tut-2-KVL and KCL
30 pages
Problems in Chapter 7
PDF
No ratings yet
Problems in Chapter 7
6 pages
Using The Concept of Supermesh, Find The Current Through 8 Resistor in The Following Circuit
PDF
No ratings yet
Using The Concept of Supermesh, Find The Current Through 8 Resistor in The Following Circuit
16 pages
Chapter 7 FET Transistors
PDF
No ratings yet
Chapter 7 FET Transistors
118 pages
Analog Electronics: Lab Report 4
PDF
No ratings yet
Analog Electronics: Lab Report 4
8 pages
Lecture9 Memory Organization
PDF
No ratings yet
Lecture9 Memory Organization
32 pages
BJT Biasing
PDF
100% (1)
BJT Biasing
26 pages
Lecture3 Chapter4 - Design 4-Bit Ripple Carry Binary Adder-Subtractor Circuit
PDF
No ratings yet
Lecture3 Chapter4 - Design 4-Bit Ripple Carry Binary Adder-Subtractor Circuit
32 pages
ECE 460 Lab Report
PDF
100% (1)
ECE 460 Lab Report
23 pages
COMIA, JOHN LLOYD B - Exercises-No.1
PDF
No ratings yet
COMIA, JOHN LLOYD B - Exercises-No.1
7 pages
Clipper Circuits - Clipping Circuits, Series, Positive, Negative, Parallel, Biased - D&E Notes
PDF
No ratings yet
Clipper Circuits - Clipping Circuits, Series, Positive, Negative, Parallel, Biased - D&E Notes
6 pages
Title: Implementation OF Sr-Latches & Flip Flops Using Nand &nor Lab Worksheet #12
PDF
No ratings yet
Title: Implementation OF Sr-Latches & Flip Flops Using Nand &nor Lab Worksheet #12
3 pages
EECS 141: First Midterm Exam, Fall '96
PDF
No ratings yet
EECS 141: First Midterm Exam, Fall '96
7 pages
CC216 Digital Logic Design: LAB Work #4
PDF
No ratings yet
CC216 Digital Logic Design: LAB Work #4
14 pages
Organization of The 8086/8088 Microprocessor: Lecture#6
PDF
No ratings yet
Organization of The 8086/8088 Microprocessor: Lecture#6
19 pages
Chapter 12 PP PDF
PDF
No ratings yet
Chapter 12 PP PDF
8 pages
Module 2 FET Transistor
PDF
No ratings yet
Module 2 FET Transistor
50 pages
Laplace Formulae
PDF
No ratings yet
Laplace Formulae
4 pages
EEP3701 Practical Assignment
PDF
100% (1)
EEP3701 Practical Assignment
17 pages
Circuit Theory - Solved Assignments - Semester Fall 2003
PDF
No ratings yet
Circuit Theory - Solved Assignments - Semester Fall 2003
35 pages
Lab No. 2-ENA PDF
PDF
No ratings yet
Lab No. 2-ENA PDF
5 pages
Laplace Transform Examples
PDF
No ratings yet
Laplace Transform Examples
19 pages
Ca Lab Manual
PDF
No ratings yet
Ca Lab Manual
48 pages
Ch01 PDF
PDF
No ratings yet
Ch01 PDF
14 pages
Chapter # 16: Loud Speakers, Headphones and Earpiece
PDF
No ratings yet
Chapter # 16: Loud Speakers, Headphones and Earpiece
12 pages
Lecture 2 - BJT R Model
PDF
No ratings yet
Lecture 2 - BJT R Model
17 pages
Applied Physics Lab Lab Lab
PDF
No ratings yet
Applied Physics Lab Lab Lab
31 pages
SA 1 - Lab Report
PDF
No ratings yet
SA 1 - Lab Report
26 pages
Transient Analysis - Practice Sheet 01
PDF
No ratings yet
Transient Analysis - Practice Sheet 01
8 pages
Lecture Five Mesh Analysis: - Identify Mesh - How To Apply Mesh Analysis - Super Mesh
PDF
No ratings yet
Lecture Five Mesh Analysis: - Identify Mesh - How To Apply Mesh Analysis - Super Mesh
15 pages
Electric Circuit Analysis 3Rd Edition Solution Manual - MD
PDF
No ratings yet
Electric Circuit Analysis 3Rd Edition Solution Manual - MD
3 pages
Node and Supernode Final 2
PDF
No ratings yet
Node and Supernode Final 2
10 pages
Philips 8051
PDF
No ratings yet
Philips 8051
114 pages
A-D To D-A Circuits
PDF
No ratings yet
A-D To D-A Circuits
35 pages
Navneet Eced Lab Exp
PDF
No ratings yet
Navneet Eced Lab Exp
16 pages
Resonant Circuit (Parallel Resonance)
PDF
100% (1)
Resonant Circuit (Parallel Resonance)
8 pages
1.characteristics of MOSFET
PDF
No ratings yet
1.characteristics of MOSFET
8 pages
Cmos Vlsi Design 65
PDF
No ratings yet
Cmos Vlsi Design 65
1 page
ECE312 Lec03 PDF
PDF
No ratings yet
ECE312 Lec03 PDF
46 pages
IEC - Lab-Exp-3 Solution
PDF
No ratings yet
IEC - Lab-Exp-3 Solution
13 pages
UART Transmitter: (And Adding A START Bit and END Bit For A Total of 10-Bits.)
PDF
100% (1)
UART Transmitter: (And Adding A START Bit and END Bit For A Total of 10-Bits.)
12 pages
Parallel RLC Circuit and RLC Parallel Circuit Analysis
PDF
No ratings yet
Parallel RLC Circuit and RLC Parallel Circuit Analysis
24 pages
Unit 1 Tutorials
PDF
No ratings yet
Unit 1 Tutorials
11 pages
BEEE-Question Bank 2023
PDF
No ratings yet
BEEE-Question Bank 2023
5 pages
Chapter 15
PDF
No ratings yet
Chapter 15
10 pages
CEG2136 15lab3
PDF
No ratings yet
CEG2136 15lab3
17 pages
PIC Program For Division
PDF
No ratings yet
PIC Program For Division
4 pages
Question Paper Code:: Reg. No.
PDF
No ratings yet
Question Paper Code:: Reg. No.
5 pages
ECEN 2250, Introduction To Circuits & Electronics, Fall 2011 - Course Description PDF
PDF
No ratings yet
ECEN 2250, Introduction To Circuits & Electronics, Fall 2011 - Course Description PDF
4 pages
Lab Report Electronics
PDF
No ratings yet
Lab Report Electronics
25 pages
IGFET
PDF
No ratings yet
IGFET
13 pages
Morrison 1981
PDF
No ratings yet
Morrison 1981
13 pages
Iron Oxide Composite
PDF
No ratings yet
Iron Oxide Composite
17 pages
JFET (Junction Field Effect Transistor)
PDF
No ratings yet
JFET (Junction Field Effect Transistor)
11 pages