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.
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 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
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
I am trying to use a function to sort through a char array full of words. The current issue I am having is that in my sortNames function I am getting the error, "expression must be a modifiable lvalue" at the part below
hold = nameArr[ii];
nameArr[ii] = nameArr[jj];
nameArr[jj] = hold;
I am guessing that its because I am trying to pass values through an array for some reason. I am struggling with understanding references and pointers and the such, and I imagine that is hurting me here as well. Any help with this would be fantastic, thank you in advance.
Here is my current code...
#include <iostream>
#include <string>
using namespace std;
char nameArr[20][15]; // array to store the 20 values
int val = 0; // variable to pass values to the array
int x = 0; // loop counter outside functions
//Function prototypes
void getNames(char (&nameArr)[20][15], int &val);
void sortNames( char(&nameArr)[20][15]);
//getNames Function
void getNames(char (&nameArr)[20][15], int &val)
{
int i = 0; // loop counter
cout << "Awesome, now lets input those names...\n" << endl;
for (i = 0; i < val; i++)
{
cout << "\nNAME " << i+1 << ": " << ' ';
cin >> nameArr[i];
}
cout << "\n\n\nThese are the names that you inserted:\n" << endl;
for (i = 0; i < val; i++)
{
cout << nameArr[i] << "\n" << endl;
}
}
// sortNames function
void sortNames( char(&nameArr)[20][15])
{
int n = 15; // max length of word
int ii = 0; // loop counter
int jj = 0; // other counter
string hold; // holding array
for (int ii = 0 ; ii < n ; ii++)
{
for (int jj = ii + 1; jj < n; jj++)
{
if (nameArr[ii] > nameArr[jj])
{
hold = nameArr[ii];
nameArr[ii] = nameArr[jj];
nameArr[jj] = hold;
}
}
}
}
int main()
{
cout << "NAME SORTER!\n\nPlease enter in the amount of names you wish to enter: " << ' ';
cin >> val;
getNames(nameArr, val);
cout << "\n\n\nAlright, lets sort now..." << endl;
sortNames(nameArr);
cout << "\nHere are the results:\n" << endl;
for (x = 0; x < val; x++)
{
cout << nameArr[x] << "\n" << endl;
}
system("pause");
}
Your main problem here is that you are trying to use an assignment operator on two fixed sized arrays, which isn't legal. Consider the following code:
int a[2] = {0, 0};
int b[2] = {1, 1};
a = b;
This gives the same error you are getting. On the lines you mentioned, you are doing the same thing with char[15] arrays.
To fix your problems, you either need to allocate your char array dynamically/work with the pointers, or a simpler solution would be to just change your char[][] array to a string[] array.
That being said, there are a lot of things you can clean up here:
You have a few variables declared globally that can just be defined in main or lower
You can declare loop counters inside the for loop instead of beforehand, as you do in the sortNames function
In sortNames you are declaring a few variables twice
I'll add a few things to dwcanilla's answer.
You will want to change your function prototypes and headers to something more like this:
void getNames(char ** & arr, int val);
void sortNames(char ** & arr);
What this means is that the function accepts a reference to an array of c-strings; that is, when you work with the array within the function you are modifying the actual array you passed and not just a copy. Also I think you'd be fine just passing the integer by value for getNames.
Second, global variables are generally a bad idea. Since you can pass the array reference directly to your functions you may want to declare nameArr and your other global variables inside main instead.
Third, in getNames you won't be able to use cin to assign your c-strings directly.
EDIT: This is a better way --
getting console input for Cstrings
Finally, the < operator doesn't work on c-strings the way you're using it in your sort function. Use strcmp() instead (and be sure to include the cstring header):
if(strcmp(arr[ii], arr[jj]) > 0)
I am writing this program in c++ and unable to determine what am I doing wrong. This nested loop is supposed to print a matrix with rows and columns and for some reason its stuck at row 0 and column 0 when asking for user input. Thanks in advance.
#include <iostream>
using namespace std;
int main ()
{
//program to print the input values in rows and columns of two dimensional array in revserse roder using loop
//decalre the vraibles and array
int array [3][3],rows,cols,maxrows = 3,maxcols = 3;
//use for loop to intiiate the array and input values from users
for (rows = 0; rows < maxrows;rows = rows++ )
{
for (cols = 0; cols < maxcols;cols = cols++ )
{
cout << " Enter the value for array location : " << " [ " << rows << " , " << cols << " ] " ;
cin >> array [rows][cols] ;
}
}
//display the values entered in array starting with bottom row first and then the rest
for ( rows = 0 ; rows < maxrows ; rows ++ )
{
for ( cols = 0 ; cols < maxcols ; cols ++ )
{
cout << " The values that were entered in this array starting with bottom row are " << array [rows][cols] ;
}
}
}
You already have your answer, but I thought I should point out that the style of variable declaration. Namely, int array [3][3],rows,cols,maxrows = 3,maxcols = 3;
This is bad because it is not very readable. The type of the row and column variables are incorrect in the strictest sense, see why size_t is better when using it as an array index. Additionally, a case could be made for why you should favour pre-increment instead of post-incrementing unless you have a good reason not to (++i instead of i++), although in this particular case it does not matter since the operator is not overloaded. Furthermore, using constants appropriately makes code more readable and eliminates certain types of bugs. Lastly, give your variables a sensible value as soon as possible to eliminate undefined behaviour.
#include <iostream>
using namespace std;
int main ()
{
//program to print the input values in rows and columns of two dimensional array in revserse roder using loop
//decalre the vraibles and array
int array [3][3] = {};
const size_t maxrows = 3,
const size_t maxcols = 3;
//use for loop to intiiate the array and input values from users
for (size_t rows = 0; rows < maxrows; ++rows )
{
for (size_t cols = 0; cols < maxcols; ++cols )
{
cout << " Enter the value for array location : " << " [ " << rows << " , " << cols << " ] " ;
cin >> array [rows][cols] ;
}
}
//display the values entered in array starting with bottom row first and then the rest
for ( size_t rows = 0; rows < maxrows ; ++rows)
{
for ( size_t cols = 0; cols < maxcols ; ++cols)
{
cout << " The values that were entered in this array starting with bottom row are " << array [rows][cols] ;
}
}
}
The comments hinted at the problem, but did not state it explicitly: the statement
rows = rows++
is ambiguous because the right-side is incremented after fetching the value which is then assigned to the left-side. With suitable warnings enabled for g++, it says
foo.c:26: warning: operation on ‘rows’ may be undefined
In effect, it says that some compilers may give differing results, such as making it no different from
rows = rows
If it did that, it would cause an infinite loop. (With g++, by the way, the value does get incremented).