SlideShare a Scribd company logo
1 of 5
Download to read offline
Eric Roberts Handout #7 
CS106B April 3, 2009 
Assignment #1—Simple C++ 
Parts of this handout were written by Julie Zelenski 
Due: Friday, April 10 
Part 1. Get your C++ compiler working 
Your first task is to set up your C++ compiler. If you’re using the machines in Stanford’s 
public clusters, you don’t need to do anything special to install the software. If you’re 
using you own machine, you should consult one of the following handouts, depending on 
the type of machine you have: 
• Handout #7M. Downloading XCode on the Macintosh 
• Handout #7P. Downloading Visual Studio for Windows 
Once you have the compiler ready, go to the assignments section of the web site and 
download the starter file for the type of machine you are using. For either platform, the 
Assignment1 folder contains six separate project folders: one for this warmup problem 
and one for each of the five problems in Part 2 of the assignment. Open the project file in 
the folder named 0-Warmup. Your mission in Part 1 of the assignment is simply to get 
this program running. The source file we give you is a complete C++ program—so 
complete, in fact, that it comes complete with two bugs. The errors are not difficult to 
track down (in fact, we’ll tell you that one is incorrect arguments to a function call and 
the other is a needed #include statement is missing). This task is designed to give you a 
little experience with the way errors are reported by the compiler and what it takes to fix 
them. 
Once you fix the errors, compile and run the program. When the program executes, it 
will ask for your name. Enter your name and it will print out a “hash code” (a number) 
generated for that name. We’ll talk later in the class about hash codes and what they are 
used for, but for now just run the program, enter your name, and record the hash code. 
You’ll email us this number. A sample run of the program is shown below: 
Please enter your name: Eric 
The hash code for your name is 339. 
Once you’ve got your hash code, we want you to e-mail it to your section leader and 
introduce yourself. You don’t yet know your section assignment, but will receive it via 
email after signups close, so hold on to your e-mail until then. I’d also appreciate if you 
would cc me on the e-mail (eroberts@stanford.edu) so I can meet you as well. 
Here’s the information to include in your e-mail: 
1. Your name and the hash code that was generated for it by the program 
2. Your year and major 
3. When you took 106A (or equivalent course) and how you feel it went for you 
4. What you are most looking forward to about 106B 
5. What you are least looking forward to about 106B 
6. Any information that might be helpful to us about how to best help you learn and 
master the course material
– 2 – 
Part 2. Simple C++ problems 
Most of the assignments in this course are single programs of a substantial size. To get 
you started, however, the first assignment is a series of five short problems that are 
designed to get you used to using C++ and to introduce the idea of functional recursion. 
None of these problems will require more than a page of code to complete; most can be 
solved in just a few lines. 
Problem 1 (Chapter 1, exercise 7, page 41) 
Greek mathematicians took a special interest in numbers that are equal to the sum of their 
proper divisors (a proper divisor of N is any divisor less than N itself). They called such 
numbers perfect numbers. For example, 6 is a perfect number because it is the sum of 
1, 2, and 3, which are the integers less than 6 that divide evenly into 6. Similarly, 28 is a 
perfect number because it is the sum of 1, 2, 4, 7, and 14. 
Write a predicate function IsPerfect that takes an integer n and returns true if n is 
perfect, and false otherwise. Test your implementation by writing a main program that 
uses the IsPerfect function to check for perfect numbers in the range 1 to 9999 by 
testing each number in turn. When a perfect number is found, your program should 
display it on the screen. The first two lines of output should be 6 and 28. Your program 
should find two other perfect numbers in the range as well. 
Problem 2 (Chapter 2, exercise 6, page 79) 
A histogram is a graphical way of displaying data by dividing the data into separate 
ranges and then indicating how many data values fall into each range. For example, 
given the set of exam scores 
100, 95, 47, 88, 86, 92, 75, 89, 81, 70, 55, 80 
a traditional histogram would have the following form: 
*** 
* * * 
* * * * * * 
0–9 10–19 20–29 30–39 40–49 50–59 60–69 70–79 80–89 90–99 100 
The asterisks in the histogram indicate one score in the 40s, one score in the 50s, five 
scores in the 80s, and so forth. 
When you generate histograms using a computer, however, it is usually much easier to 
display them sideways on the page, as in this sample run: 
0: 
10: 
20: 
30: 
40: * 
50: * 
60: 
70: ** 
80: ***** 
90: ** 
100: *
– 3 – 
Write a program that reads in an array of integers—ideally from a text file as described in 
Chapter 3—and then displays a histogram of those numbers, divided into the ranges 0–9, 
10–19, 20–29, and so forth, up to the range containing only the value 100. Your program 
should generate output that looks as much like the sample run as possible. 
Problem 3 (Chapter 3, exercise 2, page 116) 
Heads. . . . 
Heads. . . . 
Heads. . . . 
A weaker man might be moved to re-examine his faith, if in nothing 
else at least in the law of probability. 
—Tom Stoppard, Rosencrantz and Guildenstern Are Dead, 1967 
Write a program that simulates flipping a coin repeatedly and continues until three 
consecutive heads are tossed. At that point, your program should display the total 
number of coin flips that were made. The following is one possible sample run of the 
program: 
tails 
heads 
heads 
tails 
tails 
heads 
tails 
heads 
heads 
heads 
It took 10 flips to get 3 consecutive heads. 
Problem 4 (Chapter 5, exercise 8, page 201) 
The mathematical combinations function C(n, k) is usually defined in terms of factorials, 
as follows: 
C(n, k) = 
n! 
k! x (n–k)! 
The values of C(n, k) can also be arranged geometrically to form a triangle in which n 
increases as you move down the triangle and k increases as you move from left to right. 
The resulting structure, which is called Pascal’s Triangle after the French mathematician 
Blaise Pascal, is arranged like this: 
C(0, 0) 
C(1, 0) C(1, 1) 
C(2, 0) C(2, 1) C(2, 2) 
C(3, 0) C(3, 1) C(3, 2) C(3, 3) 
C(4, 0) C(4, 1) C(4, 2) C(4, 3) C(4, 4) 
Pascal’s Triangle has the interesting property that every entry is the sum of the two 
entries above it, except along the left and right edges, where the values are always 1. 
Consider, for example, the circled entry in the following display of Pascal’s Triangle:
– 4 – 
1 
1 
1 
1 
1 
1 
1 
2 
3 
4 
5 
6 
1 
3 
6 
10 
15 
1 
4 
10 
20 
1 
5 
15 
1 
1 6 1 
This entry, which corresponds to C(6, 2), is the sum of the two entries—5 and 10—that 
appear above it to either side. Use this relationship between entries in Pascal’s Triangle 
to write a recursive implementation of the C(n, k) function that uses no loops, no 
multiplication, and no calls to Fact. 
Write a simple test program to demonstrate that your combinations function works. And 
if you want an additional challenge, write a program that uses C(n, k) to display the first 
ten rows of Pascal’s Triangle. 
Problem 5 (Implementing IntToString) 
The strutils.h interface exports a method 
string IntegerToString(int n); 
that converts an integer into its representation as a string of decimal digits, so that, for 
example, IntegerToString(1729) should return the string "1729". Your job in this 
problem is to write a function IntToString that does the same thing as the function in 
strutils.h but with a recursive implementation. (The name is shortened in this 
exercise to avoid having your implementation conflict with the library version.) 
Fortunately, this function has a natural recursive structure because it is easy to break an 
integer down into two components using division by 10. This decomposition is discussed 
in Chapter 5, exercise 6, which shows how to divide 1729 into two pieces, like this: 
1 7 2 9 
1 7 2 
n / 10 
9 
n % 10 
If you use recursion to convert the first part to a string and then append the character 
value corresponding to the final digit, you will get the string representing the integer as 
a whole. 
As you work through this problem, you should keep the following points in mind: 
• Your solution should operate recursively and should use no iterative constructs such as 
for or while. It is also inappropriate to call the provided IntegerToString function 
or any other library function that does numeric conversion. 
• The value that you get when you compute n % 10 is an integer, and not a character. To 
convert this integer to its character equivalent you have to add the ASCII code for the 
character '0' and then cast that value to a char. If you then need to convert that
– 5 – 
character to a one-character string, you can concatenate it with string(). (The Java 
trick of concatenating with "" doesn’t work because that is a C string.) 
• You should think carefully about what the simple cases need to be. In particular, you 
should make sure that calling IntToString(0) returns "0" and not the empty string. 
This fact may require you to add special code to handle this case. 
• Your implementation should allow n to be negative, so that IntToString(-42) should 
return "-42". Again, implementing this function for negative numbers will probably 
require adding special-case code.

More Related Content

What's hot

Main topic 3 problem solving and office automation
Main topic 3 problem solving and office automationMain topic 3 problem solving and office automation
Main topic 3 problem solving and office automationInfinity Tech Solutions
 
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Philip Schwarz
 
C programming session 05
C programming session 05C programming session 05
C programming session 05Vivek Singh
 
3.3 Logarithmic Functions
3.3 Logarithmic Functions3.3 Logarithmic Functions
3.3 Logarithmic FunctionsVictoria Ryburn
 
GSP 215 RANK Introduction Education--gsp215rank.com
GSP 215 RANK Introduction Education--gsp215rank.comGSP 215 RANK Introduction Education--gsp215rank.com
GSP 215 RANK Introduction Education--gsp215rank.comagathachristie281
 
GSP 215 RANK Education Counseling--gsp215rank.com
 GSP 215 RANK Education Counseling--gsp215rank.com GSP 215 RANK Education Counseling--gsp215rank.com
GSP 215 RANK Education Counseling--gsp215rank.comwilliamwordsworth40
 
GSP 215 RANK Education Planning--gsp215rank.com
GSP 215 RANK Education Planning--gsp215rank.comGSP 215 RANK Education Planning--gsp215rank.com
GSP 215 RANK Education Planning--gsp215rank.comWindyMiller12
 
Matlab lecture 8 – newton's forward and backword interpolation@taj copy
Matlab lecture 8 – newton's forward and backword interpolation@taj   copyMatlab lecture 8 – newton's forward and backword interpolation@taj   copy
Matlab lecture 8 – newton's forward and backword interpolation@taj copyTajim Md. Niamat Ullah Akhund
 
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHMCLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHMRc Os
 
GSP 215 RANK Lessons in Excellence-- gsp215rank.com
GSP 215 RANK Lessons in Excellence-- gsp215rank.comGSP 215 RANK Lessons in Excellence-- gsp215rank.com
GSP 215 RANK Lessons in Excellence-- gsp215rank.comRoelofMerwe102
 
GSP 215 RANK Inspiring Innovation--gsp215rank.com
GSP 215 RANK Inspiring Innovation--gsp215rank.com GSP 215 RANK Inspiring Innovation--gsp215rank.com
GSP 215 RANK Inspiring Innovation--gsp215rank.com KeatonJennings102
 
GSP 215 RANK Education Your Life--gsp215rank.com
GSP 215 RANK Education Your Life--gsp215rank.comGSP 215 RANK Education Your Life--gsp215rank.com
GSP 215 RANK Education Your Life--gsp215rank.comthomashard64
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3Philip Schwarz
 
The Functional Programming Triad of fold, scan and iterate
The Functional Programming Triad of fold, scan and iterateThe Functional Programming Triad of fold, scan and iterate
The Functional Programming Triad of fold, scan and iteratePhilip Schwarz
 
Lab7: More Arrays, Strings, Vectors, and Pointers
Lab7: More Arrays, Strings, Vectors, and PointersLab7: More Arrays, Strings, Vectors, and Pointers
Lab7: More Arrays, Strings, Vectors, and Pointersenidcruz
 

What's hot (20)

Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Programming with matlab session 3 notes
Programming with matlab session 3 notesProgramming with matlab session 3 notes
Programming with matlab session 3 notes
 
Main topic 3 problem solving and office automation
Main topic 3 problem solving and office automationMain topic 3 problem solving and office automation
Main topic 3 problem solving and office automation
 
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
 
Environmental Engineering Assignment Help
Environmental Engineering Assignment HelpEnvironmental Engineering Assignment Help
Environmental Engineering Assignment Help
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
3.3 Logarithmic Functions
3.3 Logarithmic Functions3.3 Logarithmic Functions
3.3 Logarithmic Functions
 
GSP 215 RANK Introduction Education--gsp215rank.com
GSP 215 RANK Introduction Education--gsp215rank.comGSP 215 RANK Introduction Education--gsp215rank.com
GSP 215 RANK Introduction Education--gsp215rank.com
 
GSP 215 RANK Education Counseling--gsp215rank.com
 GSP 215 RANK Education Counseling--gsp215rank.com GSP 215 RANK Education Counseling--gsp215rank.com
GSP 215 RANK Education Counseling--gsp215rank.com
 
GSP 215 RANK Education Planning--gsp215rank.com
GSP 215 RANK Education Planning--gsp215rank.comGSP 215 RANK Education Planning--gsp215rank.com
GSP 215 RANK Education Planning--gsp215rank.com
 
Matlab lecture 8 – newton's forward and backword interpolation@taj copy
Matlab lecture 8 – newton's forward and backword interpolation@taj   copyMatlab lecture 8 – newton's forward and backword interpolation@taj   copy
Matlab lecture 8 – newton's forward and backword interpolation@taj copy
 
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHMCLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
 
NACA Regula Falsi Method
 NACA Regula Falsi Method NACA Regula Falsi Method
NACA Regula Falsi Method
 
GSP 215 RANK Lessons in Excellence-- gsp215rank.com
GSP 215 RANK Lessons in Excellence-- gsp215rank.comGSP 215 RANK Lessons in Excellence-- gsp215rank.com
GSP 215 RANK Lessons in Excellence-- gsp215rank.com
 
GSP 215 RANK Inspiring Innovation--gsp215rank.com
GSP 215 RANK Inspiring Innovation--gsp215rank.com GSP 215 RANK Inspiring Innovation--gsp215rank.com
GSP 215 RANK Inspiring Innovation--gsp215rank.com
 
GSP 215 RANK Education Your Life--gsp215rank.com
GSP 215 RANK Education Your Life--gsp215rank.comGSP 215 RANK Education Your Life--gsp215rank.com
GSP 215 RANK Education Your Life--gsp215rank.com
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3
 
The Functional Programming Triad of fold, scan and iterate
The Functional Programming Triad of fold, scan and iterateThe Functional Programming Triad of fold, scan and iterate
The Functional Programming Triad of fold, scan and iterate
 
5 2
5 25 2
5 2
 
Lab7: More Arrays, Strings, Vectors, and Pointers
Lab7: More Arrays, Strings, Vectors, and PointersLab7: More Arrays, Strings, Vectors, and Pointers
Lab7: More Arrays, Strings, Vectors, and Pointers
 

Viewers also liked

Comunicación efectiva
Comunicación efectivaComunicación efectiva
Comunicación efectivaBetty555
 
Advantages of using a Veterans Loan to Buy a Home
Advantages of using a Veterans Loan to Buy a HomeAdvantages of using a Veterans Loan to Buy a Home
Advantages of using a Veterans Loan to Buy a HomeConnor T. MacIVOR
 
Ateoriadodesenvolvimentohumanosegundoerikerikcsonrevistoem09 05-2011-11050912...
Ateoriadodesenvolvimentohumanosegundoerikerikcsonrevistoem09 05-2011-11050912...Ateoriadodesenvolvimentohumanosegundoerikerikcsonrevistoem09 05-2011-11050912...
Ateoriadodesenvolvimentohumanosegundoerikerikcsonrevistoem09 05-2011-11050912...Jhonny Ribeiro
 
Moodle user group May 2014 Derby College
Moodle user group May 2014 Derby CollegeMoodle user group May 2014 Derby College
Moodle user group May 2014 Derby CollegeJisc RSC East Midlands
 

Viewers also liked (7)

Comunicación efectiva
Comunicación efectivaComunicación efectiva
Comunicación efectiva
 
Advantages of using a Veterans Loan to Buy a Home
Advantages of using a Veterans Loan to Buy a HomeAdvantages of using a Veterans Loan to Buy a Home
Advantages of using a Veterans Loan to Buy a Home
 
CIA - Tổng quan về trường
CIA - Tổng quan về trườngCIA - Tổng quan về trường
CIA - Tổng quan về trường
 
CASE Network Studies and Analyses 205 - Moldova in 1995 - 1999: Macroeconomic...
CASE Network Studies and Analyses 205 - Moldova in 1995 - 1999: Macroeconomic...CASE Network Studies and Analyses 205 - Moldova in 1995 - 1999: Macroeconomic...
CASE Network Studies and Analyses 205 - Moldova in 1995 - 1999: Macroeconomic...
 
Amigasso
AmigassoAmigasso
Amigasso
 
Ateoriadodesenvolvimentohumanosegundoerikerikcsonrevistoem09 05-2011-11050912...
Ateoriadodesenvolvimentohumanosegundoerikerikcsonrevistoem09 05-2011-11050912...Ateoriadodesenvolvimentohumanosegundoerikerikcsonrevistoem09 05-2011-11050912...
Ateoriadodesenvolvimentohumanosegundoerikerikcsonrevistoem09 05-2011-11050912...
 
Moodle user group May 2014 Derby College
Moodle user group May 2014 Derby CollegeMoodle user group May 2014 Derby College
Moodle user group May 2014 Derby College
 

Similar to A01

Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...Dadangsachir WANDA ir.mba
 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapaloozaJenniferBall44
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxdunhamadell
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning materialArthyR3
 
Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02auswhit
 
Learning R while exploring statistics
Learning R while exploring statisticsLearning R while exploring statistics
Learning R while exploring statisticsDorothy Bishop
 
Anything but simple Mathematica
Anything but simple MathematicaAnything but simple Mathematica
Anything but simple MathematicaSergeiPronkevich
 
Oop lab assignment 01
Oop lab assignment 01Oop lab assignment 01
Oop lab assignment 01Drjilesh
 
C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit IssuesAndrey Karpov
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview QuestionsGradeup
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docxrosemarybdodson23141
 
Acm aleppo cpc training fifth session
Acm aleppo cpc training fifth sessionAcm aleppo cpc training fifth session
Acm aleppo cpc training fifth sessionAhmad Bashar Eter
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxmonicafrancis71118
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As CompDavid Halliday
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As CompDavid Halliday
 

Similar to A01 (20)

C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapalooza
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docx
 
Mechanical Engineering Homework Help
Mechanical Engineering Homework HelpMechanical Engineering Homework Help
Mechanical Engineering Homework Help
 
Get Fast C++ Homework Help
Get Fast C++ Homework HelpGet Fast C++ Homework Help
Get Fast C++ Homework Help
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning material
 
Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02
 
Learning R while exploring statistics
Learning R while exploring statisticsLearning R while exploring statistics
Learning R while exploring statistics
 
Anything but simple Mathematica
Anything but simple MathematicaAnything but simple Mathematica
Anything but simple Mathematica
 
Oop lab assignment 01
Oop lab assignment 01Oop lab assignment 01
Oop lab assignment 01
 
C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit Issues
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docx
 
Cse cpl manual-2016
Cse cpl manual-2016Cse cpl manual-2016
Cse cpl manual-2016
 
Acm aleppo cpc training fifth session
Acm aleppo cpc training fifth sessionAcm aleppo cpc training fifth session
Acm aleppo cpc training fifth session
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORYGE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
 

More from lksoo

More from lksoo (20)

Lo48
Lo48Lo48
Lo48
 
Lo43
Lo43Lo43
Lo43
 
Lo39
Lo39Lo39
Lo39
 
Lo37
Lo37Lo37
Lo37
 
Lo27
Lo27Lo27
Lo27
 
Lo17
Lo17Lo17
Lo17
 
Lo12
Lo12Lo12
Lo12
 
T3
T3T3
T3
 
T2
T2T2
T2
 
T1
T1T1
T1
 
T4
T4T4
T4
 
P5
P5P5
P5
 
P4
P4P4
P4
 
P3
P3P3
P3
 
P1
P1P1
P1
 
P2
P2P2
P2
 
L10
L10L10
L10
 
L9
L9L9
L9
 
L8
L8L8
L8
 
L7
L7L7
L7
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

A01

  • 1. Eric Roberts Handout #7 CS106B April 3, 2009 Assignment #1—Simple C++ Parts of this handout were written by Julie Zelenski Due: Friday, April 10 Part 1. Get your C++ compiler working Your first task is to set up your C++ compiler. If you’re using the machines in Stanford’s public clusters, you don’t need to do anything special to install the software. If you’re using you own machine, you should consult one of the following handouts, depending on the type of machine you have: • Handout #7M. Downloading XCode on the Macintosh • Handout #7P. Downloading Visual Studio for Windows Once you have the compiler ready, go to the assignments section of the web site and download the starter file for the type of machine you are using. For either platform, the Assignment1 folder contains six separate project folders: one for this warmup problem and one for each of the five problems in Part 2 of the assignment. Open the project file in the folder named 0-Warmup. Your mission in Part 1 of the assignment is simply to get this program running. The source file we give you is a complete C++ program—so complete, in fact, that it comes complete with two bugs. The errors are not difficult to track down (in fact, we’ll tell you that one is incorrect arguments to a function call and the other is a needed #include statement is missing). This task is designed to give you a little experience with the way errors are reported by the compiler and what it takes to fix them. Once you fix the errors, compile and run the program. When the program executes, it will ask for your name. Enter your name and it will print out a “hash code” (a number) generated for that name. We’ll talk later in the class about hash codes and what they are used for, but for now just run the program, enter your name, and record the hash code. You’ll email us this number. A sample run of the program is shown below: Please enter your name: Eric The hash code for your name is 339. Once you’ve got your hash code, we want you to e-mail it to your section leader and introduce yourself. You don’t yet know your section assignment, but will receive it via email after signups close, so hold on to your e-mail until then. I’d also appreciate if you would cc me on the e-mail (eroberts@stanford.edu) so I can meet you as well. Here’s the information to include in your e-mail: 1. Your name and the hash code that was generated for it by the program 2. Your year and major 3. When you took 106A (or equivalent course) and how you feel it went for you 4. What you are most looking forward to about 106B 5. What you are least looking forward to about 106B 6. Any information that might be helpful to us about how to best help you learn and master the course material
  • 2. – 2 – Part 2. Simple C++ problems Most of the assignments in this course are single programs of a substantial size. To get you started, however, the first assignment is a series of five short problems that are designed to get you used to using C++ and to introduce the idea of functional recursion. None of these problems will require more than a page of code to complete; most can be solved in just a few lines. Problem 1 (Chapter 1, exercise 7, page 41) Greek mathematicians took a special interest in numbers that are equal to the sum of their proper divisors (a proper divisor of N is any divisor less than N itself). They called such numbers perfect numbers. For example, 6 is a perfect number because it is the sum of 1, 2, and 3, which are the integers less than 6 that divide evenly into 6. Similarly, 28 is a perfect number because it is the sum of 1, 2, 4, 7, and 14. Write a predicate function IsPerfect that takes an integer n and returns true if n is perfect, and false otherwise. Test your implementation by writing a main program that uses the IsPerfect function to check for perfect numbers in the range 1 to 9999 by testing each number in turn. When a perfect number is found, your program should display it on the screen. The first two lines of output should be 6 and 28. Your program should find two other perfect numbers in the range as well. Problem 2 (Chapter 2, exercise 6, page 79) A histogram is a graphical way of displaying data by dividing the data into separate ranges and then indicating how many data values fall into each range. For example, given the set of exam scores 100, 95, 47, 88, 86, 92, 75, 89, 81, 70, 55, 80 a traditional histogram would have the following form: *** * * * * * * * * * 0–9 10–19 20–29 30–39 40–49 50–59 60–69 70–79 80–89 90–99 100 The asterisks in the histogram indicate one score in the 40s, one score in the 50s, five scores in the 80s, and so forth. When you generate histograms using a computer, however, it is usually much easier to display them sideways on the page, as in this sample run: 0: 10: 20: 30: 40: * 50: * 60: 70: ** 80: ***** 90: ** 100: *
  • 3. – 3 – Write a program that reads in an array of integers—ideally from a text file as described in Chapter 3—and then displays a histogram of those numbers, divided into the ranges 0–9, 10–19, 20–29, and so forth, up to the range containing only the value 100. Your program should generate output that looks as much like the sample run as possible. Problem 3 (Chapter 3, exercise 2, page 116) Heads. . . . Heads. . . . Heads. . . . A weaker man might be moved to re-examine his faith, if in nothing else at least in the law of probability. —Tom Stoppard, Rosencrantz and Guildenstern Are Dead, 1967 Write a program that simulates flipping a coin repeatedly and continues until three consecutive heads are tossed. At that point, your program should display the total number of coin flips that were made. The following is one possible sample run of the program: tails heads heads tails tails heads tails heads heads heads It took 10 flips to get 3 consecutive heads. Problem 4 (Chapter 5, exercise 8, page 201) The mathematical combinations function C(n, k) is usually defined in terms of factorials, as follows: C(n, k) = n! k! x (n–k)! The values of C(n, k) can also be arranged geometrically to form a triangle in which n increases as you move down the triangle and k increases as you move from left to right. The resulting structure, which is called Pascal’s Triangle after the French mathematician Blaise Pascal, is arranged like this: C(0, 0) C(1, 0) C(1, 1) C(2, 0) C(2, 1) C(2, 2) C(3, 0) C(3, 1) C(3, 2) C(3, 3) C(4, 0) C(4, 1) C(4, 2) C(4, 3) C(4, 4) Pascal’s Triangle has the interesting property that every entry is the sum of the two entries above it, except along the left and right edges, where the values are always 1. Consider, for example, the circled entry in the following display of Pascal’s Triangle:
  • 4. – 4 – 1 1 1 1 1 1 1 2 3 4 5 6 1 3 6 10 15 1 4 10 20 1 5 15 1 1 6 1 This entry, which corresponds to C(6, 2), is the sum of the two entries—5 and 10—that appear above it to either side. Use this relationship between entries in Pascal’s Triangle to write a recursive implementation of the C(n, k) function that uses no loops, no multiplication, and no calls to Fact. Write a simple test program to demonstrate that your combinations function works. And if you want an additional challenge, write a program that uses C(n, k) to display the first ten rows of Pascal’s Triangle. Problem 5 (Implementing IntToString) The strutils.h interface exports a method string IntegerToString(int n); that converts an integer into its representation as a string of decimal digits, so that, for example, IntegerToString(1729) should return the string "1729". Your job in this problem is to write a function IntToString that does the same thing as the function in strutils.h but with a recursive implementation. (The name is shortened in this exercise to avoid having your implementation conflict with the library version.) Fortunately, this function has a natural recursive structure because it is easy to break an integer down into two components using division by 10. This decomposition is discussed in Chapter 5, exercise 6, which shows how to divide 1729 into two pieces, like this: 1 7 2 9 1 7 2 n / 10 9 n % 10 If you use recursion to convert the first part to a string and then append the character value corresponding to the final digit, you will get the string representing the integer as a whole. As you work through this problem, you should keep the following points in mind: • Your solution should operate recursively and should use no iterative constructs such as for or while. It is also inappropriate to call the provided IntegerToString function or any other library function that does numeric conversion. • The value that you get when you compute n % 10 is an integer, and not a character. To convert this integer to its character equivalent you have to add the ASCII code for the character '0' and then cast that value to a char. If you then need to convert that
  • 5. – 5 – character to a one-character string, you can concatenate it with string(). (The Java trick of concatenating with "" doesn’t work because that is a C string.) • You should think carefully about what the simple cases need to be. In particular, you should make sure that calling IntToString(0) returns "0" and not the empty string. This fact may require you to add special code to handle this case. • Your implementation should allow n to be negative, so that IntToString(-42) should return "-42". Again, implementing this function for negative numbers will probably require adding special-case code.