I have a task and I have no any idea how to start. There should be array with dimensions 3x4 and I have to insert there generated random integers in range [-7,20). I have problem because I've never used multidimensional arrays. Please show me the simpliest solution.
I think your best solution, on how to start, is to start with a foundation and add to it:
#include <iostream>
#include <cstdlib>
int main()
{
std::cout << "Hello World!\n";
std::cout << "Paused. Press ENTER to continue.\n";
std::cin.ignore(1000000, '\n');
return EXIT_SUCCESS;
}
The above short program will allow you to get your IDE and project set up correctly. Get this working first.
Next, you may want to work with multidimensional arrays:
const unsigned int MAXIMUM_ROWS = 4;
const unsigned int MAXIMUM_COLUMNS = 3;
int main()
{
std::cout << "Multidimensional array test\n\n";
int my_array[MAXIMUM_ROWS][MAXIMUM_COLUMNS];
for (size_t row = 0; row < MAXIMUM_ROWS; ++row)
{
for (size_t column = 0; column < MAXIMUM_COLUMNS; ++column)
{
my_array[row][column] = row * MAXIMUM_ROWS + column;
}
}
// Now to print
for (size_t row = 0; row < MAXIMUM_ROWS; ++row)
{
for (size_t column = 0; column < MAXIMUM_COLUMNS; ++column)
{
std::cout << my_array[row][column] << "\t";
}
std::cout << "\n";
}
std::cout << "Paused. Press ENTER to continue.\n";
std::cin.ignore(1000000, '\n');
return EXIT_SUCCESS;
}
Or, you could write a small program that generates random numbers within your range and prints them out.
Finally combine pieces of these working programs into your final masterpiece.
This is a technique of how to start. Search the internet for "Test Driven Development" for additional techniques on starting a program or project.
using a nested loop is the best idea.. with something like randr running in each loop
Related
I have seen this carriage return example online about a loading effect but I am failing to understand it properly. Why does it have to be 2 \rLoading and not one? Can someone explain it to me?
for (int j = 0; j < 3; j++) {
cout << "\rLoading \rLoading";
for (int i = 0; i < 3; i++) {
cout << ".";
sleep(300);
}
}
The first section
\rLoading____
is printed to have the string "Loading" and three empty spaces at the beginning of the line. The next carriage return then sets the cursor to the beginning of the line. Then
Loading
is printed again, but the cursor is now directly behind the word, at the first of the three spaces. Now here:
for (int i = 0; i < 3; i++) {
cout << ".";
sleep(300);
}
three dots are printed in an interval of 300 seconds each into the places, where the three dots are.
This whole procedure is iterated three times, so the main purpose of the three blanks of the first "Loading" is, to delete the dots from the previous iteration.
The key is that \r will not clear characters which were printed on the screen earlier. So the first \rLoading act as a display eraser.
In fact you can use 10 spaces instead of the Loading , but you must count it accurately, which is not intuitional.
The following is the optimized code, which can be directly compiled and run on an modern x86 & linux machine. You can try to delete one of the \rLoading and see what will happen for easily understanding.
#include <iostream>
#include <unistd.h>
int main(int argc, char* argv[]) {
for (int j = 0; j < 3; j++) {
std::cout << "\rLoading \rLoading" << std::flush;
// std::cout << "\r \rLoading" << std::flush; // same effect
for (int i = 0; i < 3; i++) {
std::cout << "." << std::flush;
sleep(1);
}
}
std::cout << std::endl;
return 0;
}
Two promotions:
a std::flush is needed or you will not see the effects
300 seconds is too long -> 1 seconds
i'm a complete beginner to programming and I started with C++. I'm on arrays now and i'm trying to create a simple ten times table. I succeeded with the following code but i's sceptical i did the right thing since there are no square brackets:
#include <iostream>
using namespace std;
int main() {
int product;
for(int i = 1; i < 11; ++i) {
for(int j = 1; j < 11; ++j) {
product = i*j;
cout << product << "\t" << flush;
}
cout << endl;
}
return 0;
}
After messing about a bit i came up with the following:
#include <iostream>
using namespace std;
int main() {
int row = 11;
int col = 11;
int table[row][col];
for(row = 1; row < 11; ++row) {
for(col = 1; col < 11; ++col) {
table[row][col] = row*col;
cout << table[row][col] << "\t" << flush;
}
cout << endl;
}
return 0;
}
Both give the desired output, my question is why? I'm also curious to know if the first really is an array, if not what is it? Any advice on my basic code writing will also be greatly appreciated.
The first example does not use an array. You are printing out the 10x tables but you are not storing that information in the program. This means that after the loop, the program will not remember what the table looks like.
In the second example the variable table is the multidimensional array.
After the look you could call cout << table[4][6] << endl; for example, and 24 would be printed, without re-computing what 4*6 is. This is because you saved the information in the multidimensional array.
(also as the comments mentioned, arrays in programming start at 0, meaning that ideally you should makes your loops for(row = 0; row <= 10; ++row) {. This way the first slot in the array is not being wasted.
Also as the comments are mentioning, 'vectors' are nice but if you are learning programming, you should understand how an array works, and I would suggest not getting into vectors until you understand the basics of an array)
Both give the desired output, my question is why?
Because in both cases you print the same value.
In first case, you save the value in a variable
product = i*j;
and print the variable
cout << product << "\t" << flush;
In second case, you save the same value (row has the same value as i, col has the same value as j; so row * col has the same value as i * j) in a variable
table[row][col] = row*col;
(this time is a variable inside an array of array, that depends from row and col) and you print the same variable
cout << table[row][col] << "\t" << flush;
I'm also curious to know if the first really is an array, if not what is it?
Do you mean product?
No: product is a simple integer variable.
A variable that change value at every iteration of product = i*j;
It's the table variable in the second example that is an array; or better, an array of arrays.
The difference is that at the end of the double for, product maintain only the value of the last calculated product when table maintain all the calculated product.
Any advice on my basic code writing will also be greatly appreciated.
First of all, as explained from Some programmer dude, the code
int row = 11;
int col = 11;
int table[row][col];
isn't correct C++ because you can't use non constant values for array dimensions.
You can use directly 11
int table[11][11];
or you can define row and col as constants
int const row = 11;
int const col = 11;
int table[row][col];
or better (starting from C++11) as constexpr constants
constexpr int row { 11 };
constexpr int col { 11 };
int table[row][col];
Second: IMHO it's better avoid (when possible) using namespace std; but explicating the namespace; so
std::cout << table[row][col] << "\t" << std::flush;
This avoid risks of name collisions when you use other libraries.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
char arr[10]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
gets(arr);
for (int i=0;i<1;i++)
{
for (int j=0;j<10;j++)
{
if(j<=4)
{
arr1[0][j]=arr[j] ;
}
else if (j>4)
{
arr1[1][j-5]=arr[j] ;
}
}
}
for(int j=0;j<5;j++)
{
cout<<arr1[0][j]<<" ";
}
cout<<endl;
for(int j=0;j<5;j++)
{
cout<<arr1[1][j]<<" ";
}
Here what i am trying to do is converting a 1d array in to 2d array.
my main purpose is to store 1d array on a 2d and when the first row is completed it should shift the string to next row it is doing all the as i have declared the arr[10] and inputting 10 charcter string through get(arr) it is storing the array as i want but at the end displays an error window i dont know why the program is running perfect as well as giving this error window
my input : hanzlaamja (10charcters)
my output:
h a n z l
a a m j a
according to my wish but the main problem is the error window.
note : there is nothing in error box or warning box.
My program is working perfectly, but i am getting an error of array corruption.
Can anybody help me out? I would be very thankful
please see this error message
full picture
The problem is that you read in 10 characters (e.g. "hanzlaamja") and the string termination character '\0', which is automatically added by gets. Thereby you exceed array bounds, as this would require space for 11 characters. So it would already work if you wrote char arr[11];. But as mentioned in the comments, do not use gets; it is unsafe and it does not prevent you from exceeding array bounds. The following snippet shows how to do this part better:
...
char arr[11]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
// gets(arr);
if (!fgets(arr,11,stdin)) {
cout << "no value read." << endl;
return 1;
}
...
A lot of your loops could be written shorter / better readable. But that's not the actual topic.
Adding to the great point pointed out by #Stephan Lechner, I have composed a solution "as close as possible" to your original.
Compiled under visual studio 2017.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout << "main - start" << endl;
const size_t numOfRows = 2;
const size_t numOfCol = 5;
const size_t numCharsInSingleDimArray = 10;
char arr[numCharsInSingleDimArray] = { '\0' }, arr1[numOfRows][numOfCol] = { '\0' };
cout << "enter the full line : ";
gets_s(arr); // Note:If the buffer (arr) is too small to contain the input line and null terminator, these functions invoke an invalid parameter handle.
cout << "main - entered:" << arr << endl;
char* twoDimArrStartLoc = &(arr1[0][0]); // as user4581301 pointed out, it is also possible to "approach" it by treating the two dimensional array as a contiguous bytes in memory
for (size_t i = 0, j = 0; i< numCharsInSingleDimArray; ++i, ++j)
{
twoDimArrStartLoc[j] = arr[i];
}
cout << "main - after converting the 1d array into 2d array, arr1 is:" << endl;
for (size_t i = 0; i < numOfRows; ++i)
{
for (size_t j = 0; j < numOfCol; ++j)
{
cout << "arr1[" << i << "]" << "[" << j << "]:" << arr1[i][j] << " ";
}
cout << endl;
}
// for debug - you can remove this if not needed...
cout << "main - end, enter any key and press enter to terminate..." << endl;
char tmp;
cin >> tmp;
return 0;
}
Hope it helps.
Cheers,
Guy.
thank you everyone for your support the MAIN mistake i was doing is the use of gets(arr) and doing arr[10] as if you are using function gets(arr) you have to give one extra index which is used by this function gets(arr) i.e. arr[11]
solved :)
I'm trying to convert a for loop to while loop in c++ and do some checking for duplicates in a random number generator for generating lotto numbers so far all the stuff i'm trying seems to make the compiler very unhappy and I could really use a few pointers. It's the for loop in the Harray() function that feeds the Balls[] array
that i want to convert to a while loop.
#include<iostream>
#include<cstdlib> // to call rand and srand.
#include<ctime> // to make rand a bit more random with srand(time(0)) as first call.
#include<iomanip> // to manipulate the output with leading 0 where neccesary.
using namespace std;
// Hrand() function create and return a random number.
int Hrand()
{
int num = rand()%45+1; // make and store a random number change 45 for more or less Balls.
return num; // return the random number.
}
// Harray() function create and fill an array with random numbers and some formatting.
void Harray()
{
int Balls[6]; // change the number in Balls[6] and in the for loop for more or less nrs. a row.
for(int x=0; x<=6; x++) //the loop to fill array with random numbers.
{
int a; // made to pass the Balls[x] data into so i can format output.
int m = Hrand(); // calling the Hrand() function and passing it's value in int m.
Balls[x] = m; // throwing it into the array tought i did this because of an error.
a = Balls[x]; // throwing it into int a because of an type error.
cout<<"["<<setfill('0')<<setw(02)<<a<<"]"; //format output with leading 0 if neccesary.
}
cout<<endl; // start new row on new line.
}
// Main function do the thing if compiler swallows the junk.
int main() // start the program.
{
int h; // int to store user cchoice.
srand(time(0)); // make rand more random.
cout<<"How many rows do you want to generate?"<<endl; // ask how many rows?
cin>>h; // store user input.
for(int i=h; h>0; h--) // produce rows from user input choice.
{
Harray(); // calling Harray function into action.
}
return 0; // return zero keep the comipler happy.
}
I would like to always have six diffrent numbers in a row but i don't see how to get there with the for loops i think the while loop is way to go but am open to any suggestion that will work. I'm just starting with c++ i might have overlooked some options.
int x=0;
while(x<6)
{
int a;format output.
int m = Hrand();value in int m.
Balls[x] = m; because of an error.
a = Balls[x];
cout<<"["<<setfill('0')<<setw(02)<<a<<"]";
x++;
}
Here, I also fixed a bug. Since Balls has 6 elements, the last element will be 5. Thus you want x<6 instead of x<=6. That goes for the for loop too.
One drawback of while loops is that you cannot declare local variables with them.
First of all, you should realize that the difference between a for loop and a while loop is mostly syntactic--anything you can do with one, you can also do with the other.
In this case, given what you've stated as your desired output, what you probably really want is something like this:
std::vector<int> numbers;
std::set<int> dupe_tracker;
while (dupe_tracker.size() < 6) {
int i = Hrand();
if (dupe_tracker.insert(i).second)
numbers.push_back(i);
}
The basic idea here is that dupe_tracker keeps a copy of each number you've generated. So, you generate a number, and insert it into the set. That will fail (and return false in retval.second) if the number is already in the set. So, we only add the number to the result vector if it was not already in the set (i.e., if it's unique).
How convert for-loop to while-loop
#include <iostream>
class T545_t
{
// private data attributes
int j;
public:
int exec()
{
// A for-loop has 3 parameters, authors often fill 2 of them with magic
// numbers. (magic numbers are usually discouraged, but are expected
// in for-loops)
// Here, I create names for these 3 for-loop parameters
const int StartNum = 2;
const int EndNum = 7;
const int StrideNum = 2;
std::cout << std::endl << " ";
for (int i = StartNum; i < EndNum; i += StrideNum ) {
std::cout << i << " " << std::flush;
}
std::cout << std::flush;
// A while-loop must use / provide each of these 3 items also, but
// because of the increased code-layout flexibility (compared to
// for-loop), the use of magic numbers should be discouraged.
std::cout << std::endl << " ";
j = StartNum;
do {
if (j >= EndNum) break;
std::cout << j << " " << std::flush;
j += StrideNum;
} while(true);
std::cout << std::flush;
std::cout << std::endl << " ";
j = StartNum;
while(true) {
if (j >= EndNum) break;
std::cout << j << " " << std::flush;
j += StrideNum;
}
std::cout << std::flush;
std::cout << std::endl << " ";
j = StartNum;
while(j < EndNum) {
std::cout << j << " " << std::flush;
j += StrideNum;
}
std::cout << std::endl;
return 0;
}
}; // class T545_t
int main(int , char** )
{
T545_t t545;
return(t545.exec());
}
Ask me where 'j' is declared?
This code is marked as C++, so in this case, I have declared 'j' in the private data attribute 'section' of this class definition. That is where you'd look for it, right?
If your c++ code does not have class, what's the point?
Basically I am relearning C++ and decided to create a lotto number generator.
The code creates the ticket and if that ticket does not already exist, it is added to a vector to store every possible combination.
The program works, but its just far too slow, adding an entry roughly every second, and It will get slower as it finds it more difficult to add unique combinations out of over 13 million possible combinations.
Anyway here is my code, any optimization tips would appreciated:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> lottoCombos;
const int NUMBERS_PER_TICKET = 6;
const int NUMBERS = 49;
const int POSSIBLE_COMBOS = 13983816;
string createTicket();
void startUp();
void getAllCombinations();
int main()
{
lottoCombos.reserve(POSSIBLE_COMBOS);
cout<< "Random Ticket: "<< createTicket()<< endl;
getAllCombinations();
for (int i = 0; i < POSSIBLE_COMBOS; i++)
{
cout << endl << lottoCombos[i];
}
system("PAUSE");
return 0;
}
string createTicket()
{
srand(static_cast<unsigned int>(time(0)));
vector<int> ticket;
vector<int> numbers;
vector<int>::iterator numberIterator;
//ADD AVAILABLE NUMBERS TO VECTOR
for (int i = 0; i < NUMBERS; i++)
{
numbers.push_back(i + 1);
}
for (int j = 0; j < NUMBERS_PER_TICKET; j++)
{
int ticketNumber = rand() % numbers.size();
numberIterator = numbers.begin()+ ticketNumber;
int nm = *numberIterator;
numbers.erase(numberIterator);
ticket.push_back(nm);
}
sort(ticket.begin(), ticket.end());
string result;
ostringstream convert;
convert << ticket[0] << ", " << ticket[1] << ", " << ticket[2] << ", " << ticket[3] << ", " << ticket[4] << ", " << ticket[5];
result = convert.str();
return result;
}
void getAllCombinations()
{
int i = 0;
cout << "Max Vector Size: " << lottoCombos.max_size() << endl;
cout << "Creating Entries" << endl;
while ( i != POSSIBLE_COMBOS )
{
bool matchFound = true;
string newNumbers = createTicket();
for (int j = 0; j < lottoCombos.size(); j++)
{
if ( newNumbers == lottoCombos[j] )
{
matchFound = false;
break;
}
}
if (matchFound != false)
{
lottoCombos.push_back(createTicket());
i++;
cout << "Entries: "<< i << endl;
}
}
sort(lottoCombos.begin(), lottoCombos.end());
cout << "\nCombination generation complete!!!\n\n";
}
The reason each lottery ticket is taking a second to generate is because you are misusing srand(). By calling srand(time(0)) every time createTicket() is called, you ensure that createTicket() returns the same numbers every time it is called, until the next time the value returned by time() changes, i.e. once per second. So your reject-duplicates algorithm will almost always find a duplicate until the next second goes by. You should move your srand(time(0)) call to the top of main() instead.
That said, there are perhaps larger issues to confront here: my first question would be, is it really necessary to generate and store every possible lottery ticket? (and if so, why?) IIRC real lotteries don't do that when issuing a ticket; they just generate some random numbers and print them out (and if there are multiple winning tickets printed with the same numbers, the owners of those tickets share the prize money).
Assuming you do need to generate every possible lottery ticket for some reason, there are better ways to do it than randomly. If you've ever watched the odometer increment while driving a car, you'll get the idea for how to do it linearly; just imagine an odometer with 6 wheels, where each wheel has 49 different possible positions it can be in (rather than the traditional 10).
Finally, a vector has O(N) lookup time, and if you are doing a lookup in the vector for every value you generate, then your algorithm has O(N^2) time, which is to say, it's going to get really slow really quickly as you generate more tickets. So if you have to store all known tickets in a data structure, you should definitely use a data structure with quicker lookup times, for example a std::map or a std::unordered_set, or even a std::bitset as suggested by #RedAlert.