I have started studying arrays and have just started making some practice but I am having some problems with using loops to name the elements inside of a specific array.
I was trying to make this piece of code that assigned the numbers from 1 up to 12(to resemble the months of the year) to the ints inside of the array, this is what I came up with:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int array[12];
for (int i = 0; i < 12;) {
cout << "Month number " << i + 1 << endl;
array[i] = (i++);
}
return 0;
}
What I don't like about this is the fact that I had to leave the increment/decrement space inside of the for loop empty. I had initially tried making the code look something like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int array[12];
for (int i = 0; i < 12; i++) {
cout << "Month number " << i + 1 << endl;
array[i] = i++;
}
return 0;
}
But this way, even if the first element of the array came out correct, the subsequent ones didn't. I think the reason for this is that the i++ in the last statement of the loop makes the value of i increment but I couldn't find a way around it without having to add another line with i-- or doing as I did in the first code I posted.
Could anyone offer me a hand in understanding how to make it so that i can store the value of i, incremented by one, inside of that specific array element, without incrementing it for the whole loop(if it is possible)?
I know there are ways around it, just like I showed in the first code i posted, but it's something that's bugging me and so I would like to make it more visually pleasing.
Please, keep in mind that I am just a beginner :)
Thanks in advance for the answers, and sorry for the long question.
Edit: Apparently, coding like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int array[12];
for (int i = 0; i < 12; i++) {
cout << "Month number " << i + 1 << endl;
array[i] = i + 1;
}
cout << array[4] << endl;
return 0;
}
makes it so that the program works correctly and looks like I wanted, but I can't comprehend why it does :(
Edit 2: Apparently, as UnholySheep pointed out, I missed on the fact that + 1 does not modify the value of the integer, while ++ does.
Thanks to everyone that answered and explained how ++ and +1 work!
Simply do i+1 again.
for (int i = 0; i < 12; i++)
{
cout << "Month number " << i + 1 << endl;
array[i] = i + 1;
}
Now it's obvious you actually want to start at 1 and go to 12, so this seems somewhat better with less repetition:
for (int i = 1; i <= 12; i++)
{
cout << "Month number " << i << endl;
array[i-1] = i;
}
EDIT: As for your edit, the reason why this works is because i++ operator works on the particular i variable. It increments that existing i by one, making it so that the next time you access i, it will be 1 more than it was before.
Writing i+1, on the other hand, creates a completely new, temporary, variable (actually a constant). So when you write
array[i] = i+1;
you're saying that you want i to remain unchanged, but you want to create a new number, one bigger than i, and put that new number into the array.
You can even write it out longer to be completely explicit:
int newNumber = i+1;
array[i] = newNumber;
for (int i = 0; i < 12; i++) {
cout << "Month number " << i + 1 << endl;
array[i] = i+1;
}
No reason to increment i in the loop
Related
This kind of explains it all I really don't know why this is happening, can you guys help? I even made the length constant because I though that could be the problem, but it still happens so I really don't know.
So the problem is that I define length1 as 4, but then after a few times in the for loop, the value just randomly changes...
#include <iostream>
#include <string>
using namespace std;
int uppercase[26] = {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};
int lowercase[26] = {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};
string test;
int entered_text[] = {};
int length = 0;
int length1 = 0;
int main() {
cout << "Enter Text:" << endl;
getline (cin, test);
length = test.size();
length1 = 4;
cout << test<< endl;
for (int i = 0; i < length1; i++){
entered_text[i] = test[i];
}
cout << entered_text[0] << endl;
return 0;
}
By looking at your code, it seems you're approaching this problem as if you were coding in JavaScript and using objects. Obviously, C++ does not approach objects the same way as JavaScript (nowhere near the same).
Here is a rough example of what you could do instead. I don't understand what you're trying to do, but I believe you can implement dynamic arrays and pointers to tackle the problem you have. Read up on using C++ pointers and C++ dynamic arrays. Here is some "rough" code that will hopefully get you on your way:
int main() {
cout << "Enter Text:" << endl;
getline (cin, test);
cout << test<< endl;
length = test.size();
// Create dynamic array and have this array the size of your string.
// Also, initialize a pointer to point to the address of your new array
int *enteredText;
enteredText = new char [length];
int *save = enteredText;
// Iterate over the array “entered_text” and assign it values
for (int i = 0; i < length; i++){
*entered_text = test[i];
entered_text++;
}
// now print chars
for (int i = 0; i < length; i++){
cout << *save << endl;
save++;
}
return 0;
don't make every variable you use global, its better to keep them local if there's no strong reason to do otherwise, and in c++ you have to tell your compiler the size of your array, or use allocation, but I would suggest to use std::vector<int>
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.
so i wrote this code in c++ to solve this equation (x+y+z=30) where each of these variables has a limited amount of possible of values (1,3,5,7,9,11,13,15) so repetition is allowed and here's my code :
#include <iostream>
using namespace std;
int main()
{
int x[8]={1,3,5,7,9,11,13,15};
int y[8]={1,3,5,7,9,11,13,15};
int z[8]={1,3,5,7,9,11,13,15};
for (int i=0; i<8; i++)
{
for (int j=0; j<8; j++)
{
for (int k=0; k<8; j++)
{
if (x[i]+y[j]+z[k]==30)
{
cout << x[i] << "\n" << y[j] << "\n" << z[k]<< "\n"<< endl;
break;
}
}
}
}
}
now i don't know if this is the right way to approach it (I'm a beginner) but still this program did okay since it gave set of three number that did equal to 30 but it didn't stick to the possible values e.g (7,22,1), now that what you see their is the best i could come up with other attempts or fixes just made things worse e.g crashing or what so ever.
if you could help that would be great and most importantly tell me where i went wrong as this whole purpose of this is to learn not solve the problem.
thank you so much in advance !
You are using break statement which only breaks one of the loops. You have nested loops in your program, so i would recommend you to use goto: instead.
for (int i=0; i<8; i++)
{
for (int j=0; j<8; j++)
{
for (int k=0; k<8; j++)<----- it should be k++
{
if (x[i]+y[j]+z[k]==30)
{
goto stop;
}
}
}
}
stop:
cout << x[i] << "\n" << y[j] << "\n" << z[k]<< "\n"<< endl;
I actually ran the code and there is 2 more problems:
As mentioned on the answer below, it 3 odd numbers never add up to 30;
variables i , j and k need to be global variables. So initialize them before using in loops. Then it should work perfectly(if the number isn't even).
I don't see 22 in the values you initialized the arrays with. You also can just use one array with the possible values; 3 arrays are not needed.
I see that you only have odd integers as possible values. 3 odd integers can never sum up to an even integer like 30, so there is no solution to your problem as stated. The one solution you provided has 22 as one value, an even integer.
I am trying to output the values present in the array, that are accepted during runtime, onto the console. But when I run this program I get the 5 values in the array as the last value only.
For example: if i give 0 1 2 3 4 as the five values for this program then the output is shown as 4 4 4 4 4.
#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
int arrsize = 5;
int *ptr = new int[arrsize];
*ptr = 7;
cout << *ptr << endl;
cout << "enter 5 values:";
for (int i = 0; i < arrsize; i++)
{
cin >> *ptr;
cin.get();
}
cout << "the values in the array are:\n ";
for (int i = 0; i < arrsize; i++)
{
cout << *ptr << " ";
}
delete[] ptr;
cin.get();
return 0;
}
Both of your loops:
for (int i = 0; i < arrsize; i++)
...
loop over a variable i that is never used inside the loop. You are always using *ptr which refers always to the first element of the dynamically allocated array. You should use ptr[i] instead.
A part from that, dynamic allocation is an advanced topic. I'd recommend sticking with simpler and more commonly used things first:
std::cout << "Enter values:";
std::vector<int> array(std::istream_iterator<int>(std::cin), {});
std::cout << "\nThe values in the array are:\n";
std::copy(begin(array), end(array), std::ostream_iterator<int>(std::cout, " "));
Live demo
Following issues I think you could tackle:
The first include can be omitted I think. Your code works without that.
You use cin.get(), not sure why you need that. I think you can remove that. Even the one at the very end. You could put a cout << endl for the last newline. I am using Linux.
And use ptr like an array with index: ptr[i] in the loops as mentioned in the other answer. ptr[i] is equivalent to *(ptr+i). You have to offset it, otherwise you're overwriting the same value (that is why you get that result), because ptr points to the first element of the array.
P.S.: It seems that if you're using Windows (or other systems) you need the cin.get() to avoid the console to close down or so. So maybe you'd need to check it. See comments below.
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.