You are on page 1of 24

POINTER WORKSHEET-1

The main program keeps track of information on members of a health club. It calls a
function AddMember() when there is a new membership. The membership counts are
kept track of in main(), so main() can pass this info to other functions.

int main()
{
int total_cnt, At memory location 1000
family_cnt, At memory location 2000
adult_cnt, At memory location 1600
child_cnt; At memory location 2200

The variables above are known to main(), not AddMember(). AddMember() will not
recognize their names.

The function header for AddMember() is

void AddMember(int *totalptr, int *fptr, int *aptr, int *cptr)

where totalptr is a pointer to the total count (total_cnt), fptr is a pointer to the family
count (family_cnt), etc.

1. Write a calling statement for AddMember(), from main.

2. Assume the variables have these current values, total_cnt = 204, family_cnt = 52,
adult_cnt = 108, child_cnt = 96, when main() calls AddMember(). In the chart below,
write the value of the expression, or check the ERROR column if the expression
would result in a syntax error.
VALUE ERROR
If the expresion is IN main
total_cnt __________ _____
&total_cnt __________ _____
*totalptr __________ _____
&totalptr __________ _____
adult_cnt __________ _____
&adult_cnt __________ _____
&child_cnt __________ _____
*family_cnt __________ _____
If the expression is IN AddMember
totalptr __________ _____
fptr __________ _____
*aptr __________ _____
&cptr __________ _____
&total_cnt __________ _____
*total_cnt __________ _____
*totalptr __________ _____
*fptr __________ _____

POINTER WORKSHEET-1

The main program keeps track of information on members of a health club. It calls a
function AddMember() when there is a new membership. The membership counts are
kept track of in main(), so main() could pass this info to other functions.

void main()
{
int total_cnt, At memory location 1000
family_cnt, At memory location 2000
adult_cnt, At memory location 1600
child_cnt; At memory location 2200

The variables above are known to main(), not AddMember(). AddMember() will not
recognize their names.

The function header for AddMember is

void AddMember(int *totalptr, int *fptr, int *aptr, int *cptr)

where totalptr is a pointer to the total count (total_cnt), fptr is a pointer to the family
count (family_cnt), etc.

1. Write a calling statement for AddMember(), from main.


AddMember(&total_cnt, &family_cnt, &adult_cnt, &child_cnt);

2. Assume the variables have these current values, total_cnt = 204, family_cnt = 52,
adult_cnt = 108, child_cnt = 96, when main() calls AddMember(). In the chart below,
write the value of the expression, or check the ERROR column if the expression
would result in a syntax error.
VALUE ERROR
If the expresion is IN main
total_cnt 204 _____
&total_cnt 1000 _____
*totalptr __________ __X__
&totalptr __________ __X__
Main does not recognize totalptr.
adult_cnt 108 _____
&adult_cnt 1600 _____
&child_cnt 2200 _____
*family_cnt __________ __X__
Variable family_cnt is not a pointer, so you can not dereference it.
If the expression is IN AddMember
totalptr 1000 _____
fptr 2000 _____
*aptr 108 _____
&cptr *** _____
&total_cnt __________ __X__
*total_cnt __________ __X__
AddMember does not know what total_cnt is.
*totalptr 204 _____
*fptr 52 _____

*** Since cptr is a variable, its value is stored somewhere, so IT DOES have an
address, you just don't know what it is. Just using &cptr will not get an error, because
THERE IS an address, but it probably is not what you intended. Writing something
like &cptr = 20 WILL get an error.

NOTE: &total_cnt = 1000 = totalptr. So we usually have &variablename in the


calling statement when the argument is a pointer data type. (NOT *variablename,
even though the * is in the function header!!)

adult_cnt = 108 = *aptr. So we usually use *pointername in the code of the function
when the argument is a pointer data type.

POINTER WORKSHEET - 2

Relating Expressions

This worksheet is intended to show the relationship between array names, subscripts,
and pointer arithmetic. It may be helpful (but not required) to use a sheet of graph
paper to represent where the variable values are stored (their addresses or storage
locations). It is easier to understand the relationship if you can visualize how the
information is stored.

SET-UP
void main()
{ int int_ary[10]={2,4,6,8}; // array of 10 integers
char chr_ary[11]; // array of 11 characters,
// room for 10 useable characters
// and the null terminator
.
.
.
}

Assume that the space reserved for the integer array starts at storage location 2000.
Assume that the space reserved for the character array starts at storage location 1600.

PART 1

1. Where does the integer array end? (Hint: How many bytes for an integer?)
10 integers X 4 bytes per integer = 40 bytes.
2000 + 40 = 2020, so the integer array goes up to, but does not include,
location 2040. The last integer space in the array is location 2036.
2. Where does the character array end?
11 characters X 1 byte per character = 11 bytes. 1600 + 11 = 1611, so the
character array goes up to, but does not include, location 1611. The last
space in the array is location 1610. (This does not mean that the null terminator
is at location 1610. It could be earlier.)
3. What is the value of int_ary? Of chr_ary?
int_ary = 2000 and chr_ary = 1600
4. What is the value of int_ary[0]? Of int_ary[3]? Of int_ary+1? Of int_ary+9?
(Based on the declaration statement.)
int_ary[0] = 2, int_ary[3] = 8 Both expressions refer to actual elements in the
array.
int_ary+1 and int_ary+9 do not refer to elements in the array. They are storage
locations.
int_ary+1 is a pointer to the location 1 integer space past the start of the array.
int_ary+1 = 2004 (location 2000 + 4 bytes).
int_ary+9 = 2036 (location 2000 + 36 bytes).
5. "The name of an array is a pointer to the array." Describe the difference
between the expressions chr_ary and *chr_ary.
chr_ary is a constant pointer to the beginning of the array. It is also a pointer
to the first element in the array. *chr_ary is a character in the array.
What are their values? chr_ary = 1600, *chr_ary = 'c'
6. Describe the difference between int_ary+1, int_ary[1] and *(int_ary+1).
int_ary+1 is a pointer to the second element of the array. int_ary[1] and
*(int_ary+1) both refer to the second integer in the array.
What are their values? int_ary+1 = 2004, int_ary[1] = *(int_ary+1) = 4
7. What is the value of &chr_ary[0]? Of &chr_ary[1]? Of &chr_ary?
&chr_ary[0] = 1600 (the location of the first element in the array)
&chr_ary[1] = 1601 (the location of the second element in the array)
&chr_ary is unknown. It does not equal 1600. chr_ary is a constant pointer
to location 1600 (it is stored in another location which was not given). For
PART 2, assume &chr_ary = 1004.
8. What is the value of &int_ary[0]? Of &int_ary?
&int_ary[0] = 2000, &int_ary is unknown. int_ary is a constant pointer to
location 2000. The location of int_ary was not given. For PART 2, assume
&int_ary = 1006.

If you have been writing out the storage locations, you should have something
similar to the charts below.

location 1000 1001 1002 1003 1004,1005 1006,1007 1008 1009

value 1600 2000


name chr_ary int_ary
location 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610

value c o m p u t e r \0 ??? ???


name * [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

* names used are chr_ary[subscript]

location 2000,2003 2004,2007 2008,2011 2012,2015 2016,2019

value 2 4 6 8 0
name int_ary[0] int_ary[1] int_ary[2] int_ary[3] int_ary[4]

location 2020,2023 2024,2027 2028,2031 2032,2035 2036,2039

value 0 0 0 0 0
name int_ary[5] int_ary[6] int_ary[7] int_ary[8] int_ary[9]

PART 2

Check the answers to PART 1 before continuing. You need to understand #4-8 inorder
to do PART 2.
Assume the following line of code has been executed.
strcpy(chr_ary, "computer");
The values in the integer array have not changed. Determine the value of each
expression below.
1. chr_ary chr_ary+0 *chr_ary *(chr_ary+0)
1600 1600 'c' 'c'
2. chr_ary+1 *chr_ary+1 *(chr_ary+1)
1601 'd' 'o'
'c' + 1 = 'd'
3. int_ary *int_ary *(int_ary+0)
2000 2 2
4. int_ary+1 *int_ary+1 *(int_ary+1) int_ary[1]
2004 3 4 4
(2000 + 1 int space
= 2000 + 4 bytes)
5. *(chr_ary+3) chr_ary[3] chr_ary+3
'p' 'p' 1603
6. chr_ary chr_ary[0] *chr_ary &chr_ary[0]
1600 'c' 'c' 1600
(location of the
first element)
7. int_ary int_ary[0] *int_ary &int_ary[0]
2000 2 2 2000
8. &int_ary[0] &int_ary *int_ary+0 int_ary
2000 1006 2 2000
9. int_ary[2] *(int_ary+2) &int_ary[2] int_ary+2
6 6 2008 2008
10. int_ary+10 int_ary[10] *(int_ary+10)
2040 garbage garbage
(from the next 4 bytes after the array)

240 WORKSHEET - STRUCTURES 1

This worksheet is for practicing the notation related to structures and their fields. In
this worksheet, the word field is used in place of the word member.

The following description of a structure is located before main().


struct acctT
{
char acctNum[10]; // account number
char acctName[40]; // owner of account
float acctBal; // account balance
};

The following declarations are located in main.


acctT chkAcct; // checking account
acctT savAcct; // savings account

1. What is the data type of the structure? (Not the data type of its fields)

2. What are the variable names for the instances of the structure?

3. Give all the unique field names of both instances of the structure.
(to be unique, the variable name of the structure must be included with the name of
the field)

Write the name you would use to reference each specific field from main.
4. The name field of the checking account.

5. The balance field of the checking account.

6. The name field of the savings account.

7. The account number field of the savings account.

8. The savings account.

9. Use three statements to initialize the savings account so the account number is 5-
1357648, the name is John Smith, and the balance is $1000.00.

10. Use one statement that declares and initializes the checking account so the account
number is 98765432, the name is Betsy Ross, and the balance is $2500.00.

11. What is the data type of savAcct?

12. Write one statement to copy all the fields from chkAcct to savAcct.

Below are 2 more examples of structures. For more practice, apply questions
1,2,3,9,&10 to these examples.
EXAMPLE 1 BEFORE main
struct product
{
int IDnum; // product ID number
char ProdDesc[40]; // product description
int quantity; // number in stock
float costEA; // cost for each
};
IN main
product tool;
product book;
EXAMPLE 2 BEFORE main
struct bird
{
char ColorDesc[40]; // description of bird's colors
char song[50]; // description of song or call
int clutchsize; // Number of eggs laid per season
float wingspan; // Distance between spread wingtips
};
IN main
bird robin;
bird subject1;
bird subject2;
240 WORKSHEET - STRUCTURES 1 Key

In this worksheet, the word field is used in place of the word member.

1. What is the data type of the structure? (Not the data type of its fields) acctT

2. What are the variable names for the instances of the structure? chkAcct, savAcct

3. Give all the unique field names of both instances of the structure.
(to be unique, the variable name of the structure must be included with the name of
the field)
chkAcct.acctNum savAcct.acctNum
chkAcct.acctName savAcct.acctName
chkAcct.acctBal savAcct.acctBal

Write the name you would use to reference each specific field from main.

4. The name field of the checking account. chkAcct.acctName

5. The balance field of the checking account. chkAcct.acctBal

6. The name field of the savings account. savAcct.acctName

7. The account number field of the savings account. savAcct.acctNum

8. The savings account. savAcct

9. Use three statements to initialize the savings account so the account number is 5-
1357648, the name is John Smith, and the balance is $1000.00.
strcpy(savAcct.acctNum, "5-1357648");
strcpy(savAcct.acctName, "John Smith");
savAcct.acctBal = 1000.00;

10. Use one statement that declares and initializes the checking account so the account
number is 98765432, the name is Betsy Ross, and the balance is $2500.00.
acctT chkAcct = {"98765432", "Betsy Ross", 2500.00};

11. What is the data type of savAcct? acctT

12. Write one statement to copy all the fields from chkAcct to savAcct.
savAcct = chkAcct;
EXAMPLE 1
1. data type is product
2. structure names are tool and book
3. field names: tool.IDnum book.IDnum
tool.ProdDesc book.ProdDesc
tool.quantity book.quantity
tool.costEA book.costEA
9. Your solution should be similar to below.
tool.IDnum = 123;
because it is an integer, not a char array
strcpy(tool.ProdDesc, "Phillips screwdriver");
tool.quantity = 1200;
tool.costEA = 14.95;
10. product tool = {123, "Phillips screwdriver", 1200, 14.95};
EXAMPLE 2
1. data type is bird
2. structure names are robin, subject1 and subject 2
3. field names for robin: robin.ColorDesc
robin.song
robin.clutchsize
robin.wingspan
9 & 10 similar to above examples.
Remember to use strcpy for robin.ColorDesc and robin.song
because they are char arrays.

POINTER WORKSHEET - 2

Relating Expressions

This worksheet is intended to show the relationship between array names, subscripts,
and pointer arithmetic. It may be helpful (but not required) to use a sheet of graph
paper to represent where the variable values are stored (their addresses or storage
locations). It is easier to understand the relationship if you can visualize how the
information is stored.

SET-UP
void main()
{ int int_ary[10]={2,4,6,8}; // array of 10 integers
char chr_ary[11]; // array of 11 characters,
// room for 10 useable characters
// and the null terminator
.
.
.
}

Assume that the space reserved for the integer array starts at storage location 2000.
Assume that the space reserved for the character array starts at storage location 1600.
PART 1

1. Where does the integer array end? (Hint: How many bytes for an integer?)
2. Where does the character array end?
3. What is the value of int_ary? Of chr_ary?
4. What is the value of int_ary[0]? Of int_ary[3]? Of int_ary+1? Of int_ary+9?
(Based on the declaration statement.)
5. "The name of an array is a pointer to the array." Describe the difference
between the expressions chr_ary and *chr_ary. What are their values?
6. Describe the difference between int_ary+1, int_ary[1] and *(int_ary+1).
What are their values?
7. What is the value of &chr_ary[0]? Of &chr_ary[1]?
Of &chr_ary? (CAREFUL!!!)
8. What is the value of &int_ary[0]? Of &int_ary?

PART 2

Check the answers to PART 1 before continuing. You need to understand #4-8 inorder
to do PART 2.
Assume the following line of code has been executed.
strcpy(chr_ary, "computer");
The values in the integer array have not changed. Determine the value of each
expression below.
1. chr_ary chr_ary+0 *chr_ary *(chr_ary+0)
2. chr_ary+1 *chr_ary+1 *(chr_ary+1)
3. int_ary *int_ary *(int_ary+0)
4. int_ary+1 *int_ary+1 *(int_ary+1) int_ary[1]
5. *(chr_ary+3) chr_ary[3] chr_ary+3
6. chr_ary chr_ary[0] *chr_ary &chr_ary[0]
7. int_ary int_ary[0] *int_ary &int_ary[0]
8. &int_ary[0] &int_ary *int_ary+0 int_ary
(CAREFUL!!!)
9. int_ary[2] *(int_ary+2) &int_ary[2] int_ary+2
10. int_ary+10 int_ary[10] *(int_ary+10)

SCI 240 - Function Worksheet 1

Basics

Answer questions about the 3 function prototypes below.

long int Factorial(int );


double FindAverage(double , int );

void PrintTitle(string , int , int );

1. What type of value will each function return?

o Factorial __________________
o FindAverage __________________
o PrintTitle ___________________

2. How many arguments does each function expect?

o Factorial __________________
o FindAverage __________________
o PrintTitle ___________________

3. Write a calling statement for each function using constant values as arguments.
(Use values like 1, 2, 3.5, "Mary", not num1, name etc.)

o Factorial ___________________________________________
o FindAverage ________________________________________
o PrintTitle ___________________________________________

4. Write a calling statement for each function using variables as arguments.

o Factorial ____________________________________________
o FindAverage _________________________________________
o PrintTitle ____________________________________________

NOTE: When you call a function you do not need to know the variable names that the
function uses for the arguments.

CSCI 240 - Function Worksheet 1

Basics

Answer questions about the 3 function prototypes below.

long int Factorial(int );

double FindAverage(double , int );

void PrintTitle(string , int , int );


1. What type of value will each function return?

o Factorial __long integer___


o FindAverage __double______
o PrintTitle __nothing is returned__

2. How many arguments does each function expect?

o Factorial _____one__________
o FindAverage _____two__________
o PrintTitle ______three________

3. Write a calling statement for each function using constant values as arguments.
(Use values like 1, 2, 3.5, "Mary", not num1, name etc.)

o Factorial ____answer = Factorial(7);______________________


o FindAverage ___average = FindAverage(1234.78, 23);________
o PrintTitle _____PrintTitle("INVOICE", 82, 4);___ ____________

NOTE that Factorial and FindAverage are assignment statements because they
return a value. If they are not called with an assignment statement the returned value
is lost. PrintTitle does not need an assignment. It does its job and returns.

4. Write a calling statement for each function using variables as arguments.

The following variables would be declared in the calling function, not the function
being called.
int num1, column, row, count;
double sum;
string name;

o Factorial ____answer = Factorial(num1);___________________


o FindAverage ___average = FindAverage(sum, count);__________
o PrintTitle _____PrintTitle(name, column, row);________________

NOTE: When you call a function you do not need to know the variable names that the
function uses for the arguments.

CSCI 240 -- Function Worksheet 2

For each of the following functions write a prototype, the function, and a calling
statement.
Function 1: Write a function called CalcAverage. This function takes as its
arguments two integers. The first is a total from a number of items and the second
represents the number of items. The function should calculate and return the average.
Before the function returns, print a sentence stating what the average is.

Function 2: Write a function called FindSum. It takes no arguments. The function


should prompt the user for integer values and add them up until a negative value is
entered. The sum should then be returned.

Function 3: Write a function called PrintPageHeader. This function takes as its


argument an integer which represents the page number of the page to be printed. The
function should print "240Distributors Employee Report" and the page number
centered on the top of a new page.

Assuming that the value 2 is passed to the function, the output should resemble:
240Distributors Employee Report
Page: 2

Function 4: Write a function called UserChoice. It takes as its argument an integer


that represents an upper bound. The function is to prompt the user to enter an integer
between 1 and the upper bound. If the user enters a number less than 1, return -1. If
the user enters a number greater than the upper bound, return 0. If the user enters a
number between 1 and the upper bound, inclusive, return the user's number.

Function 5: Write a function called IsOdd. It takes as its argument an integer that is
to be tested to see if it's odd. If the number is odd, return 1. If the number is even,
return 0.

Function 6: Write a function called FigureTax. It takes as its argument a real number
that represents the subtotal for a customer's purchase. The function should apply a
6.25% tax to the subtotal and return a grand total, which is equal to the subtotal plus
the tax amount.
CSCI 240 - Function Worksheet 2 Answers

Function 1

Write a function called CalcAverage. This function takes as its arguments two
integers. The first is a total from a number of items and the second represents the
number of items. The function should calculate and return the average. Before the
function returns, print a sentence stating what the average is.

Function prototype:
double CalcAverage(int, int);

Function:
double CalcAverage(int total, int count)
{
double average;

average = (double) total / count;

cout << "\nThe average is " << average;

return average;
}

Calling Statement:
Pass ItemTotal and NumberOfItems to the function and store the return value in a
variable named avg. You can assume that ItemTotal and NumberOfItems have
received valid values prior to this call.
avg = CalcAverage(ItemTotal, NumberOfItems);

Function 2

Write a function called FindSum. It takes no arguments. The function should prompt
the user for integer values and add them up until a negative value is entered. The sum
should then be returned.

Function prototype:
int FindSum();

Function:
int FindSum()
{
int sum = 0, user_value;

cout << "Enter an integer (negative to quit): ";


cin >> user_value;

while (user_value > 0)


{
sum += user_value;
cout << "Enter another integer (negative to quit): ";
cin >> user_value;
}
return sum;
}

Calling Statement:

Call the function and assign the return value to a variable called UserSum.
UserSum = FindSum();

Function 3

Write a function called PrintPageHeader. This function takes as its argument an


integer which represents the page number of the page to be printed. The function
should print "240 Distributors Employee Report" and the page number centered on the
top of a new page.

Function prototype:
void PrintPageHeader(int);

Function:
void PrintPageHeader(int page_num)
{
cout << "\f\t\t\t\t 240 Distributors Employee Report \t\t\t Page: " <<
pagenum;
}

Calling Statement:

Pass the function an integer variable called page. Assume that page has been given a
valid value prior to this call.
PrintPageHeader(page);
Function 4

Write a function called UserChoice. It takes as its argument an integer that represents
an upper bound. The function is to prompt the user to enter an integer between 1 and
the upper bound. If the user enters a number less than 1, return -1. If the user enters a
number greater than the upper bound, return 0. If the user enters a number between 1
and the upper bound, inclusive, return the user's number.

Function prototype:
int UserChoice(int);

Function:
int UserChoice(int maximum)
{
int user_value;

cout << "Enter a value between 1 and " << maximum;


cin >> user_value;

if (user_value < 1)
return -1;
else if (user_value > maximum)
return 0;
else
return user_value;
}

Calling Statement:

Pass the function the value 25. Assign the return value to a variable called choice.
choice = UserChoice(25);

Function 5

Write a function called IsOdd. It takes as its argument an integer that is to be tested to
see if it's odd. If the number is odd, return 1. If the number is even, return 0.

Function prototype:
int IsOdd(int);
Function:
int IsOdd(int x)
{
if ((x % 2) == 0)
return 0;
else
return 1;
}

Calling Statement:

Pass the function the variable testnum and assign the return value to oddFlag. Assume
that testnum has been given a valid value prior to this call.
oddFlag = IsOdd(testnum);

Function 6

Write a function called FigureTax. It takes as its argument a real number that
represents the subtotal for a customer's purchase. The function should apply a 6.25%
tax to the subtotal and return a grand total, which is equal to the subtotal plus the tax
amount.

Function prototype:
double FigureTax(double);

Function:
double FigureTax(double subTotal)
{
double tax_amount;

tax_amount = subTotal * 0.0625;

return (subTotal + tax_amount);


}

Calling Statement:

Pass the function the value 79.85 and assign the return value to GrandTotal.
GrandTotal = FigureTax(79.85);
CSCI 240 - Loops Worksheet 1

dowhile & while

REVIEW

A do..while loop is bottom driven, so the condition statement is at the bottom of the
loop.
A while loop is top driven, so the condition statement is at the top of the loop.
Both structures require assigning a value to the test variable before the condition.
dowhile structure while structure
do testvariable = value;
{ while (condition)
statements {
: statements
: :
testvariable = new value; :
} testvariable = new value;
while (condition); }

Write the following loops as both do..while and while structures. Many of the loops
are similar. Focus on how they are the same. Note what it was that you had to change.

1. Accept a series of numbers entered from the keyboard. Continue until 0 (zero) is
entered. Add each number to a sum before getting the next number.

2. Accept a series of numbers entered from the keyboard until a negative number is
entered. Add each number to a sum. Do not include the negative number in the sum.

3. Accept a series of strings from the keyboard. Continue until the string EXIT, Exit,
or exit is entered. For each string, print the statement, "You have entered ", and then
print the string.
a) Print this statement even when the end marker is entered.
b) Do not print this statement when the end marker is entered.

4. Write a loop to add up the numbers from 6 to 25.

5. Write a loop to find the average of 10 quiz scores entered by the user. You know
there will be exactly 10.

6. Write a loop to find the average of quiz scores entered by the user. You don't know
how many the user will enter, but a negative 1 will be entered when done.
CSCI 240 - Loops Worksheet 1

dowhile & while

C++ Solutions

Here are some solutions. THESE ARE NOT THE ONLY SOLUTIONS.
1. DOWHILE
int number_in, VARIABLES USED
sum = 0;
- - - - - - - - - - - - - -
do
{
cin >> number_in; TEST VARIABLE = VALUE
sum = sum + number_in;
}
while (number_in != 0); CONDITION
cout << "sum is " << sum;
NOTE: This dowhile only works because the end marker is zero. See #2.
WHILE
int number_in, VARIABLES USED
sum = 0;

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

cin >> number_in; TEST VARIABLE = VALUE


while (number_in != 0) CONDITION
{
sum = sum + number_in;
cin >> number_in; TEST VARIABLE = NEW VALUE
}
cout << "sum is " << sum;
2. DOWHILE
int number_in,
sum = 0;
- - - - - - - - - - - - - - -
do
{
cin >> number_in;
if (number_in == -1) NEED TO BREAK OUT BEFORE
{ ADDING IN THE END MARKER
break;
}
sum = sum + number_in;
}
while (1);
cout << "sum is " << sum;
NOTE: This dowhile needed an extra if structure.
WHILE
int number_in,
sum = 0;
- - - - - - - - - - - - -
cin >> number_in;
while (number_in != -1)
{
sum = sum + number_in;
cin >> number_in;
}
cout << "sum is " << sum;
but the while structure is the same as in #1.
3a. DOWHILE
string str1;
- - - - - - - - - - - - - - - - - - - - - -
do
{
cin >> str1; TEST VARIABLE = VALUE
cout << "you have entered " << str1;
}
while (str1 != "EXIT" &&
str1 != "Exit" && CONDITION
str1 != "exit");
WHILE
string str1;
- - - - - - - - - - - - - - - - - - - - - -
cin >> str1; TEST VARIABLE = VALUE
while (!StringEqual(str1,"EXIT") &&
!StringEqual(str1,"Exit") && CONDITION
!StringEqual(str1,"exit"))
{
cout << "you have entered " << str1;
cin >> str1; TEST VARIABLE = NEW VALUE
}
cout << "you have entered " << str1;
3b. DOWHILE
string str1;
- - - - - - - -- - - - - - - - - - - -
do
{
cin >> str1;
if (str1 == "EXIT") ||
str1 == "Exit") ||
str1 == "exit"))
{
break;
}
cout << "you have entered " << str1;
}
while (1);
NOTE the similarity to #2.
WHILE
string str1;
- - - - - - - - - - - - - - - - - - - - - - -
cin >> str1;
while (str1 != "EXIT" && str1 != "Exit" &&
str1 != "exit")
{
cout << "you have entered " << str1;
cin >> str1;
}
4. DOWHILE
int number,
sum = 0;
- - - - - - - - - - - - -
number = 6; INITIAL VALUE IS BEFORE THE LOOP
do
{
sum = sum + number;
number++; TEST VARIABLE = VALUE
}
while (number < 26); CONDITION COULD BE (number <= 25)
cout << "sum is " << sum;
WHILE
int number,
sum = 0;
- - - - - - - - - - - - - - - -
number = 6; TEST VARIABLE = VALUE
while (number < 26) CONDITION
{
sum = sum + number;
number++; TEST VARIABLE = NEW VALUE
}
cout << "sum is " << sum;
5. DOWHILE
int count=0;
double score,
average,
sum = 0.0;

- - - - - - - - - - - - - - - -
do
{
cin >> score;
sum = sum + score;
count++;
}
while (count < 10); NOTE: < NOT <=. WHY?
average = sum / count;
cout << "average is " << average;
WHILE
int count=0;
double score,
average,
sum = 0.0;
- - - - - - - - - - - - - - - -
cin >> score;
while (count < 11) CONDITION COULD BE (count <= 10)
{
sum = sum + score;
count++;
cin >> score;
}
average = sum / count; NOTE: CALCULATED AFTER LOOP
cout << "average is " << average;
6. DOWHILE
int count=0;
double score,
average,
sum = 0.0;

- - - - - - - - - - - - - -
do
{
cin << score;
if (score == -1)
{
break;
}
sum = sum + score;
count++;
}
while (1);
average = sum / count;
cout << "average is " << average;
WHILE
int count=0;
double score,
average,
sum = 0.0;
-- - - - - - - - - - - - - - - --
cin >> score;
while (score != -1)
{
sum = sum + score;
count++;
cin << score;
}
average = sum / count;
cout << "average is " << average;
NOTE IN WHICH SITUATIONS THE WHILE HAS LESS CODE THAN THE DOWHILE.

CSCI 240 - Loops Worksheet 2

for loops

Write for loops to accomplish the scenarios below. Many of the loops are similar.
Focus on how they are the same. Note what it was you had to change.

1 a) Add integers from 1 to 10, inclusive. Print the current sum after each addition.

1 b) Add integers from 1 to 50, inclusive. Print the current sum after each addition.

1 c) 1 to 100. ........... 1 to anything.

2) Add integers greater than 1, up to, but not including, 10.

3 a) Print all the multiples of 3, between 1 and 20.


3 b) Print all the multiples of 3, between 100 and 200.

3 c) Print all the multiples of 3, between 2 numbers that are entered by the user.

4) Write a short program to print all the multiples in a given range of an integer
entered by the user. The user will also enter the limits. For example, print the
multiples of 3 between 20 and 40: 21, 24, 27, 30, 33, 36, 39..

CSCI 240 - Loops Worksheet 2

C++ Solutions

Note the similarities in the loops.


1a. int i, sum;
sum = 0;
for (i = 1; i < 11; i++) // or use i <= 10
{
sum += i;
cout << "\nCurrent sum is " << sum);
}
1b. Change for statement to
for (i = 1; i < 51; i++)
1c. Change for statement to
for (i = 1; i < 101; i++)
2. int i, sum;
sum = 0;
for (i = 2; i < 10; i++)
{
sum += i;
cout << "\nCurrent sum is " << sum;
}
3a. int i;
for (i = 3; i <= 20; i+=3)
{
cout << "\n" << i;
}

Here you start with the first multiple and increment by the number that you are
finding multiples of. You must know the first multiple.
OR
for (i = 1; i <= 20; i++)
{
if (i % 3 == 0)
cout << "\n" << i;
}

Here you increment by 1, but only print it if it is a multiple.


3b. int i;
for (i = 100; i <= 200; i++)
{
if (i % 3 == 0)
cout << " " << i);
}

By using the 2nd version, you do not need to know the first multiple.
3c. int i, begin, end;
cout << "\nEnter the beginning of the search range: ";
cin >> begin;
cout << "\nEnter the end of the search range: ";
cin >> end;
for (i = begin; i <= end; i++)
{
if (i % 3 == 0)
cout << " " << i;
}
4. #include ...
#include ...
void main()
{
int i, begin, end, base;
cout << "\nEnter the beginning of the search range: ";
cin >> begin;
cout << "\nEnter the end of the search range: ";
cin >> end;
cout << "\nEnter the integer whose multiples you want: ";
cin >> base;
for (i = begin; i <= end; i++)
{
if (i % base == 0)
cout << " " << i;
}
}

You might also like