POS/370
Programming
Concepts Using C++
Week 4
Newsletter (E. Nikjeh)
Hello Class,
The programs are supposed to be your individual work. It is okay to share ideas and get help from one another, but do the actual work yourself. This course is not designed to make you all C++ programmers, just introduce you to programming concepts.
Repetitive (
The repetition structure allows the programmer to specify that an action (a block of code) is to be repeated while some condition remains true. We specify a condition that must be met for the loop to terminate. If the condition remains true all the time, then we will have an endless loop. We have three types of loop in C++; for, while and do …while as follows:
1- for loop structure: It handles all the details of counter-controlled repetition. So we know how many times we’ll perform the body of loop. The for loop is a pre-test loop. A pre-test loop performs the test condition before executing the body of the loop. The general format of the for structure is:
for (initialization; loopContinuationTest; increment)
{
statement(s) (body of loop);
}
For a for loop with one statement we can have:
for (initialization; loopContinuationTest; increment)
Statement;
Example: for (int i = 1; i <= 10; i++)
Cout<<i<<” Hello”<<endl;
This for loop will print the i value from 1 to 10 and 10 Hello. When the
for structure begins
executing, the control variable i is
declared and initialized to 1. Then, the loop-continuation condition i <+ 10 is checked and the body
statement prints the value of i 1 and Hello. The
control variable i is then
incremented in the expression i++
(remember i++ means i=i+1)
and the loop begins with the loop-continuation test. This process continues
until the control variable i is incremented to 11. This causes the loop-continuation test
to fail and repetition terminates.
A missing loop-test is assumed to evaluate to nonzero; such a loop is infinite loop. For example: for( ; ; ) cout<<”Hello”<<endl;
2- while loop: The while loop is a pre-test loop, first the condition will be checked if it is true the body of loop will be executed. In the body of the loop we change a data (variable) in order to terminate our while loop. The while loop is usually used to perform a block of code any number of times depending on condition of our loop. The general format of while loop is:
a- while (loopContinuationTest) // the simple while loop with one statement statement;
b- while (loopContinuationTest) // the while loop with one or more statements
{
statement(s);
}
example: int i = 0;
while (i <= 10)
{
i = i + 1;
Cout<<i<<” Hello”<<endl;
}
c- do … while loop: This is a post-test loop. First the body of loop will be executed (once) then the condition will be evaluated. If the condition is true it will perform the body of the loop until the condition gets false. The general format of do … while is as follows:
do
{
statement(s)
} while(loopContinuationTest);
example:
int i = 0
do
{
cout<<i<<” Hello”<<endl;
i = i + 1;
} while(i <= 10);
The break statement may be used to terminate a loop at any point. It transfers control to the first statement after the loop. The continue statement causes the loop to skip to its next iteration, essentially transferring control to the while, do, or for statement.
Arrays: An array is a consecutive group
of memory locations that all have the same name and the same type. To refer to
a particular location or element in the array, we specify the name of the array
and the position number of the particular element in the array. The position
number contained within square brackets is more formally called a subscript. A subscript must be an
integer or an integer expression. The first element in every array is the
zeroth element. For example: float score[4] score[0], score[1], score[2], score[3]
So the subscripts are started from 0 to 3 and we cannot have score[4].
The highest subscript number is one less than the physical number of elements. Any time we want to refer to an array element, we must always include the subscript in the open([) and closed(]) brackets. We can initialize an array. For example: one-dimensional arrays
int number[3] = {0, 0, 0}; or int number[3] = {0};
int number[3] = {41, 7, 91};
char code[3] = {‘a’, ‘b’, ‘c’};
float price[5] = {(float)8.5, (float)54.6, (float)3.9, (float)4.8, (float)12.5};
float scores[7] = {(float)0.0} // all elements are initialized to zero;
float sale[5] = {(float)6.5} /*the first element is initialized to 6.5 and the
other (four)elements are initialized to 0.0;*/
Passing Arrays to Functions: To pass an array to a function we do as follows:
1- Enter the array’s data type and empty square brackets in the prototype.
float calcSale(float [] );
2- Enter the array name in the function call.
float sale[12] = {0.0};
cout<<”Total sale: “<<calcSale(sale)<<endl;
3- Enter the array’s data type and name, followed by empty square brackets, in the function header.
float calcSale(float sale[])
Arrays in C++ are automatically passed by reference rather than by value.
Two-Dimensional
Arrays:
A two-dimensional array resembles a table in that the elements are in rows and columns. We must specify two subscripts: The first identifies the element’s row, and the second identifies the element’s column. Note that multiple-dimensional arrays can have more than two subscripts. C++ compilers support at least 12 array subscripts. In general, an array with m rows and n columns is called a m-by-n array. Examples:
int b[2][3] = {{1, 2, 3}, {4, 5, 6}} in this array we have:
b[0][0] = 1 b[0][1] = 2 b[0][2] = 3
b[1][0] = 4 b[1][1] = 5 b[1][2] = 6
int number[2][5] = {0}; // All elements are initialized to zero.
char students[3][20] = {“David”,”Steven”,”Sara”}; /* It creates an array of string values (three names with maximum 20 characters each). We can print these names only with referencing the first dimension as follows:
cout<<”The first name is “<<students[0]<<”The second name is “<<students[1]
<<”The third name is “<<students[2]<<endl;
Passing Two-Dimension Arrays to Functions:
Passing two-dimensional array to a function is similar to passing one-dimensional array to a function with one difference. We need to put the second bracket with its subscript in function prototype and in function header. Example:
In function prototype float printSale(float [][4]);
In function call float sale[20][4];
cout<<printSale(sale)<<endl;
in function header float printSale(float [][4])
Structures:
As you know the array is a group of related data with the same data types. In structures we can have a group of related data with different data types. Structures allow us to define a record of information. So we can create our own data types. Example: struct studentRecord
{
long studentId;
char studentName[25];
float studentGpa;
};
Keyword struct introduces the structure definition. The identifier studentRecord is the structure tag that names the structure definition and is used to declare variables of the structure type. In this example , the new type name is studentReord. The names declared in the braces of the structure definition are the structure’s members.
StudentRecord stdRec[3] = {{15134, “David”, 3.7}
{15265, “Mike”, 3.6}
{15386, “Sara”, 3.9}
};
or we can initialize to zero as follow:
studentRecord stdRec = {0, “”, 0};
Members of a structure are accessed using the member access operators the dot operator (.). stdRec[0].studentId = 15134 stdRec[0].studentName = “David”
stdRec[0].studentGpa = 3.7
stdRec[1].studentId = 15265 stdRec[1].studentName = “Mike”
stdRec[1].studentGpa = 3.6
and we can print them as follows:
cout<<”The student Id number is “<<stdRec[2].studentId<<endl;
cout<<”The student Name is “<<stdRec[2].studentName<<endl;
cout<<”The student GPA is “<<stdRec[2].studentGpa<<endl;
For the subscript (instead 2), we can use a variable like i . So we can create a loop to print or read each member for each element in the array.
Counters and
Accumulators:
A counter is a numeric variable used for counting something, often within a loop (e.g. I = I + 1 ). An accumulator is a numeric variable is used to tally (sum) values within a loop structure (e.g. totalSale = totalSale + sale).
Program Examples:
Example 1- // To read sales and calculate the total sale using while loop
#include<iostream.h>
void main()
{
float sales = 0.0;
float totalSales = 0.0;
int counter = 0;
cout<<"Enter the first sales amount: "<<endl;
cin>>sales;
cout<<”Enter –1 ,if you don’t have sales value”<<endl;
while(sales != -1)
{
totalSales = totalSales + sales; // this is an accumulator à totalSales
counter = counter +1;
cout<<"Enter the next sales amount: "<<endl;
cin>>sales;
}
cout<<"How many sales do you have? "<<counter<<endl;
cout<<"The total sale amount is "<<totalSales<<endl;
}
Example 2-
// To read sales and calculate the total sale using do … while loop
#include<iostream.h>
void main()
{
float sales = 0.0;
float totalSales = 0.0;
int counter = 0;
cout<<"Enter the first sales amount: "<<endl;
cin>>sales;
do
{
totalSales = totalSales + sales; // this is an accumulator
counter = counter +1; // this is a counter (how many sales)
cout<<"Enter the first sales amount: "<<endl;
cin>>sales;
}
while(sales != -1);
cout<<"How many sales do you have? "<<counter<<endl;
cout<<"The total sale amount is "<<totalSales<<endl;
}
Example 3-
// To read and print an array (one-dimensional) with for loop
#include<iostream.h>
void main()
{
int i = 0;
float sales[10] = {0};
float totalSales = 0.0;
for(i = 0; i <= 9 ; i++)
{
cout<<"Enter sale number "<<i+1<<": ";
cin>>sales[i];
totalSales = totalSales + sales[i];// this is an accumulator
}
cout<<"***The list of our sales***"<<endl;
for(i = 0; i <= 9; i++)
{
cout<<"Sales number "<<i+1<<" is "<<sales[i]<<endl;
}
cout<<"The total sales is $"<<totalSales<<endl;
}
Example 4-
// To read and print student grade using two-dimensional array
#include<iostream.h>
void main()
{
int i = 0;
int j = 0;
float studGrade[4][3] = {0};
// to read the student grades
for(i = 0; i<=3; i++)
for(j = 0; j<=2; j++)
{
cout<<"Enter student number "<<i+1<<" course "<<j+1<<" grade ";
cin>>studGrade[i][j];
}
cout<<"\n***The students courses grade list***"<<endl;
// to print the student grades
for(i = 0; i<=3; i++)
for(j = 0; j<=2; j++)
{
cout<<"Student number "<<i+1<<" for course "<<j+1<<" the grade is "<<studGrade[i][j]<<endl;
}
}
Example 5-
// This program is about Record Structure for students
#include<iostream.h>
void main()
{
int i = 0;
struct studentRecordType
{
long studentId;
char studentName[25];
float studentGpa;
};
// initialization
studentRecordType stRecord[4] = { {100,"David",(float)3.7}, {200,"Steven",(float)3.9}, {300,"John",(float)3.5}, {400,"Bill",(float)3.6} };
// to print record structure with for loop
for(i = 0; i<=3; i++)
{
cout<<"Student Id is: "<<stRecord[i].studentId<<endl;
cout<<"Student Name is: "<<stRecord[i].studentName<<endl;
cout<<"Student GPA is: "<<stRecord[i].studentGpa<<endl;
cout<<" Next student "<<endl;
}
}
For more information about errors, you can go to this Web Site and type the error code in the text box for search then click on GO:
http://msdn.microsoft.com/default.asp
Please try to run the above programs again.
Have a nice day
See you in class
Esmaail M Nikjeh