23
Manual # 2 Topic: Conditional Structure Case Study Included Subject: Introduction to Computing Author: Sunawar Khan Ahsan Author2: 1

Conditional structure

Embed Size (px)

Citation preview

Page 1: Conditional structure

Manual # 2

Topic:

Conditional Structure

Case Study Included

Subject:Introduction to Computing

Author:Sunawar Khan Ahsan

Author2:Mehwish Shabbir

1

Page 2: Conditional structure

-----------------------------------------------------------------------------------------------------------Write a program that if the user entered value other then zero then the program should display that value otherwise do nothing.

Note the use of not(!) operator.#include <iostream.h>#include<math.h>int main(){

int a;cout<<"Enter the Value: ";cin>>a;cout<<"\n";

if(a!=0){

cout<<"Value is: "<<a<<endl;}cout<<"\n\n";return 0;

}------------------------------------------------------------------------------------------------------------Write a program which will take the integer value from the user and then the program tells us that whether the integer entered is odd or even.

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

int a,b;cout<<”Enter the Integer Value: “;cin>>a;b = a % 2;if(b == 0) // if(a%2 == 0){

cout<<”Integer Entered is Even”<<”\n\n”;}else {

cout<<”Integer Entered is Odd”<<”\n\n”;}

return 0;}------------------------------------------------------------------------------------------------------------Write a program in which the user can enter the age of a person. If the age of a person is from 1 to 15, the program should display, person is teenager, and if the age is between 16 to 35, the program should display that person is young, and if the age is between 36 to 50 the program should display that person is in mid-age, and if he is above 50, the program should display that he is old.

In this program we have to use And operators in our conditions.Note: Note the indentation in the Program below. Please make a habit to write a

code in a way below code is written.

Program:

2

Page 3: Conditional structure

#include <iostream.h>#include<math.h>int main(){

int age;cout<<"Enter the age of a Person: ";cin>>age;cout<<"\n";if(age>=1 && age<=15){cout<<"Person is a Teenager"<<endl;}

else if(age>=16 && age<=35){cout<<"Person is Young"<<endl;}

else if(age>=36 && age<=50){cout<<"Person is in Mid-Age"<<endl;}

else {cout<<"Person is Old"<<endl;}

cout<<"\n\n";return 0;

}------------------------------------------------------------------------------------------------------------

3

Page 4: Conditional structure

------------------------------------------------------------------------------------------------------------Write a program which will take the value from the user between 1 to 10. And if the value entered is divisible by 3 then the program should display that the value is divisible by 3 otherwise display invalid.

Now between 1 to 10, three values are divisible by 3 i.e. 3,6 & 9. So, you may use a OR operator in this case.

Program:

#include <iostream.h>#include<math.h>int main(){

int a;cout<<"Enter the age of a Person: ";cin>>a;cout<<"\n";if(a==3 || a==6 || a==9){

cout<<"Value is divisible by 3"<<endl;}else{cout<<"Invalid";}cout<<"\n\n";return 0;

}------------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------------Write a program as written below, and enter characters from keyboard like: a, b, c, A, ; , ! and ^, note the output, you`ll always get output 0.

Remember: C++ Compiler characterized the special characters ;,>,<,etc under char category.

#include <iostream.h>

int main(){

int a;

4

Page 5: Conditional structure

cout<<"Enter the Character: ";cin>>a;

cout<<a;

cout<<"\n\n";

return 0;}------------------------------------------------------------------------------------------------------------Write a program as written below, and enter characters from keyboard like: a, b, c, A and note the output, if you’ll enter single character then you’ll get the desired result but if you’ll enter the word like cat, house then you’ll get only the first character of that word. Now, how can we get the full word, later we will cover String Topic, which will remove this restriction. But for the time being, you’ll play with a single character.

You can also check the output by entering the special characters: ; ,) ,! ,@ etc. And also you can see the output by giving the integer like 4556, 2323 even in this case the output shows only the first character.

#include <iostream.h>

int main(){

char a;

cout<<"Enter the Character: ";cin>>a;

cout<<a;

cout<<"\n\n";

return 0;}------------------------------------------------------------------------------------------------------------Write a program as below and note the output of the following code:#include <iostream.h>

int main(){

char a;

cout<<"Enter the Character: ";cin>>a;

if(a==c){cout<<a;}

cout<<"\n\n";

return 0;}

5

Page 6: Conditional structure

You`ll get the output as an error i.e. undeclared identifier c; or something like that. You`ll already know that you cant play with characters in case int. So, in order to compare the characters you have to made the following change in the if line.

if(a==’c’)Now, your code will not give you any errors. And also see the output. Now, if you want to compare the value without giving and commas (like we did above a==’c’), then you have to give its ASCII (ASCII (American Standard Code for Information Interchange) value, like ASCII value of c is 99.So, replace the if line i.e. if(a==’c’) with if(a==99), and note the output again.

#include <iostream.h>

int main(){

char a;

cout<<"Enter the Character: ";cin>>a;

if(a==’c’) // Same as if(a==99){cout<<a;}

cout<<"\n\n";

return 0;}------------------------------------------------------------------------------------------------------------Now, by using the following code, you can also detect that the following ASCII value belongs to which character. #include <iostream.h>

int main(){

char a;

a=45;

cout<<a;

cout<<"\n\n";

return 0;}------------------------------------------------------------------------------------------------------------Q1: Write a program which will determine the roots of the equation. The program also tells us that whether the roots are real or imaginary.------------------------------------------------------------------------------------------------------------Q2: A palindrome is a number or text phrase that reads the same backwards as forwards. For each example, each of the following five digits is palindrome: 12231, 54425, 24441 and 11611. Write a program that reads in a five-digit integer and determines whether it is a palindrome or not.

6

Page 7: Conditional structure

Hint: Use the division and modulus operators to separate the numbers into individualDigits.

------------------------------------------------------------------------------------------------------------Q3: A certain grade of steel is graded according to the following conditions:

(1) Hardness must be greater than 50.(2) Carbon contents must be less than 0.7.(3) Tensile strength must be greater than 500.

The grades are as follows:

Grade is 10 if all three conditions are met.Grade is 9 if conditions (i) and (ii) are met.Grade is 8 if condition (ii) and (iii) are met.Grade is 7 if condition (i) and (iii) are met.Grade is 6 if only one condition is met.Grade is 5 if none of the conditions are met.

Write a program which will require the user to give values of harness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.

------------------------------------------------------------------------------------------------------------Q4: Write a program in which we will consider the ages of four persons, name of the following persons with respective ages are as follow:

Salman is 22 years old,Noman is 15 years old,Zeeshan is 12 years old &Rehman is 7 years old,

The program should take the name from the user and display his respective age.Remember: When you enter the name, it will take only the first word, so in comparison you can only consider the first character.------------------------------------------------------------------------------------------------------------Q5: Any character is entered through the keyboard; write a program to determine whether the character entered is a capital letter, a small letter, a digit or a special symbol. The following table shows the range of ASCII values for various characters:

Characters ASCII ValuesA-Za-z0-9special symbols

65-9097-12248-570-47, 58-64, 91-96, 123-127

------------------------------------------------------------------------------------------------------------Q6: An insurance company follows following rules to calculate premium.

(a) If a person’s health is excellent and the person is between 25 and 35 years of age and lives in a city and is a male then the premium is Rs. 4 per thousand and his policy amount cannot exceed Rs. 2 lakhs.

(b) If a person satisfies all the above conditions except that the sex is female then the premium is Rs. 3 per thousand and her policy amount cannot exceed Rs. 1 lakh.

(c) If a person’s health is poor and the person is between 25 and 35 years of age and lives in a village and is a male then the premium is Rs. 6 per thousand and his policy cannot exceed Rs. 10,000.

(d) In all other case the person is not ensured.

Write a program which will ask you to enter the person’s health, sex, age and policy amount. If the policy amount do not exceed the limit then it will calculate the

7

Page 8: Conditional structure

premium of the person according to above given criteria otherwise says that policy amount exceeds the limit. Note: Now here you cannot enter the complete word, like ‘Excellent’ you have to just enter the first word of Excellent i.e. E or e whatever you like. You can see the behavior of a program by entering the full word like ‘Excellent’, then it will not ask you the remaining inputs because it will take the input from the remaining word of Excellent word.The above program works with a full word because they have only the single output while this program takes the multiple outputs.

------------------------------------------------------------------------------------------------------------Q7: A Company estimates salary of any job holder as

I) If basic pay is less then 1500, company provides house rent allowance @ 10%, dearness allowance@20%, tearness allowance@50%.

II) If basic pay is greater then or equal to 1500, company provides house rent allowance @ 50%, dearness [email protected]%, tearness allowance@50%,adhac allowance@30%.

Write a program that input salary of any job holder and calculate his total salary.------------------------------------------------------------------------------------------------------------Q8: Write a program that input X and y co-ordinates of a point in the co-ordinate plane. Based on these values, it determine whether it lies, on X or Y axis or any of the four quadrants?------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Q9: Write a program that input an integer and tells whether it is even or odd?------------------------------------------------------------------------------------------------------------Q10: Write a program which will take the year as input from the user. Write a program to find whether the year is leap or not?------------------------------------------------------------------------------------------------------------Q11: Write a program that input an integer and find it is divisible by 3 or not using conditional operator?------------------------------------------------------------------------------------------------------------Q12: Write a program that input salary. If salary is 20K or more it deducts 7% of salary, if salary is l0K and less then 20K it deducts 1K of salary. If salary is less then 10Kdeducts nothing and calculates total salary.------------------------------------------------------------------------------------------------------------Q13: Write a program that input 3 numbers. If a is not zero, find it is common divisor of b and c?------------------------------------------------------------------------------------------------------------Q14: Write a program that input five digit numbers and find its reverse. Determine that input number is equal to reverse number or not?------------------------------------------------------------------------------------------------------------Q15: According to the Georgian Calendar, it was Monday on the date 01/01/01. If any year is input through the keyboard. Write a program to find out what is the day on 1st

January of the year?------------------------------------------------------------------------------------------------------------Q14: While purchasing certain items, a discount of 10% is offered if the quantity purchased is more then 10,000. If input through keyboard. Write a program to calculate total expense?------------------------------------------------------------------------------------------------------------Q 17: Write a program to input current year and joining year in which employee joined the organization are entered through the keyboard. If the number of years for which the employee has served the organization of greater then 3, then bonus of Rs.2500/- is given to the employee. If the year of service are not greater then 3, then program should do nothing?

8

Page 9: Conditional structure

------------------------------------------------------------------------------------------------------------Q 18: If age of Ali, Irfan and Rehman are entered through the keyboard. Write a program to find the youngest one of three?------------------------------------------------------------------------------------------------------------Q 19: Write a program to check whether a triangle is valid or not when the three angles of the triangle are entered through the keyboard. A triangle is valid if sum of all the three angle is equal to 1800?------------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------------Q 20: Given the coordinates (x, y) of a center of a circle and it’s radius. Write a program which will determine whether a point lies inside the circle, on the circle or outside of the circle?------------------------------------------------------------------------------------------------------------Q 21: Given three points (x1, y1), (x2, y2), (x3, y3). Write a program to check if all the three points fall on one straight line?------------------------------------------------------------------------------------------------------------Q 22: Any year entered through the keyboard. Write a program to determine whether the year is leap year or not. Use the logical operator && and ||?------------------------------------------------------------------------------------------------------------Q23: If the three sides of a triangle are entered through the keyboard. Write a program to check whether the triangle is isosceles, equilateraland scalene or right angle triangle?------------------------------------------------------------------------------------------------------------Q 24: A library charges a fine for every book returned late. For first 5 days the fine is 50 paise, for 6-10 days fine is one rupee and above 10 days fine is 5 rupees. If you return book after 30 days your membership will be cancelled. Write a program to accept the number of days the member is late to return the book and display the fine or the appropriate message?------------------------------------------------------------------------------------------------------------Q 25: Write a program using conditional operator to determine whether a year entered through the keyboard is leap year or not?------------------------------------------------------------------------------------------------------------Q 26: Write a program to input the current reading and previous reading of electric meter. Find out the total units consumed by using Nested “if else” structure and compute the electricity bill as:

I. If the units consumed are less than or equal to 300 then rate of electricity is Rs. 3 per unit

II. If the units consumed are more than 300 and less than or equal to 400 rate of electricity is Rs. 4 per unit.

III. If the units consumed are more than 400 then rate of electricity is Rs. 5 per unit.------------------------------------------------------------------------------------------------------------Q 27: Write a program that input salary and grade. It adds 50% bonus if the grade is greater than 15. It adds 25% bonus if the grade is 15 or less and display the total salary?------------------------------------------------------------------------------------------------------------Q 28: Write a program that input two integers. It determines and prints if the first integer is multiple of second integer?------------------------------------------------------------------------------------------------------------Q 29: Write a program that input two integers. It determines and prints if the first integer is square of second integer?------------------------------------------------------------------------------------------------------------

9

Page 10: Conditional structure

------------------------------------------------------------------------------------------------------------Q 30: Write a program that input radius and user choice. It calculate area of circle if the user enter 1 as choice. It calculate circumference if the user enter 2 as choice?------------------------------------------------------------------------------------------------------------Q 31: Write a program that input number of weeks day and display the name of the day?------------------------------------------------------------------------------------------------------------Q 32: Write a program that input a character form the user and checks whether it is a vowel or constant?------------------------------------------------------------------------------------------------------------Q 33: Write a program to input two floating values and operators according to user choice. And perform operation according to the given operator?------------------------------------------------------------------------------------------------------------Q 34: Write a program that displays the following menu of health club.

1. Standard Adult Membership2. Child Membership3. Senior Citizen Membership4. Quit The Program

It input choice and number of months and calculates membership charges as followsChoice Charges Per Month

Standard Adult Membership Rs. 50 Child Membership Rs. 20Senior Citizen Membership Rs. 30

------------------------------------------------------------------------------------------------------------Q 35: Write a program that input converts ASCII number to character and vice versa. The program should display the following menu.

1. Convert ASCII Value to Character2. Convert Character to ASCII Value

------------------------------------------------------------------------------------------------------------Q 36: Write a program that convert MILITARY TIME to STANDARD TIME?------------------------------------------------------------------------------------------------------------Q 37: Write a program that input three values a , b and c. Print the root if real of the quadratic equation ax2 + bx + c=0. Sample input 1(a=1, b=1,c=60 then root should be calculate and displayed. If value of b is ZERO then output should be displayed “Sorry the Roots are Not Real”?------------------------------------------------------------------------------------------------------------Q 38:Write a program that input year and month. It displays number of days in month of the year entered by the user. For example, if the user enter 2010 in year and 3 in month, the program should display “March 2010 Has 31 Days.”?------------------------------------------------------------------------------------------------------------Q 39: Write a program that input basic salary of an employee from the user. It deducts the income tax from the salary on the following basis:

I. 20% income tax if the salary is above Rs. 30000II. 15% income tax if the salary is between Rs. 20000 and Rs. 30000

III. 10% income tax if the salary is belowRs. The program then finally displays total salary, income tax and the net salary.------------------------------------------------------------------------------------------------------------Q 40: Write a program that contains an if statement that may be used to compute the area of square (area=side*side) or a triangle (area=1/2*base*height) after prompting the user to type the first character of the figure name s or t?------------------------------------------------------------------------------------------------------------Q 41: Write a Program to get character form the user and determine whether it is capital or small?------------------------------------------------------------------------------------------------------------

10

Page 11: Conditional structure

------------------------------------------------------------------------------------------------------------Q 41: Write a code to get three number from user and tells whether entered number is Zero, +VE or –VE?------------------------------------------------------------------------------------------------------------Q 42: Write a program that input purchase price and sale price and tells whether it is profit or loss?------------------------------------------------------------------------------------------------------------Q 43: Write a program which inputs a person’s height (in centimeters) and weight (inkilograms) and outputs one of the messages: underweight, normal, oroverweight, using the criteria:

Underweight: weight < height/2.5Normal: height/2.5 <= weight <= height/2.3Overweight: height/2.3 < weight

------------------------------------------------------------------------------------------------------------Q 44: Write a program which inputs a date in the format dd/mm/yy and outputs it in theformat month dd, year. For example, 25/12/61 becomes:

December 25, 1961------------------------------------------------------------------------------------------------------------Q45: Write a program that input for students’ final grades in a given class (the grades are integer values in the range 1-9) The program then displays the class grade average, the highest grade, and how many students in the class failed the course (a grade less than 4 is a failing grade).#include <iostream>#include <stdio.h>

int main() { int grade, count, highest, failed;double sum, average; count = 0;char choice;sum = 0;highest = 0;failed = 0;{  cout << "Enter student's grade:";  cin >> grade;  if( grade >=1 && grade <=9 )  {     sum = sum + grade;    if ( grade > highest )         highest = grade;    if ( grade < 4 )      ++failed;    ++count;  }  else      cout << "Invalid grade Input\n";  cout << "Do you want enter more Grade Y/N :";  cin >> choice;}average = sum / count; cout << endl;cout << "Class average: " << average << endl;cout << "Highest grade: " << highest << endl; cout << "Number of students that failed the course: " << failed << endl;cin.get();return 0;}

11

Page 12: Conditional structure

------------------------------------------------------------------------------------------------------------Q46: Find the absolute value of a number entered by the user#include<iostream.h>#include<conio.h>int main(){

int a;cout<<"Enter any number:";cin>>a;if(a>0)

cout<<"The absolute value of number is:"<<a;else

cout<<"The absolute value of number is:"<<-(a);getch();return 0;

}------------------------------------------------------------------------------------------------------------Q47: Write a program that check whether the bank transaction is a deposit, withdrawal, valid transfer or invalid transfer.#include <iostream.h>#include <stdlib.h>int main(){float amount;char transaction_code;cout<<"D - Cash Deposit, W - Cash Withdrawal, T - Cash Transfer\n";cout<<"\nEnter the transaction code(D, W, T); ";cin>>transaction_code;if (transaction_code == 'D'){cout<<"\nDeposit transaction";cout<<"\nEnter amount: ";cin>>amount;cout<<"\nPROCESSING....Please Wait";cout<<"\nAmount deposited: "<<amount;cout<<"\n---THANK YOU!/---";}elseif (transaction_code == 'W'){cout<<"\nWithdrawal transaction";cout<<"\nEnter amount: ";cin>>amount;cout<<"\nPROCESSING....Please Wait";cout<<"\nAmount withdrawn: "<<amount;cout<<"\n---THANK YOU!/---";}elseif (transaction_code == 'T'){cout<<"\nTransfer transaction";cout<<"\nEnter amount: ";cin>>amount;cout<<"\nPROCESSING....Please Wait";

12

Page 13: Conditional structure

cout<<"\nAmount transferred: "<<amount;cout<<"\n---THANK YOU!/---";}else {cout<<"\nInvalid transaction!!";cout<<"D = Deposit, W = Withdrawal, T = Transfer";cout<<"\nPlease enters the correct transaction code: ";}cout<<"\n";system("pause");return 0;} ------------------------------------------------------------------------------------------------------------Q48: Write a program for the menu selection such as Append, Modify, Delete & Exit though Case Structure.------------------------------------------------------------------------------------------------------------Q49: Write a program that if the user types in the correct password, he/she will be logged in; If it's a wrong password, it will not let him/her log in.------------------------------------------------------------------------------------------------------------Q50:Write a program that determines a student’s grade. The program will read three types of scores(quiz, mid-term, and final scores) and determine the grade based on the following rules:-if the average score =90% =>grade=A -if the average score >= 70% and <90% => grade=B -if the average score>=50% and <70% =>grade=C -if the average score<50% =>grade=FSolution:#include <cstdlib>#include <iostream>#include<iomanip> using namespace std;  int main(int argc, char *argv[]) {    float x;    float y;    float z;    float avg;    cout<<"Enter 3 score(quiz, mid-term, and final) vales separated by space:";    cin>>x>>y>>z;    avg=(x+y+z)/3;    if(avg>=90)cout<<"Grade A";    else if((avg>=70) && (avg<90)) cout<<"Grade B";    else if((avg>=50) && (avg<70))cout<<"Grade C";    else if(avg<50) cout<<"Grade F";    else cout<<"Invalid";    cout<<"\n";    system("PAUSE");    return EXIT_SUCCESS; }------------------------------------------------------------------------------------------------------------Q51:Write a program in which the user get working time (hours, minutes & seconds) of employee 5 times and finally determines the longest time duration of working hours.------------------------------------------------------------------------------------------------------------

13

Page 14: Conditional structure

------------------------------------------------------------------------------------------------------------Q52:Write a program that determine the designation of the employer on the base of job title and service duration.Solution:

#include <iostream.h>#include <stdlib.h>int main() {char job_title; int years_served, no_of_pub; cout<<"Enter data \n"; cout<<"Current job (Tutor-T, lecturer-L, Assoc prof-A): "; cin>>job_title; cout<<"Years served: "; cin>>years_served; cout<<"No of publication: "; cin>>no_of_pub; if(job_title == 'T') { if(years_served > 15) if(no_of_pub > 10) cout<<"\nPromote to lecturer"; else cout<<"\nMore publications required"; else cout<<"\nMore service required"; }else if(job_title == 'L') { if(years_served > 10) if(no_of_pub > 5) cout<<"\nPromote to Assoc professor"; else cout<<"\nMore publications required"; else cout<<"\nMore service required"; }else if(job_title == 'A') { if(years_served > 5) if(no_of_pub > 5) cout<<"\nPromote to professor"; else cout<<"\nMore publications required"; else cout<<"\nMore service required"; }cout<<"\n"; system("pause"); return 0;

}

14

Page 15: Conditional structure

Practice Exercise:Write expressions for the following:

To test if a number n is even. To test if a character c is a digit. To test if a character c is a letter. To do the test: n is odd and positive or n is even and negative. To set the n-th bit of a long integer f to 1. To reset the n-th bit of a long integer f to 0. To give the absolute value of a number n. To give the number of characters in a null-terminated string literal s.

What Is the OUTPUT of The Following?# include "stdio.h"main(){ int a=300,b,c; if(a>=400) b=300; c=200; printf("\n%d%d",b,c);}

# include "stdio.h"main(){ int x=10,y=20; if(x==y) b=300; c=200; printf("\n%d%d",x,y);}

# include "stdio.h"main(){ int x=3,y,z; y=x=10; z=x<10; printf("\nx=%dy=%d z=%d",x,y,z);}

# include "stdio.h"main(){ int i = 65; char j='A'; if (i==j)printf("C Is WOW"); else printf("CIs Headache");}

# include "stdio.h"main(){ int i=4; z=12; if(i=5&&z>5) printf("Let us Ceeeeee"); else Printf("SK Ahsan");}

# include "stdio.h"main(){ int a=40; if(a>40&&a<45) printf("a si greater than 40 and less than 45"); else printf("%d", a);}

# include <stdio.h>main(){ int x=20, y=40, z=45' if(x>y&&x>z) printf("X is Greater"); if(y>x&&y>z) printf("Y is Greater"); if(z>x&&z>y) printf("Z is Greater");}

# include <stdio.h>main(){ int j=4,k; k=!5&&j; printf("\nK=%d" , k);}

Point out the errors if any, in the following programs?# include "stdio.h"main(){ float a=12.25, b=12.52; if(a=b) printf("A and B are Equal");}

# include "stdio.h"main(){ int x=10,y=15; if(x%2=y%3) printf("Carpathians");}

15

Page 16: Conditional structure

# include <stdio.h>main(){ int i=2, j=5; if(i==2 && j==5) printf("Satisfied At Least");}

# include <stdio.h>main(){ int i=10, j=20; if(i=5)&& if(j=10) printf(Have a Nice day Plz);}

------------------------------------------------------------------------------------------------------------

Case Study 1: Cryptography (Encryption -- Decryption)A company wants to transmit data over the telephone, but is concerned that its phones can be tapped. All the data are transmitted as four digit integers. The company has asked you to write a program that encrypts that data so that it can be transmitted more securely. Your program should read a four digit integer and encrypt it as follows: Replace each digit by (the sum of that digit plus 7) modulus 10. Then, swap the first digit with the third, swap the second digit with fourth and print the encrypted integer.

Write a separate program that inputs an encrypted four digit integer and decrypts it to form the original number.

-----------------------------------------------------------------------------------------------------------

Sunawar Khan Ahsan

For solution contact me at 03334892200Mail: [email protected]

-----------------------------------------------------------------------------------------------------------

S.K. Ahasn

16