I am trying to complete a C++ exercise in which an array is displayed and the user is prompted to input a multiplier, which will result in the initial numbers that were displayed being multiplied by the user's input. Here is the code that I have so far:
#include <iostream>
using namespace std;
int main()
{
int array[5] = { 1, 2, 3, 4, 5 };
for (const auto& a : array)
{
std::cout << a << std::endl;
}
double multiplier;
cout << "Input a multiplier: ";
cin >> multiplier;
for (int array = 1; array <= 5; ++array)
{
array == multiplier * array;
std::cout << array << std::endl;
}
}
When it runs, it prints the correct array, with a newline being created after each array value, and prompts the user for the multiplier. However, when the multiplier is inputted, the values do not change. Here is an example output:
1
2
3
4
5
Input a multiplier: 2
1
2
3
4
5
The goal is to get this output:
1
2
3
4
5
Input a multiplier: 2
2
4
6
8
10
Any help or code improvement would be appreciated, as figuring out how to multiply and display the multiplied values is the only thing needed to be done in order to complete the exercise. Thank you in advance!
There are three big issues with your code:
1. Naming conventions.
Do not name your array and your temporary for loop variable the same thing. This will cause an issue further down the line, which I'll illustrate.
2. Incorrect operator
As minterm has mentioned, you are using a comparison operator instead of the equal operator. But that alone will not fix your issue.
3. Not accessing array values
You are not actually multiplying the array values with the multiplier. You have to access the elements, which means you cannot start the index at 1.
for (int i = 0; i < 5; i++){
array[i] *= multiplier
cout << array[i] << endl;
}
Use = instead of ==. Currently, it just evaluates a logical statement instead of setting it to a new value.
Also, you need to change "int array" in the for loop to a different name so as to not get it confused with the array called array. Call the variable in the for loop something else, like "int i".
So then the line in question would not be "array == multiplier*array", but instead something like "int j = multiplier * array[i]", and then have it print out j instead of array.
A simpler approach would be to use another range-based for loop instead of the indexed version:
for (auto& a : array)
{
a *= multiplier;
std::cout << a << std::endl;
}
If you don't need to update the array itself (after all, your code doesn't actually read from the array again), then you a very similar, though more straightforward version might be applicable:
for (const auto& a : array)
{
std::cout << a * multiplier << std::endl;
}
You have quite a few things going on that are incorrect.
First is your over scoping (maybe not the right term) the array value.
You have an array value declared outside of your for loop, and you're using the value array again inside of the for loop for the counter. So you're not actually doing anything to your array. You're actually trying to do something to the initialization variable.
Second you're using == instead of =
You're using a comparison operator (==) instead of an assignment operator (=), but there's other big no no's going on.
array is an int[5] not just an int
To actually modify each element of your array, you need to reference the index by saying array[index] where index is a value of 0 to length of array - 1, so 4 in your case.
You're using a double multiplier and trying to apply it to an int *
If you try to multiply by a double value like 2.5, your array values are going to be int's and not a number with a decimal value. You should make your int array [] into a double array []
Not accessing your array, starting from index 0
When looping through an array, the first index is always 0. You're using array = 1 and array <= 5. This would skip your first index, and give you an out of bound index at the end. You should use int index = 0; index < 5; index++; instead.
You're trying to print array
Since array is an int [] printing array in the for loop like that will just give you the address of where the array is. You'll have to either print out each index or use the enhanced for loop method after you've applied your multiplier.
If you're wanting to use your above implementation, do this
for (int index = 0; index < 5; index++)
{
array[index] *= multiplier; // Or you can use array[index] = multiplier * array[index]
std::cout << array[index] << std::endl;
}
Related
So here's a simple program that just search for two numbers in an array that sum up to a certain value k
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_set<int> hashtable;
int k =7;
int arr[5] = {1, 2, 3, 4, 5};
int s = sizeof(arr);
for (int i =0; i<s; i++){
if( hashtable.find(k - arr[i])!= hashtable.end() )
{
cout << arr[i] << endl;
cout<< "found one " << arr[i] << " and "<< k-arr[i]<< endl;
} else {
hashtable.insert(arr[i]);
}
}
return 0;
}
And here's the out put, I am getting
4
found one 4 and 3
5
found one 5 and 2
7
found one 7 and 0
7
found one 7 and 0
Am I missing something?
You access the array outside of its bounds. The behaviour of the program is undefined.
sizeof does not yield the number of elements in an array. It yields the size of an object in bytes. When the size of the element is more than one byte - and int is more than one byte on most systems - then the number of bytes in the array is more than the number of elements.
A correct way to get the number of elements in an array is to use std::size:
int s = std::size(arr);
Since you use only arr[i] and not i itself, you can write for (auto a : arr). This will respect the array bounds, you don't need to calculate the maximum index. Hence, it avoids the wrong calculation (which the other answers fix)
Maybe there are other ways to get the size of an array but for now this will do :
int s = sizeof(arr)/sizeof(arr[0]);
Trying to fill an array using a pointer so each index of array contains its' index. The output I am currently getting is this +DD;D;DD. Could someone explain where I am going wrong on this? Thanks.
#include <iostream>
using namespace std;
int main()
{
int NUMBER_ELEMENTS;
cout << "Enter number of elements: ";
cin >> NUMBER_ELEMENTS;
short array1[NUMBER_ELEMENTS];
short *arrPtr;
arrPtr = array1;
short i = 0;
while(i < NUMBER_ELEMENTS)
{
*arrPtr = i;
arrPtr = arrPtr + 1;
cout << "+" + array1[i];
i++;
}
}
Problem 1: The length of an automatic array can not be given at runtime. It must be known at compile time. In order to create an array with dynamic length, you can use std::vector instead.
explain how this is a variable length array?
You can input different values in different executions of the program. Therefore the length varies. Even the value staying the same is by itself not sufficient. The expression used the array length must be a compile time constant expression.
Problem 2: "+" + array1[i] doesn't do what you probably think it does.
The string literal is an array of characters. array1[i] is an integer. When you add an integer to an array using the plus-operator, the array decays to a pointer to first element of the array, and the the pointer is incremented by number given as the operand.
Therefore "+" + 0 increments the pointer by zero places, so the string printed in the first iteration is "+". "+" + 1 increments the pointer by one places. After the + character, there is only the null terminator, so the printed string is empty. After that iteration, the later iterations overflow the array, and the behaviour of the program is undefined.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a[5];
for (int i = -1; i < 7; i++)
cout << i << " " << setw(2) << a[i] << endl;
}
So I'm trying to figure out why this won't work. If i take out a[i] it works, but if i leave it in, the for loop goes from -2 until the 1000's which is obviously not right. Is it because a[i] is not bound to the parameters of the for loop (i < 7)? I'm not really sure I understand.
EDIT As many of you have explained it was a matter of uninitializing the array and using bounds outside of the array (e.g -2). It was not something I thought of, nor found when searching for why this was happening.
First, as marcadian pointed out, the array a is not initialized, so values in the array are completely random.
Also, the size of the a array is 5, meaning that you can access between indexes 0 and 4 inclusive.
However, in your loop, you try to access at index -1, and index 6. Attempting to write and read at invalid indexes ( such as -1 and 6, in this case ) is undefinded behavior ( it can crash with a segmentation fault, or corrupt other variables, which can make debugging process very hard ... )
A way to avoid buffer overrun like you did is to use std::array STL container, like this :
std::array<int, 5> a;
//Access elements using the method 'at()', it has bound checking
a.at(0); // 0 is a valid index
//a.at(-1); // -1 is not a valid index, it will crash ( at least in debug mode )
//a.at(6); // 6 is also not a valid index
The std::array STL container does the same things normal array does, but provides useful methods
You're printing out random value in memory because variable a is not initialized. Uninitialized variable has random value in memory. What are you trying to do?
in computers an array is really just a given number of values, starting at array[0], and ending at array[n].
int a[5]; statically allocates space for 5 integers on the stack, starting at a[0], and ending at a[4].
Try this iteration instead:
for (int i = 0; i < 4; i++)
In addition to not initializing the array, a, the indices you would be using to access its elements are out of bounds. C++ uses zero-indexing - you could try, for instance:
int main() {
int a[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
cout << i << " " << a[i] << endl;
}
}
Output would be:
0 1
1 2
2 3
3 4
4 5
I was making a three dimensional array in c++ and I get hexadecimal numbers
#include <iostream>
using namespace std;
int main(){
int arer[2][3][3] = {{{1,2,3}, {4,5,6}, {7,8,9}}, {{10,11,12}, {13,14,15} ,{16,17,18}}};
for(int x = 0;x <= 18;x++){
cout << arer[x] << " ";
}
return 0;
}
I used to get an output like
0xbebd5ea4
and more like these
This the right way to print a 3D array:
int main(){
int arer[2][3][3] = {{{1,2,3}, {4,5,6}, {7,8,9}}, {{10,11,12}, {13,14,15} ,{16,17,18}}};
for(int i = 0;i < 2;i++){
for(int j = 0;j < 3;j++){
for(int k = 0;k < 3;k++){
std::cout << arer[i][j][k] << " ";
}
}
}
return 0;
}
What you are doing is printing the addresses of some memory.
arer is a 3-dimensional array (an array of 2-dimensional arrays). arer[x] is a 3x3 array of int. An array, when passed to any function as an argument (which includes stream's operator<<()) is converted to a pointer (to the first element). If passing a 3x3 array, a pointer to an array of 3 elements is passed.
Since one variant of ostreams operator<<() accepts a void *, most pointers will be implicitly converted to void * and passed to that version. That is what is happening here. A void * represents an address in memory. By convention, addresses are often printed in a hexadecimal form.
Also, in your example, arer[x] is only valid if x is 0 or 1 (valid values of the first index). Other values (up to 18 inclusive in your loop) are not valid elements of arer - so accessing them gives undefined behaviour.
I am trying to loop through the array and get the elements inside in C++. Here is my code:
int result;
int index_array [] = {11,12,13,14,15,16,17,18,19,20};
for (int count =0; count < index_array.length() ; count++){
if(count%2 == 0){
cout << "Elements at the even index are " << index_array[count] << endl;
}
}
If I change the for loop to:
for (int count =0; count < 10 ; count++){
There is no error because my array only consists of 10 items. But if I used the .length() method, there is an error which is expression must have a class type. I have no idea what is it, as in if it is in Eclipse, there contains a more detailed error description. What might be wrong?
Updated answer
for (int count =0; count < sizeof(index_array)/sizeof(index_array [0]) ; count++){
if((count+1)%2 == 0){
cout << "Elements at the even index are " << index_array[count] << endl;
}
}
You can't call length() on int index_array[], it is a primitive array, not an object.
You could call size(), if you have, for example vector<int> index_array.
There is not .length for a plain array in C++.
Instead use std::vector and you can use method size() :
std::vector<int> index_array {11,12,13,14,15,16,17,18,19,20};
for (int count =0; count < index_array.size() ; count++){
if(count%2 == 0){
cout << "Elements at the even index are " << index_array[count] << endl;
}
}
Also in your case, you can calculate the length of the array:
int length = sizeof(index_array)/sizeof(index_array[0]);
int index_array [] = {11,12,13,14,15,16,17,18,19,20};
This is not an object that you can invoke some length() method on. Instead, it's a regular array, just like in C.
You can do one of two things.
The first is to use one of the C++ collection classes such as std::vector (adjustable size) or std::array (constant size) with their size() methods:
// C++11 syntax
std::vector<int> index_array {11,12,13,14,15,16,17,18,19,20};
// Pre C++11 syntax
int ia_src[] = {11,12,13,14,15,16,17,18,19,20};
vector<int> index_array (ia_src, ia_src + sizeof (ia_src) / sizeof (*ia_src));
std::array<int,10> index_array = {11,12,13,14,15,16,17,18,19,20};
The second is to simply treat the array as an array, in which case the length of that array can be found with the expression:
sizeof (index_array) / sizeof (*index_array)
Just be aware that this only works for arrays. If you pass that array to a function, it will decay to a pointer to the first element and sizeof will no longer work as you expect. You need to get the size while it's still an array and pass that along with it.
Arrays in c++ are not object (classes) so they don't have neither methods nor attributes.
May be you can use the Array class instead and get the size like std::array::size()