Tag Archives: Sum
Java || Snippet – How To Do Simple Math Using Integer Arrays
This page will consist of simple programs which demonstrate the process of doing simple math with numbers that are stored in an integer array.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
Integer Arrays
The "Random" Class
For Loops
Assignment Operators - Simple Math Operations
Custom Setw/Setfill In Java
Note: In all of the examples on this page, a random number generator was used to place numbers into the array. If you do not know how to obtain data from the user, or if you do not know how to insert data into an array, click here for a demonstration.
===== ADDITION =====
The first code snippet will demonstrate how to add numbers together which are stored in an integer array. This example uses the “+=” assignment operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import java.util.Random; public class Addition { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe sum of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum + arry[x] totalSum += arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
SAMPLE OUTPUT
Welcome to My Programming Notes' Java Program.
Original array values:
22 26 41 89 35 90 15 99 85 5 95 86
--------------------------------------------------
The sum of the items in the array is: 688
===== SUBTRACTION =====
The second code snippet will demonstrate how to subtract numbers which are stored in an integer array. This example uses the “-=” assignment operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import java.util.Random; public class Subtraction { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe difference of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum - arry[x] totalSum -= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
SAMPLE OUTPUT
Welcome to My Programming Notes' Java Program.
Original array values:
99 92 91 26 1 52 98 62 51 22 64 65
--------------------------------------------------
The difference of the items in the array is: -723
===== MULTIPLICATION =====
The third code snippet will demonstrate how to multiply numbers which are stored in an integer array. This example uses the “*=” assignment operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import java.util.Random; public class Multiplication { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe product of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum * arry[x] totalSum *= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
SAMPLE OUTPUT
Welcome to My Programming Notes' Java Program.
Original array values:
95 63 32 19 93 83 71 35 32 37 66 95
--------------------------------------------------
The product of the items in the array is: 494770176
===== DIVISION =====
The fourth code snippet will demonstrate how to divide numbers which are stored in an integer array. This example uses the “/=” assignment operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import java.util.Random; public class Division { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable double totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe quotient of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum / arry[x] totalSum /= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
SAMPLE OUTPUT
Welcome to My Programming Notes' Java Program.
Original array values:
28 85 90 52 1 64 93 85 4 22 4 28
--------------------------------------------------
The quotient of the items in the array is: 1.8005063061510687E-17
C++ || Snippet – How To Do Simple Math Using Integer Arrays
This page will consist of simple programs which demonstrate the process of doing simple math with numbers that are stored in an integer array.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
Integer Arrays
For Loops
Assignment Operators - Simple Math Operations
Setw
Note: In all of the examples on this page, a random number generator was used to place numbers into the array. If you do not know how to obtain data from the user, or if you do not know how to insert data into an array, click here for a demonstration.
===== ADDITION =====
The first code snippet will demonstrate how to add numbers together which are stored in an integer array. This example uses the “+=” assignment operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int totalSum =0; srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe sum of the items in the array is: "; // Find the sum of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalSum = totalSum + arry[i] totalSum += arry[i]; } // after the calculations are complete, display the total to the user cout<< totalSum <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
SAMPLE OUTPUT
Original array values
64 85 44 31 35 2 94 67 12 80 97 10
--------------------------------------------------------
The sum of the items in the array is: 621
===== SUBTRACTION =====
The second code snippet will demonstrate how to subtract numbers which are stored in an integer array. This example uses the “-=” assignment operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int totalDiffetence =0; srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe difference of the items in the array is: "; // Find the difference of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalDiffetence = totalDiffetence - arry[i] totalDiffetence -= arry[i]; } // after the calculations are complete, display the total to the user cout<< totalDiffetence <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
SAMPLE OUTPUT
Original array values
10 43 77 10 2 17 87 67 6 95 57 18
--------------------------------------------------------
The difference of the items in the array is: -489
===== MULTIPLICATION =====
The third code snippet will demonstrate how to multiply numbers which are stored in an integer array. This example uses the “*=” assignment operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int totalProduct =1; srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe product of the items in the array is: "; // Find the product of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalProduct = totalProduct * arry[i]; totalProduct *= arry[i]; } // after the calculations are complete, display the total to the user cout<< totalProduct <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
SAMPLE OUTPUT
Original array values
33 36 52 28 4 99 97 17 42 81 83 33
--------------------------------------------------------
The product of the items in the array is: 1803759104
===== DIVISION =====
The fourth code snippet will demonstrate how to divide numbers which are stored in an integer array. This example uses the “/=” assignment operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable float totalQuotient =1; // need to save the variable as a float, not an int srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe quotient of the items in the array is: "; // Find the quotient of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalQuotient = totalQuotient / arry[i]; totalQuotient /= arry[i]; } // after the calculations are complete, display the total to the user cout<< totalQuotient <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
SAMPLE OUTPUT
Original array values
75 38 59 14 53 42 29 88 92 27 69 16
--------------------------------------------------------
The quotient of the items in the array is: 2.72677e-020
C++ || Input/Output – Find The Average of The Numbers Contained In a Text File Using an Array/Bubble Sort
This program highlights more practice using text files and arrays. This program is very similar to one which was previously discussed on this site, but unlike that program, this implementation omits the highest/lowest values which are found within the array via a sort.
The previously discussed program works almost as well as the current implementation, but where it fails is when the data which is being entered into the program contains multiple values of the same type. For example, using the previously discussed method to obtain the average by omitting the highest/lowest entries found within an array, if the array contained the numbers:
1, 2, 3, 3, 3, 2, 2, 1
The previous implementation would mark 1 as being the lowest number (which is correct) and it would mark 3 as being the highest number (which is also correct). The area where it fails is when it omits the highest and lowest scores found within the array. The program will skip over ALL of the numbers contained within the array which equal to 1 and 3, thus resulting in the program obtaining the wrong answer.
To illustrate, before the previous program computes its adjusted average scores, it will not only omit just 1 and 3 from the array, but it will also omit all of the 1’s and 3’s from the list, resulting in our array looking like this:
2, 2, 2
When you are finding the average of a list of numbers by omitting the highest/lowest scores, you don’t want to omit ALL of the values which may equal said numbers, but merely just the highest (last element in the array) and lowest (first element in the array) scores.
So if the previous implementation has subtle issues, why is it on this site? The previous program illustrates very well the process of finding the highest/lowest integers found within an array. It also works flawlessly for data in which there is non repeating values found within a list (i.e 1,2,3,4,5,23,6). So if you know you are reading in from a file in which there are non repeating values, the previous implementation works well. Often times though, developers do not know what type of data the incoming files will contain, so this current implementation is a better way to go, especially if it is not known exactly how many numbers are contained within a file.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Fstream
Ifstream
Ofstream
Working With Files
While Loops
For Loops
Bubble Sort
Basic Math - Finding The Average
The data file that is used in this example can be downloaded here.
Note: In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
#include <iostream> #include <fstream> using namespace std; // function prototype float FindOmittedAverage(int numbers[], int counter); int main() { // declare variables ifstream infile; ofstream outfile; float average=0; float sum =0; int highestNumber = -999999; int lowestNumber = 99999999; int numbers[100]; // open the input file in which you will read data from infile.open("INPUT_Numbers_ programmingnotes_freeweq_com.txt"); if(infile.fail()) { cout<<"nInput file not found!n"; exit(1); // there was an error, program exits } // open the output file in which the compiled data will be saved to outfile.open("OUTPUT_Averages_ programmingnotes_freeweq_com.txt"); if(outfile.fail()) { cout <<"There was an error creating the output file, press enter to terminate program."; exit(1); // there was an error, program exits } // display data to screen via cout cout <<"The numbers countained in the input file are: "; // saves data to the outfile. Notice the declaration to // save data to the outfile is the same as the ^ above cout // statment outfile <<"The numbers countained in the input file are: "; // incoming data from the file will be stored in an int array // so this counter will increment the array index every time the // program finds a new value inside the file to store inside the array int counter =0; // this while loop will read in data from the file until it reaches the end of the file // (i.e until there are no more number found within the file) // this process also stored the numbers inside the "numbers" array while(infile >> numbers[counter]) { // 'sum' variable adds the incoming numbers together // computing the sum sum += numbers[counter]; // finds the highest number contained within the incoming file if( numbers[counter] > highestNumber) { highestNumber = numbers[counter]; } // finds the lowest number contained within the incoming file if (numbers[counter] < lowestNumber) { lowestNumber = numbers[counter]; } // displays the currently found number from the file to stdout cout << numbers[counter] << ", "; // saves the currently found number from the file to the output file outfile << numbers[counter]<< ", "; ++counter; } // always close your file after your done using them infile.close(); // display the highest found number to stdout cout<< "nnThe highest and lowest numbers contained in the file are: nHighest: " << highestNumber<<"nLowest: "<<lowestNumber<<endl; // saves the highest found number to the output file outfile<< "nnThe highest and lowest numbers contained in the file are: nHighest: " << highestNumber<<"nLowest: "<<lowestNumber<<endl; // using the sum found from the above while loop, we compute the average average = sum/(counter); // display/save the average of the numbers which were contained in the // file to stdout and the output file cout<<"nThe average of the "<<counter<<" numbers contained in the file is: "<<average<<endl; outfile<<"nThe average of the "<<counter<<" numbers contained in the file is: "<<average<<endl; // function declaration which finds the omitted average of the found numbers // from the file average = FindOmittedAverage(numbers,counter); // display/save the omitted average of the numbers which were contained in the // file to stdout and the output file cout<<"nThe average of the "<<counter<<" numbers contained in the file omitting the highest and lowest scores is: "<<average<<endl; outfile<<"nThe average of the "<<counter<<" numbers contained in the file omitting the highest and lowest scores is: "<<average<<endl; // closes the outfile once we are done using it outfile.close(); return 0; } // function takes in the 'numbers' array, and 'counter' variable from // the main function as parameters, and computes the average, omitting // the highest and lowest numbers found within the array float FindOmittedAverage(int numbers[], int counter) { float sum = 0; float avg = 0; // this is a 'bubble sort' which will sort the numbers // contained within the array, from lowest to the highest // i.e (1,2,3,4,5,6,7,8) for(int iteration = 1; iteration < counter; iteration++) { for(int index = 0; index < counter - iteration; index++) { // if the previous value in the array is bigger than the next, then swap them if(numbers[index]> numbers[index+1]) { int temp = numbers[index]; numbers[index] = numbers[index+1]; numbers[index+1]= temp; } } }// end of sort // after the sorting is complete, set the highest // and lowest elements in the array to zero numbers[0]=0; numbers[counter-1]=0; // find the sum of the newly sorted array // with the highest and lowest entries being deleted (set to zero) for(int i = 0; i < counter; i++) { sum += numbers[i]; } // compute the average avg = sum / (counter-2); // return the average back to main return avg; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Remember to include the input file)
The numbers countained in the input file are: 12, 45, 23, 46, 11, -5, 23, 33, 50, 17, 13, 25, 15, 50,
The highest and lowest numbers contained in the file are:
Highest: 50
Lowest: -5The average of the 14 numbers contained in the file is: 25.5714
The average of the 14 numbers contained in the file omitting the highest and lowest scores is: 26.0833
C++ || Find The Average Using an Array – Omit Highest And Lowest Scores
This page will consist of two programs which calculates the average of a specific amount of numbers using an array.
REQUIRED KNOWLEDGE FOR BOTH PROGRAMS
Float Data Type
Constant Values
Arrays
For Loops
Assignment Operators
Basic Math
====== FIND THE AVERAGE USING AN ARRAY ======
The first program is fairly simple, and it was used to introduce the array concept. The program prompts the user to enter the total amount of numbers they want to find the average for, then the program displays the answer to them via cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream> using namespace std; int main() { // declare variables float total = 0; int numElems = 0; float average[100]; // declare array which has the ability to hold 100 elements cout << "How many numbers do you want to find the average for?: "; cin >> numElems; // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { cout << "nEnter #" << index +1<< " : "; cin >> average[index]; total += average[index]; } // find the average. Note: // the expression below literally // means: total = total / numElems; total /= numElems; cout << "nThe average of the " << numElems << " numbers is " << total <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
ARRAY
Notice the array declaration on line #9. The type of array being used in this program is a static array, which has the ability to store up to 100 integer elements in the array. You can change the number of elements its able to store to a higher or lower number if you wish.
FOR LOOP
Notice line 17-22 contains a for loop, which is used to actually store the data inside of the array. Without some type of loop, it is virtually impossible for the user to input data into the array; that is, unless you want to add 100 different cout statements into your code asking the user to input data. Line 21 uses the assignment operator “+=” which gives us a running total of the data that is being inputted into the array. Note the loop only stores as many elements as the user so desires, so if the user only wants to input 3 numbers into the array, the for loop will only execute 3 times.
Once compiled, you should get this as your output:
How many numbers do you want to find the average for?: 5
Enter #1 : 23
Enter #2 : 17
Enter #3 : 29
Enter #4 : 14
Enter #5 : 16
The average of the 5 numbers is 19.8
====== FIND THE AVERAGE – OMIT HIGHEST AND LOWEST SCORES ======
The second program is really practical in a real world setting, specifically when a teacher records test scores into the computer. We were asked to create a program for a fictional competition which had 6 judges. The 6 judges each gave a score of the performance for a competitor in a competition, (i.e a score of 1-10), and we were asked to find the average of those scores, omitting the highest/lowest results. The program was to store the scores into an array, display the scores back to the user via cout, display the highest and lowest scores among the 6 obtained, display the average of the 6 scores, and finally display the average adjusted scores omitting the highest and lowest result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
#include <iostream> using namespace std; const int NUM_JUDGES = 6; int main() { int scores[NUM_JUDGES]; // array is initialized using a const variable int highestScore = -999999; int lowestScore = 999999; float sumOfScores = 0; float avgScores = 0; // use a for loop to obtain data from user using the const variable cout<< "Judges, enter one score each for the current competitor: "; for(int counter=0; counter < NUM_JUDGES; ++counter) { cin >> scores[counter]; } // use another for loop to redisplay the data back to the user via cout cout<<"nThese are the scores from the " << NUM_JUDGES << " judges: "; for(int index=0; index < NUM_JUDGES; ++index) { cout<<"nThe score for judge #"<<(index+1)<<" is: "<<scores[index]; } // use a for loop to go thru the array checking to see the highes/lowest element cout<<"nnThese are the highest and lowest scores: "; for(int index=0; index < NUM_JUDGES; ++index) { // if current score in the array is bigger than the current 'highestScore' // element, then set 'highestScore' equal to the current array element if(scores[index] > highestScore) { highestScore = scores[index]; } // if current 'lowestScore' element is bigger than the current array element, // then set 'lowestScore' equal to the current array element if(lowestScore > scores[index]) { lowestScore = scores[index]; } } cout << "ntHighest: "<< highestScore; cout << "ntLowest: "<< lowestScore; cout << "nThe average score is: "; // this calculates a running total, adding each element in the array together for(int counter=0; counter < NUM_JUDGES; ++counter) { sumOfScores += scores[counter]; } avgScores = sumOfScores/NUM_JUDGES; cout<< avgScores; // reset data back to 0 so we dont get wrong answers sumOfScores = 0; avgScores = 0; cout<<"nThe average adjusted score omitting the highest and lowest result is: "; // final loop, which calculates a running total, adding each element // in the array together, this time omitting the highest/lowest elements for(int counter=0; counter < NUM_JUDGES; ++counter) { // IF(current score isnt equal to the highest elem) AND (current score isnt equal lowest elem) // THEN create a running total if ((scores[counter] != highestScore) && (scores[counter] != lowestScore)) { sumOfScores += scores[counter]; } } avgScores = sumOfScores/(NUM_JUDGES-2); cout<< avgScores <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
CONST
A constant variable was declared and used to initialize the array (line 8). Note, when using static arrays, the program has to know how many elements to initialize the program with before the program starts, so creating a constant variable to do that for us is convenient.
FOR LOOPS
Once again loops were used to traverse the array, as noted on lines 16, 23, 30, 53, and 70. The const variable was also used within the for loops, making it easier to modify the code if its necessary to reduce or increase the number of available judges.
HIGHEST/LOWEST SCORES
This is noted on lines 34-44, and it is really simple to understand the process once you see the code.
OMITTING HIGHEST/LOWEST SCORE
Lines 70-78 highlight this process, and the loop basically traverses the array, skipping over the highest/lowest elements
Once compiled, you should get this as your output:
Judges, enter one score each for
the current competitor: 123 453 -789 2 23345 987These are the scores from the 6 judges:
The score for judge #1 is: 123
The score for judge #2 is: 453
The score for judge #3 is: -789
The score for judge #4 is: 2
The score for judge #5 is: 23345
The score for judge #6 is: 987These are the highest and lowest scores:
Highest: 23345
Lowest: -789
The average score is: 4020.17
The average adjusted score omitting the highest and lowest result is: 391.25
C++ || Input/Output Text File Manipulation – Find Highest, Lowest, Average & Total Sum
This is a program which will utilize fstream, specifically ifstream and ofstream, to read in data from one .txt file, and it will then output selected data into an entirely new separate .txt file.
The input data file has 8 different rows, with each row containing 7 numbers on each line. The program will take in each line one at a time, manipulating the 7 numbers to receive the desired output. This program will find the highest/lowest number in each selected line, along with the total sum of all the numbers contained in that line, and the average of all the numbers. So at the end of the program, There will be 8 different sets of data compiled for each row, with the output file looking like this:
SAMPLE RUN:
- Input File -
3 5 7 3 4 5 6- Output File -
The dataset for input line #1 is: 3 5 7 3 4 5 6
The highest number is: 7
The lowest number is: 3
The total of the numbers is: 33
The average of the numbers is: 4.71
The data file that is used in this example can be downloaded here
Note: In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio > Projects > [Your project name] > [Your project name]
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jan 6, 2012 // Taken From: http://programmingnotes.org/ // File: fileInput.cpp // Description: Demonstrates how to read and write data to a file // ============================================================================ #include <iostream> #include <fstream> using namespace std; int main () { // declare variables ifstream infile; ofstream outfile; int inputNumber = 0; int highestNum = -999999; int lowestNum = 999999; double sum = 0; double average = 0; int currentLineNum = 1; // This opens the input file infile.open("INPUT_programmingnotes_freeweq_com.txt"); if(infile.fail()) //there was an error on open, file not found { cout << "Cannot find input file, press enter to terminate program." << endl; exit (1); // there was an error, program exits } // This opens the output file outfile.open("OUTPUT_programmingnotes_freeweq_com.txt", ios::app); if(outfile.fail()) { cout <<"There was an error opening the output file, press enter to terminate program."; exit(1); // there was an error, program exits } do { cout << "The dataset for input line #" << currentLineNum << " is: "; outfile << "The dataset for input line #" << currentLineNum << " is: "; // loops thru file until we get to the last number // from the selected line // (theres 7 numbers total in each line, see input file for clarification) for(int counter = 1; counter <= 7; counter++) { infile >> inputNumber; sum += inputNumber; // calculates the total sum of #'s for each line // checks to see which number is highest/lowest from // each selected line if(inputNumber > highestNum) { highestNum = inputNumber; } if(inputNumber < lowestNum) { lowestNum = inputNumber; } // displays current number to output screen // and saves to file cout << inputNumber << "\t"; outfile << inputNumber << "\t"; }// end for loop average = sum / 7; // finds the total avg for each line // this displays data to the output screen cout << endl; cout << "The highest number is: " << highestNum << endl; cout << "The lowest number is: " << lowestNum << endl; cout << "The total of the numbers is: " << sum << endl; cout << "The average of the numbers is: " << average << endl; // outfile section here, saves data to file outfile << endl; outfile << "The highest number is: " << highestNum << endl; outfile << "The lowest number is: " << lowestNum << endl; outfile << "The total of the numbers is: " << sum << endl; outfile << "The average of the numbers is: " << average << endl << endl; // outfile section end // resets variables back to default values highestNum = -999999; lowestNum = 999999; sum = 0; average = 0; currentLineNum++; // places data on new line cout << endl << endl; } while(!infile.eof()); // loop stops once it reaches the end of file cout << endl << endl <<"\tWe have reached the end of the file!"<< endl; outfile << endl << endl <<"\tWe have reached the end of the file!"<< endl << endl; outfile.close(); // closes outfile infile.close(); // closes infile return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
LOOPS
This program utilizes one do/while loop on lines 39-97 which loops thru the input file until it reaches the end of the file. This program also uses a for loop, which is noted on line 46.
CALCULATING THE SUM
Line 50 contains the assignment operator “+=“, which will calculate a running total for all the values of each selected line.
READING IN DATA FROM FILE
This is noted in line 48, and works just like a cin statement.
OPENING FILES
File declarations, and the opening of files are highlighted on lines: 14-15, 24-25, 32-33. On line 32, the term “ios::app” means the file will append new data to the text file, instead of overwriting the old data contained within that file.
OUTPUT DATA TO FILE
This is highlighted on lines 80-84, and as you can see, the output statements are exactly the same as cout statements.
CLOSE FILES
Remember to close the files you open, as highlighted on lines 101 and 102.
Once compiling the above code, you should receive this as your output (for the 8 selected lines contained within the input text file)
The dataset for input line #1 is: 346 130 982 90 656 117 595
The highest number is: 982
The lowest number is: 90
The total of the numbers is: 2916
The average of the numbers is: 416.571The dataset for input line #2 is: 415 948 126 4 558 571 87
The highest number is: 948
The lowest number is: 4
The total of the numbers is: 2709
The average of the numbers is: 387The dataset for input line #3 is: 42 360 412 721 463 47 119
The highest number is: 721
The lowest number is: 42
The total of the numbers is: 2164
The average of the numbers is: 309.143The dataset for input line #4 is: 441 190 985 214 509 2 571
The highest number is: 985
The lowest number is: 2
The total of the numbers is: 2912
The average of the numbers is: 416The dataset for input line #5 is: 77 81 681 651 995 93 74
The highest number is: 995
The lowest number is: 74
The total of the numbers is: 2652
The average of the numbers is: 378.857The dataset for input line #6 is: 310 9 995 561 92 14 288
The highest number is: 995
The lowest number is: 9
The total of the numbers is: 2269
The average of the numbers is: 324.143The dataset for input line #7 is: 466 664 892 8 766 34 639
The highest number is: 892
The lowest number is: 8
The total of the numbers is: 3469
The average of the numbers is: 495.571The dataset for input line #8 is: 151 64 98 813 67 834 369
The highest number is: 834
The lowest number is: 64
The total of the numbers is: 2396
The average of the numbers is: 342.286We have reached the end of the file!