Chapter 3: C++ Constructs

C11SIZE1, Page number:232

In [1]:
#Size of floating-point values
import sys
x=0.0
print "The size of floating-point variables on this computer is "
print sys.getsizeof(x) #depends on the compiler 
The size of floating-point variables on this computer is 
24

C11COM1, Page number:233

In [2]:
#Illustrates the sequence point.
num=5
sq,cube=num*num,num*num*num
#Result
print "The square of ",num,"is",sq
print "and the cube is ",cube
The square of  5 is 25
and the cube is  125

C11ODEV, Page number:239

In [3]:
#Uses a bitwise & to determine whether a number is odd or even.
input1=input("What number do you want me to test?")
if input1&1:
    print "The number ",input1,"is odd"
else:
    print "The number ",input1,"is even"
What number do you want me to test?5
The number  5 is odd

C12WHIL1, Page number:248

In [5]:
ans=raw_input("Do you want to continue (Y/N)")
while ans!='Y' and ans!='N':
    print "\nYou must type a Y or an N\n"
    ans=raw_input( "Do you want to continue(Y/N)?")
Do you want to continue (Y/N)k

You must type a Y or an N

Do you want to continue(Y/N)?c

You must type a Y or an N

Do you want to continue(Y/N)?s

You must type a Y or an N

Do you want to continue(Y/N)?5

You must type a Y or an N

Do you want to continue(Y/N)?Y

C12WHIL3, Page number:251

In [6]:
#Number of letters in the user's name
name=raw_input("What is your first name?")
count=len(name)
print "Your name has ",count,"characters"
What is your first name?greg
Your name has  4 characters

C12INV1, Page number:253

In [7]:
print "*** Inventory computation ***\n"
while True:
    part_no=input("What is the next part number(-999 to end)?\n")
    if part_no!=-999:
        quantity=input("How many were bought?\n")
        cost=input("What is the unit price of this item?\n")
        ext_cost=cost*quantity
        print "\n",quantity,"of #",part_no,"will cost","%.2f" %ext_cost,"\n"
    else:
        break
print "End of Inventory computation"
*** Inventory computation ***

What is the next part number(-999 to end)?
213
How many were bought?
12
What is the unit price of this item?
5.66

12 of # 213 will cost 67.92 

What is the next part number(-999 to end)?
92
How many were bought?
53
What is the unit price of this item?
.23

53 of # 92 will cost 12.19 

What is the next part number(-999 to end)?
-999
End of Inventory computation

C12BRK, Page number:257

In [1]:
#Demonstrates the Break statement
while True:
    print "C++ is fun!\n"
    break
    user_ans=raw_input( "Do you want to see the message again(Y/N)?")
print "That's all for now"
C++ is fun!

That's all for now

C12CNT1, Page number:261

In [3]:
ctr=0
while ctr<10:
    print "Computers are fun!\n"
    ctr+=1
Computers are fun!

Computers are fun!

Computers are fun!

Computers are fun!

Computers are fun!

Computers are fun!

Computers are fun!

Computers are fun!

Computers are fun!

Computers are fun!

C12PASS1, Page number:263

In [3]:
stored_pass=11862
num_tries=0
while num_tries<3:
    user_pass=input("\nWhat is the password? (you get 3 tries...)?")
    num_tries+=1
    if user_pass==stored_pass:
        print "You entered the correct password.\n"
        print "The cash safe is behind the picture of the ship."
        exit()
    else:
        print "You entered the wrong password.\n"
        if num_tries==3:
            print "Sorry, you get no more chances"
        else:
            print "you get ",3-num_tries,"more tries...\n"
exit(0)
What is the password? (you get 3 tries...)?11202
You entered the wrong password.

you get  2 more tries...


What is the password? (you get 3 tries...)?23265
You entered the wrong password.

you get  1 more tries...


What is the password? (you get 3 tries...)?36963
You entered the wrong password.

Sorry, you get no more chances

C12GRAD1, Page number:266

In [1]:
#Adds grades and determines whether you earned an A.
total_grade=0.0
while 1:
    grade=input("What is your grade?(-1 to end)")
    if grade>=0.0:
        total_grade+=grade
    if grade==-1:
        break
#Result
print "\n\nYou made a total of ","%.1f" %total_grade,"points\n"
if total_grade>=450.00:
    print "** You made an A !!"
What is your grade?(-1 to end)87.6
What is your grade?(-1 to end)92.4
What is your grade?(-1 to end)78.7
What is your grade?(-1 to end)-1


You made a total of  258.7 points

C12GRAD2, Page number:267

In [3]:
total_grade=0.0
grade_avg=0.0
grade_ctr=0
while 1:
    grade=input("What is your grade?(-1 to end)")
    if grade>=0.0:
        total_grade+=grade
        grade_ctr+=1
    if grade==-1:
        break
grade_avg=total_grade/grade_ctr
#Result
print "\n\nYou made a total of ",'%.1f' %total_grade,"points\n"
print "Your average was ",'%.1f' %grade_avg,"\n"
if total_grade>=450.00:
    print "** You made an A !!"
What is your grade?(-1 to end)67.8
What is your grade?(-1 to end)98.7
What is your grade?(-1 to end)67.8
What is your grade?(-1 to end)92.4
What is your grade?(-1 to end)-1


You made a total of  326.7 points

Your average was  81.7 

C13FOR1, Page number:276

In [4]:
#for loop example
for ctr in range(1,11):
    print ctr,"\n"
1 

2 

3 

4 

5 

6 

7 

8 

9 

10 

C13FOR2, Page number:278

In [5]:
#Demonstrates totaling using a for loop.
total=0
for ctr in range(100,201):
    total+=ctr
#Result
print "The total is ",total
The total is  15150

C13EVOD, Page number:281

In [6]:
print "Even numbers below 21"
#Result
for num in range(2,21,2):
    print num," ",
    print "\n\nOdd numbers below 20"
#Result
for num in range(1,21,2):
    print num," ",
Even numbers below 21
2   4   6   8   10   12   14   16   18   20   

Odd numbers below 20
1   3   5   7   9   11   13   15   17   19  

C13CNTD1, Page number:282

In [8]:
for ctr in range(10,0,-1):
    print ctr
print "*** Blast off! ***\n"
10
9
8
7
6
5
4
3
2
1
*** Blast off! ***

C13FOR4, Page number:283

In [9]:
total=0.0
print "\n*** Grade Calculation ***\n"
num=input("How many students are there?\n")
for loopvar in range(0,num,1):
    grade=input("What is the next student's grade?\n")
    total=total+grade
avg=total/num
#Result
print "\n the average of this class is",'%.1f' %avg
*** Grade Calculation ***

How many students are there?
3
What is the next student's grade?
8
What is the next student's grade?
9
What is the next student's grade?
7

 the average of this class is 8.0

C13FOR6, Page number:285

In [11]:
num=5
print "\nCounting by 5s:\n"
for num in range(5,101,5):
    print "\n",num
Counting by 5s:


5

10

15

20

25

30

35

40

45

50

55

60

65

70

75

80

85

90

95

100

C13NEST1, Page number:288

In [13]:
for times in range(1,4,1):
    for num in range(1,6,1):
        print num,
    print "\n"
1 2 3 4 5 

1 2 3 4 5 

1 2 3 4 5 

C13NEST2, Page number:289

In [6]:
#for loop
for outer in range(6,-1,-1):
    for inner in range(1,outer,1):
        print inner,
    print "\n"
1 2 3 4 5 

1 2 3 4 

1 2 3 

1 2 

1 





C13FACT, Page number:291

In [1]:
#factorial
num=input("What factorial do you want to see?")
total=1
for fact in range(1,num+1,1):
    total=total*fact        
print "The factorial for ",num,"is",total
What factorial do you want to see?7
The factorial for  7 is 5040

C14CNTD1, Page number:297

In [4]:
for cd in range(10,0,-1):
    for delay in range(1,10,1):   #for delay in range(1,30001,1):
        print " "
    print cd,"\n"
print "*** Blast off! ***\n"
 
 
 
 
 
 
 
 
 
10 

 
 
 
 
 
 
 
 
 
9 

 
 
 
 
 
 
 
 
 
8 

 
 
 
 
 
 
 
 
 
7 

 
 
 
 
 
 
 
 
 
6 

 
 
 
 
 
 
 
 
 
5 

 
 
 
 
 
 
 
 
 
4 

 
 
 
 
 
 
 
 
 
3 

 
 
 
 
 
 
 
 
 
2 

 
 
 
 
 
 
 
 
 
1 

*** Blast off! ***

C14TIM, Page number:298

In [5]:
age=input("What is your age?\n")    #Get age
while age<=0:
    print "*** Your age cannot be that small ! ***"
    for outer in range(1,3,1):    #outer loop
        for inner in range(1,50,1):  #inner loop
            print ""
        print "\r\n\n"
        age=input("What is your age?\n")
print "Thanks, I did not think you would actually tell me your age!"
What is your age?
20
Thanks, I did not think you would actually tell me your age!

C14BRAK1, Page number:299

In [6]:
print "Here are the numbers from 1 to 20\n"
for num in range(1,21,1):
    print num,"\n"
    break #break statement
print "That's all, folks!"
Here are the numbers from 1 to 20

1 

That's all, folks!

C14BRAK2, Page number:300

In [7]:
#A for loop running at the user’s request.
print "Here are the numbers from 1 to 20\n"
for num in range(1,21,1):
    print num
    ans=raw_input("Do you want to see another (Y/N)?")
    if ans=='N' or ans=='n':
        break
print "That's all, folks!\n"
Here are the numbers from 1 to 20

1
Do you want to see another (Y/N)?y
2
Do you want to see another (Y/N)?y
3
Do you want to see another (Y/N)?y
4
Do you want to see another (Y/N)?y
5
Do you want to see another (Y/N)?y
6
Do you want to see another (Y/N)?y
7
Do you want to see another (Y/N)?y
8
Do you want to see another (Y/N)?y
9
Do you want to see another (Y/N)?y
10
Do you want to see another (Y/N)?N
That's all, folks!

C14BRAK3, Page number:302

In [8]:
total=0.0
count=0
print "\n*** Grade Calculation ***\n"
num=input("How many students are there?")
for loopvar in range(1,num+1,1):
    grade=input("What is the next student's grade? (-99 to quit)")
    if grade<0.0:
        break
    count+=1
    total+=grade
avg=total/count
#Result
print "The average of this class is ",'%.1f' %avg
*** Grade Calculation ***

How many students are there?10
What is the next student's grade? (-99 to quit)87
What is the next student's grade? (-99 to quit)97
What is the next student's grade? (-99 to quit)67
What is the next student's grade? (-99 to quit)89
What is the next student's grade? (-99 to quit)94
What is the next student's grade? (-99 to quit)-99
The average of this class is  86.8

C14CON1, Page number:305

In [10]:
#Demonstrates the use of the continue statement.
for ctr in range(1,11,1):
    print ctr,
    continue
    print "C++ programming"
1 2 3 4 5 6 7 8 9 10

C14CON3, Page number:306

In [11]:
#Average salaries over $10,000
avg=0.0
total=0.0
month=1.0
count=0
while month>0.0:
    month=input("What is the next monthly salary (-1) to quit")
    year=month*12.00
    if  year <= 10000.00:               #Do not add low salaries
        continue
    if month<0.0:
        break
    count+=1
    total+=year                           #Add yearly salary to total.
avg=total/float(count)
#Result
print "\nThe average of high salaries is $",'%.2f' %avg
What is the next monthly salary (-1) to quit500
What is the next monthly salary (-1) to quit2000
What is the next monthly salary (-1) to quit750
What is the next monthly salary (-1) to quit4000
What is the next monthly salary (-1) to quit5000
What is the next monthly salary (-1) to quit1200
What is the next monthly salary (-1) to quit-1

The average of high salaries is $ 36600.00

C15BEEP1, Page number:314

In [4]:
def beep():
    import os
    os.system('\a')
num=input("Please enter a number:")
#Use multiple if statements to beep.
if num==1:
    beep()
else:
    if num==2:
        beep()
        beep()
    else:
        if num==3:
            beep()
            beep()
            beep()
        else:
            if num==4:
                beep()
                beep()
                beep()
                beep()
            else:
                if num==5:
                    beep()
                    beep()
                    beep()
                    beep()
                    beep()
Please enter a number:2

C15SALE, Page number:319

In [19]:
#Prints daily, weekly, and monthly sales totals.
daily=2343.34
weekly=13432.65
monthly=43468.97
ans=raw_input("Is this the end of the month? (Y/N) :")
if ans=='Y' or ans=='y':
    day=6
else:
    day=input("What day number , 1 through 5( for mon-fri) :")
if day==6:
    print "The monthly total is ",'%.2f' %monthly
else:
    if day==5:
        print "The weekly total is ",'%.2f' %weekly
    else:
        print "The daily total is ",'%.2f' %daily    
Is this the end of the month? (Y/N) :Y
The monthly total is  43468.97

C15DEPT1, Page number:320

In [21]:
choice="R"
while choice!='S' and choice!='A' and choice!='E' and choice!='P':
    print "\n choose your department :"
    print "S - Sales"
    print "A - Accounting"
    print "E - Engineering"
    print "P - Payroll"
    choice=raw_input( "What is your choice? (upper case)")
if choice=='E':
    print "Your meeting is at 2:30"
else:
    if choice=='S':
        print "Your meeting is at 8:30"
    else:
        if choice=='A':
            print "Your meeting is at 10:00"
        else:
            if choice=='P':
                print "your meeting has been cancelled"
 choose your department :
S - Sales
A - Accounting
E - Engineering
P - Payroll
What is your choice? (upper case)E
Your meeting is at 2:30