add results of a for loop after each iteration - c++

I‘m having trouble with my for loop. I have a basic 2 times table that goes up from 1 to 10. (see below). I'm trying to add the result so that after every loop, allResult displays the values of all results added. it needs to show all results added after every loop. and I don't know how to go about it. A better description is the desired outcome commented in the code.
my Code...
int main(){
int allResult;
for( int i = 1; i < 11; i++)
{
int result = 2*i;
cout << 2 << " times " << i << " = " << result << endl;
// I want allResult to store results added. so after first loop, result = 2 so allResult = 2
// after second loop, result = 4. so allResult should be 6. (results from 1 and 2 added)
// after third loop, result = 6 so allResult should be 12. (results from 1, 2 and 3 added)
// I'm trying to apply this to something else, that uses random numbers, so i cant just * result by 2.
}
system("pause");
}

int allResult = 0;
for( int i = 1; i < 11; i++)
{
allResult += 2*i;
cout << 2 << " times " << i << " = " << 2*i << endl;
}

int allResult = 0;
for( int i = 1; i < 11; i++)
{
int result = 2*i;
cout << "2 times " << i << " = " << result << endl;
allResult += result;
cout << "allResult: " << allResult << endl;
}

int main()
{
int allResult=0;
for( int i = 1; i < 11; i++)
{
int result = 2*i;
allResult=allResult+result;
/*Initially allResult is 0. After each loop iteration it adds to its previous
value. For instance in the first loop it was allResult=0+2,
which made allResult equal to 2. In the next loop allResult=2+4=6.
Third Loop: allResult=6+6=12. Fourth loop:allResult 12+8=20 and so on..*/
cout << 2 << " times " << i << " = " << result << endl;
}
system("pause");
}

Related

C++ Hashing search function stuck in endless "else" and "while" loop

If the generated random number to look for does not exist in hashtable array, then programm gets stuck in endless loop in function void hashSearch(),
whereas it should just get out of the loop and output that search item is not found. The exact place in code is where these to outputs are:
cout << "stuck in else loop \n"; and cout << "stuck in while loop end \n";.
I've googled around, but can't find similar examples.
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <chrono>
using namespace std;
int arr [1000];
int arr2 [1000];
int randArrayInt, n, randSearchItem, searchInt, address, size2;
void printZeroArr();
void linearSentinelSearch();
void printHashArray();
void hashSearch();
int main ()
{
srand (time(nullptr)); //initialize random seed:
n = rand() % 900 + 100; //random integer number from 100 - 1000, length of the array
//n = rand() % 10; // random number in the range 1-10 for sanity tests, length of the array
//randSearchItem = rand() % 10 + 1;
randSearchItem = rand() % 900 + 100; //this is the number to search for
cout << "Array length is " << n << endl;
cout << "[";
for (int i = 0; i <= n; i++)
{
randArrayInt = rand() % 900 + 100;
//randArrayInt = rand() % 10 + 1; // generate random 1-10 number for for sanity tests
arr[i] = randArrayInt; // insert into array position the generated random number
cout<< " " << arr[i]; // print out array element at current loop position
}
cout << " ]\n" << endl;
printZeroArr();
}
void printZeroArr()
{
size2 = n + 1; //length of hashed array
cout << "This is the random key to search for in array: " << randSearchItem << endl;
cout << "This is the size2 length " << size2 << endl;
cout << "This is the hasharray with zeros" << endl;
cout << "[";
for (int i = 0; i <= size2; i++)
{
arr2[i] = 0; // insert into hasharray number 0
cout<< " " << arr2[i]; // print out hasharray element at current loop position
}
cout << " ]\n" << endl;
linearSentinelSearch();
}
void linearSentinelSearch()
{
auto start = std::chrono::high_resolution_clock::now();
arr[n + 1] = randSearchItem;
//cout << "testing arr[n + 1] is " << arr[n + 1] << endl;
int i = 0;
while (arr[i] != randSearchItem) i++;
if (i == n + 1)
cout << "Sentinel search did not found the searchitem in random array" << "\n" << endl;
else
cout << "Searchitem found in array with linearsearch at position " << i << "\n" << endl;
auto finish = std::chrono::high_resolution_clock::now();
chrono::duration<double> elapsed = finish - start;
cout << "Elapsed time: " << elapsed.count() << " s\n";
printHashArray();
}
void printHashArray()
{
//cout << "printing out 'address' value, or the modulo result: " << endl;
//cout << "[";
for (int i = 0; i <= n; i++)
{
address = arr[i] % size2;
//cout << " " << address;
while (arr2[address] != 0)
{
if (address == size2 - 1)
{
address = 0;
} else
{
address++;
}
}
arr2[address] = arr[i];
}
//cout << " ]\n" << endl;
cout << "This is the hasharray with hashitems" << endl;
cout << "[";
for (int i = 0; i <= size2; i++)
{
cout << " " << arr2[i];
}
cout << " ]\n" << endl; hashSearch();
}
void hashSearch()
{
auto start = std::chrono::high_resolution_clock::now();
int searchInt = randSearchItem % size2;
while ((arr2[searchInt] != 0) && (arr2[searchInt] != randSearchItem))
{
if (searchInt == size2 - 1)
{
searchInt = 0;
cout << "if loop \n";
}
else
{
searchInt++;
cout << " stuck in else loop \n";
}
cout << " stuck in while loop end \n";
}
if (searchInt == 0) {
cout << "Search item not found using hashSearch" << endl;
} else {
cout << "Search item " << randSearchItem << " found using hashSearch at position " << searchInt << " in arr2." << endl;
}
auto finish = std::chrono::high_resolution_clock::now();
chrono::duration<double> elapsed = finish - start;
cout << "Elapsed time: " << elapsed.count() << " s\n";
}
Whereas it should just get out of the loop and output that search item is not found.
Search for cout << " stuck in else loop \n"; and cout << " stuck in while loop end \n";.
You want to stop your loop when you hit the end of the array: To that effect, you set the item to search for to zero:
if (searchInt == size2 - 1)
{
searchInt = 0;
cout << "if loop \n";
}
But in the loop control, you don't test that. You only test the array element at the current index for zero (not found) or the item to search (found):
while ((arr2[searchInt] != 0) && (arr2[searchInt] != randSearchItem)) ...
You need an additional test:
while ((searchInt != 0) && ...) ...
It took me a while to see that you want to code an open-address hastable where a zero marks unused slots. The hash value is just the number itself. Using zero as indicator for an empty slot is not ideal: You cannot store numbers whose hash code modulo the table size is zero.
I'd also code this with a non-void function where the return value is the index or some unambiguous value meaning "not found", perhaps -1. (Alternatively, you can return a pointer to the found item or NULL if the item isn't found -- after all, the index in the hash array is part of the hash table's internals and non concern to the caller.)
Then you can use early returns:
int hashSearch(const int *arr2, int size2, int item)
{
int i = item % size2;
for (; i < size2; i++) {
if (arr2[i] == -1) break; // -1 indicated unused space
if (arr2[i] == item) return i; // return index of item
}
return -1; // not found!
}
But what do you do if there is no room for a further element when you have a hash code close to the array size? You will need to add extra space at the end or you'll need to wrap around. Perhaps that is what you wanted to achieve by setting the index back to zero. In your case, ther array is full, so there are no zeros that could serve as loop-breaking criterion. You will have to find another criterion. You could ensure that there are zeros by making the hash table 30% or so bigger than the number of entries. Or you could try to detect whether the index has come full circle to the original index.
As already pointed out to you in comments: Try to use function arguments and local variables rather than puttin everything into global space. Also, the chaining of function calls, where the last thing in a function is to call the next one is strange. It's probably better to put all sequential calls into main.

Condition within for loop not executing

I'm writing a trivial program that doubles the amount of rice grains per each square on a chess board. I'm trying to work out the amount of squares required for at least 1 000 000 000 grains of rice. The problem is, what ever I try, the second if statement gets skipped even though 'test' is false after first iteration.
I've tried an else after the if statement, but the else is skipped when 'test' variable is false.
constexpr int max_rice_amount = 1000000000;
int num_of_squares = 0;
int rice_grains = 0;
bool test = true; // so we can set rice_grains amount to 1
for (int i = 0; i <= max_rice_amount; i++)
{
if (test == true)
{
rice_grains = 1; // This will only happen once
test = false;
}
else if (test == false)
rice_grains *= 2;
++num_of_squares;
std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";
}
The else causes the issue. But C++ is more powerful than you can imagine. Rework your loop to
for (
int rice_grains = 1, num_of_squares = 1;
rice_grains <= max_rice_amount;
rice_grains *= 2, ++num_of_squares
){
with
std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";
as the loop body; and weap at the beauty.
Looking at the problem description, this looks a good fit for a while loop or a do-while loop.
#include <iostream>
void f()
{
constexpr int max_rice_amount = 1000000000;
int num_of_squares = 1;
int rice_grains = 1;
while (rice_grains < max_rice_amount)
{
std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";
rice_grains *= 2;
++num_of_squares;
}
}
Code at compiler explorer
Here you recognize 3 big blocks:
Initialization
The 'until' condition in the while
The manipulation

C++ Nested for loop for exponents with set base/exponent

So I need some help with this. I want to print out all integers between 2 and 2^20 that are integer powers of 2. I figured out that I need to increase the power by 1 each time but I can't seem to figure out what goes inside the inner for loop. I cannot use the pow() function
c = 2;
cout << "\nPROBLEM C" << endl;
for (int powerC = 1; powerC <= 20; powerC++) // powerC is exponent
{
cout << setw(5) << powerC << " ";
counterC++;
for (int x = 1; x <= 20; x++) // where I am having trouble with
{
c = (c*powerC);
cout << setw(5) << c;
} // end inner for loop
if (counterC % 8 == 0)
{
cout << endl;
}
}
cout << "\nNumber of numbers = " << counterC;
This is much simpler by using the << operator.
Since 2 is 2^1, you want to print all integers from 2^1 to 2^20 inclusively, or 20 numbers:
int c = 2;
for (int i=0; i<20; i++)
{
std::cout << c << std::endl;
c <<= 1;
}

How can I get the array to show the previous list of array content before the next input?

I need the user input to be saved into my array and then output the array before the user inputs the next time. I have been moving things around different ways but cannot seem to get them to perform properly. I tried to cut down the code to the two functions I am having issues with.
void PlayGame()
{
const int HighestNum = 50;
const int LowestNum = 1;
int RandomNumber = LowestNum + rand() % HighestNum; //set for better random results
cout << "Guess the random number between " << LowestNum << " and " << HighestNum << "!\n\n";
const int attempts = 15;// limits the attempts to guess the random number to 15
int Guess [attempts] = {};
cout << "Enter your guess " << endl;
for (int count = 0; count < attempts; count++)
{
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the results
switch (r)//switch statement for function results, letting the user know if they matched the number, if the number is higher, or lower
{
case 0:
cout << "You Win!!" << endl;
cout << "\n";
cin.get();
return;
case 1:
cout << "The number is higher than your guess" << endl;
break;
case -1:
cout << "The number is lower than your guess" <<endl;
break;
}
if (count == 15)
{
cout << "Sorry, no guesses remain. The random number was... " << RandomNumber << "!";//so the user can see the random number at the end of their attempts
cout << "\n";
cin.get();
Again();
}
}
return;
}
int DisplayGuess(int member[])
{
for(int i = 0; i < 15; ++i)
cout << "\nGuess " << i + 1 << ": " << member[i];
cout << endl;
return;
}
Try this inside your loop
if(count > 0)
{
for (int j= 0; j < count; j++)
{
cout<<Guess[j];
}
}
Call DisplayGuess() in the first line of the for loop. Since the first you time you call it your array is empty, it shouldn't output anything.
So,
for (int count = 0; count < attempts; count++)
{
DisplayGuess(Guess[count]);
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the
results
. . . . . .

How to count the number of time a random number is generated in a less cumbersome way?

If a program should simulate a dice roll, and roll the dice any given number of times. How can a code be written, so it could count the times a number was rolled? I have a code below, but I think it's a tedious and ugly method to accomplish this task. I think there is a better way to do this, perhaps a very less cumbersome code.
here is the code:
#include <iostream>
#include <ctime>
int main(int argc, const char * argv[]) {
int roll, s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0, s6 = 0, i, roll_times = 0;
std::cout << "How many times do you want to roll the dice?" << std::endl;
std::cin >> roll_times;
srand(unsigned(time(NULL)));
for(i = 0; i < roll_times; i++) {
roll = rand() % 6 + 1;
switch(roll) {
case 1:
s1++;
break;
case 2:
s2++;
break;
case 3:
s3++;
break;
case 4:
s4++;
break;
case 5:
s5++;
break;
case 6:
s6++;
break;
}
}
std::cout << "The number 1 was rolled " << s1 << " times." << std::endl;
std::cout << "The number 2 was rolled " << s2 << " times." << std::endl;
std::cout << "The number 3 was rolled " << s3 << " times." << std::endl;
std::cout << "The number 4 was rolled " << s4 << " times." << std::endl;
std::cout << "The number 5 was rolled " << s5 << " times." << std::endl;
std::cout << "The number 6 was rolled " << s6 << " times." << std::endl;
return 0;
}
Instead of having individual variables, you can utilize an array of 6 integers. Then make use of the indices in the first for-loop to set your counts. The same idea can be applied to your output to the screen.
int main(int argc, const char * argv[]) {
int roll, i, roll_times = 0;
int dice[6] = {0};
cout << "How many times do you want to roll the dice?" << endl;
cin >> roll_times;
srand(unsigned(time(NULL)));
for(i = 0; i < roll_times; i++)
{
roll = rand() % 6;
dice[roll]++;
}
for(int k = 1; k <= 6; k++)
{
cout << "The number " << k << " was rolled " << dice[k-1] << " times." << endl;
}
return 0;
}
i would use an array, something like that:
int counts[6] = {0};
for(i=0;i<roll_times;i++) {
counts[rand()%6]++;
}
Make yourself a std::array which contains the counts. Then, whenever a number appears, you increment the specific count. For example:
std::array<unsigned, 6> numberCounts;
numberCounts.fill(0);
for (int i = 0; i < rollTimes; ++i)
{
++numberCounts[rollDice()];
}
// Print numberCounts
Please note: std::array is available since C++11.
OK I think a less tedious way to do this is to create an array of size 6, and then add 1 every time a number is rolled and is equal to the index number of this array, but because array indexes in c++ are zero based, all I have to do is subtract 1 from the rolled number. for example when program rolls 1, 5 times, it is added to array[rolled number - 1] or array[0]. so I wrote a much better code:
#include <iostream>
#include <ctime>
int main(int argc, const char * argv[]) {
int roll = 0, i = 0, roll_times = 0,roll_repeat[6] = {0};
std::cout << "How many times do you want to roll the dice?" << std::endl;
std::cin >> roll_times;
srand(unsigned(time(NULL)));
for(i = 0; i < roll_times; i++) {
roll = rand() % 6 + 1;
roll_repeat[roll - 1]++;
}
for(i = 0; i < 6; i++) {
std::cout << "The number " << i + 1;
std::cout << " was rolled " << roll_repeat[i] << " times.";
std::cout << std::endl;
}
return 0;
}