C++ array issue - c++

I am new with C++, so I need your help. I wrote this program,
#include<iostream.h>
int main(){
int totalAge = 0;
int age[10];
for(int j= 1; j<10; j++){
age[j] = j;
cout << age[j] << endl;
}
for(int i = 0; i<10; i++){
totalAge = age[i];
cout << "Total Age is : " << totalAge << endl;
}
system("pause");
}
Where as the output on command prompt is this:
1 2 3 4 5 6 7 8 9
Total Age is : 1700868285
Total Age is : 1
Total Age is : 2
Total Age is : 3
Total Age is : 4
Total Age is : 5
Total Age is : 6
Total Age is : 7
Total Age is : 8
Total Age is : 9
Press any key to continue . . .
The only thing I want to know is that why is first "Total Age is : 1700868285" I believe it should be "Total Age is : 0"
Please explain it.
Thanks

Your first loop never initialized age[0]. In some languages variables are automatically set to their default value. C++ is not one of them. C++ makes no guarantees about the value of an uninitialized variable. The 1700868285 value is simply whatever happened to be in the memory used to store age[0] when interpreted as an int.
Your code should read like this. Now age[0] is set to 0.
for(int j = 0; j < 10; j++)
{
age[j] = j;
cout << age[j] << endl;
}
This is a good example of why you should be very diligent about initializing variables in C++. As pointed out below by #Caesar you could start off by declaring the array and initializing it at the same time. This adds a small overhead in that you have written zeros into the array and then update it with the values you really want but this will help avoid the issue that caught you here.
You can actually do this using std::array (as pointed out by #Ben) and std::iota from the Standard Library which will make your code simpler.
std::array<int, 10> age = { 0 }; // initialize all the values to zero.
std::iota(begin(age), end(age), 0); // Set the values of the elements to 0...9
If you want to make even more C++ like you can also consider using the new form of for syntax.
for (auto a : age)
{
totalAge = a;
cout << "Total Age is : " << totalAge << endl;
}
And consider using the std:accumulate algorithm, rather than manually calculating the sum.
int totalAge = std::accumulate(begin(age), end(age), 0);

The reason you have this issue is because you never set the value for the first element in the array age. Therefore, it is value is undefined.
An easy fix is to declare your array like this int age[10] = { 0 };, initializing all the values in the array to zero.

You never initialize age[0], becuase j is never equal to 0. So in the second loop, when i=0, totalAge is assigned the uninitialized value age[0] which contains garbage value.

Array indexing begins from zero.While inputting you have given no value to age[0] while at the time of outputting you are using age[0] which gives a garbage value.So run your first loop from 0 to 9.

In your first for loop, you assign array index 1 to 1. Array index 0 is the first, which is left unassigned to anything, which means that it can have any value (because it's uninitilized). Then, in your second for loop, you access that index, which has an uninitilized value.
I think you want to change your first for loop to look something like this:
for(int j = 0; j < 10; j++){
age[j] = j;
cout << age[j] << endl;
}
Note that the only change is that it now starts from 0.

Your first loop starts from
int j= 1;
and the first element of the array is age[0]. In the second loop you're trying to get the value of age[0] and since it was never initialized you receive this long ass address number.

Related

Local Variable being changed without manipulation

I'm creating a simple quick sort program that initializes an empty array and asks the users for inputs to determine how many elements are going to be sorted and what elements are going to be sorted.
The problem I am encountering is a local variable is being changed despite being only being referenced to once assigned. Attached below is the code.
int main()
{
int amount;
int numbersarray[] = {};
std::cout << "How many numbers do you want to sort? " << std::endl;
std::cin >> amount;
for(int i = 0; i <= amount; i++){
std::cout << "Enter number to be sorted: " << std::endl;
std::cin >> numbersarray[i];
}
std::cout <<"Amount to be sorted: " << amount << std::endl;
for(int i = 0; i <= amount; i++){
std::cout << numbersarray[i] << std::endl;
}
}
What I expect to be occurring, when I input the amount as 5, I should be able to input 5 elements into the array, instead however the Amount printed is 2 and the maximum elements I can put into the array is 3.
Below is the execution output.
How many numbers do you want to sort?
5
Enter number to be sorted:
5
Enter number to be sorted:
2
Enter number to be sorted:
5
Amount to be sorted: 2
5
2
5
I've tried messing around with the for statement but I don't think I'm doing it right as it hasn't fixed the problem, The manipulation of the for statement I'm doing is changing the condition (i.e !=, <, <=)
You have undefined behavior. Anything can happen. Local variable can change without reason, the program can crash and your computer can format itself with linux 6.9
There are many problem. The first is that your program is invalid according to the standard:
int numbersarray[] = {};
This is not valid. Array need a size:
constexpr int max_amount = 32;
int numbersarray[max_amount] = {};
If you need it to be dynamic, use vector:
std::vector<int> numbersarray;
numbersarray.resize(amount);
Second, you have another source of undefined behavior:
// Iterates too much, numbersarray[amount] is past the end
// ~~~v~~~~~~~
for(int i = 0; i <= amount; i++){
std::cout << "Enter number to be sorted: " << std::endl;
std::cin >> numbersarray[i];
}
It should be:
for(int i = 0; i < amount; i++){
std::cout << "Enter number to be sorted: " << std::endl;
std::cin >> numbersarray[i];
}
To avoid invalid code and undefined behavior, you should enable warnings.
numbersarray is a C-style array with a size of zero and doesn't adjust its size dynamically (most compilers might even fail to compile int numbersarray[] = {}; since an empty initializer isn't allowed for an array with unspecified size).
Writing or reading its elements causes undefined behaviour (which can be access violations, changing unrelated variables, and much more). This is the reason why you might see the values of local variables changing. Someone else that uses the same code could get completely different behaviour, since it is undefined.

Program not running with Array during Initialization

I'm just practicing using arrays. So my program consist of inputting numbers of data type double into the array and have them print out. Simple.
I only limited the numbers down to 4. So the array, num_List[3] is in the code. I've made sure to use the for loops properly for reading and printing out the result.
The first few times I tested the code. I realized that the 4th number in the array was in scientific notation, telling me that I forgot to initialize the array to 0, in this case 0.0, since I'm using double. So I put in this code.
for (index = 0; index <= 3; index++)
num_List[index] = 0.0;
This code should have initialized the arrays of num_List to 0.0. However, when I tested this, nothing came up, after I inputted the 4 numbers. So I made a logical error here or it's something else with the for loop that's causing it to be trapped and not continue the execution.
I've read in the books about this particular way to initialize.
#include <iostream>
using namespace std;
int main() {
double num_List[3]; // These are my variables
int index;
//double num; // Ignore these two for now, for they are to be modified later on.
//double result;
cout << "This program will summarize the numbers you've inputted print out the result. \n";
cout << "And also print out the address of the 1st and 4th address in the array." << endl;
cout << "Please enter the four numbers to be summarized.";
for (index = 0; index <= 3; index++) { // I put this in after I realized my mistake of not initializing my arrays to 0.0.
num_List[index] = 0.0;} // This is where the problem is, I think.
for (index = 0; index <= 3; index++) // This reads in the user the input
cin >> num_List[index];
cout << "The numbers you have inputted is:\n";
for (index = 0; index <= 3; index++) // This prints out the array.
cout << num_List[index] << ", " << endl;
return 0;
}
If you focus on the aforementioned code, and try to compile it, you'll see that my code unfortunately doesn't continue on from there after you input 4 numbers, regardless of whether or type a number and space it up to 4 numbers, or input a number, press the enter key for those numbers. Most likely I've made a obvious mistake, but I'm having some trouble seeing it.
I use Code Blocks, so things are a little different compared to the Bloodshed C++ compiler I used to use to practice codes on.
double num_List[3];
This declares an array with 3 elements, indexed 0 through 2.
for (index = 0; index <= 3; index++)
This loops through 4 indices, 0 through 3. When you do something with num_List[3], you get undefined behavior. In your trial, the undefined behavior fortunately resulted in just some garbage output.

Array with loop

I just started to learn programming 2 months ago and I am still newbie in it. I just learn how to write a code of arrays with loop. This was my code.
#include <iostream>
using namespace std;
int main()
{
int array[5];
for(int x=1; x<=5; x++)
{
fidan[x]=16;
cout<<x<< " --- " << array[x]<<endl;
}
return 0;
}
I know that array is count from 0. But I want my program to start with 1. So, at for loop instead of x=0, I write x=1. Then at my last x it started to being weird.
Can someone help me with it. I would appreciate it. Thank you
array[5] means an array with 5 elements. These elements are:
array[0],array[1],array[2],array[3],array[4].
Now you can declare it as array[6] and then you will have an array[5] element. Now your code should have produced a segmentation fault when accessing the array[5] element, but this is undefined behavior so who knows to whom that memory segment belongs to.
The weird characters that you get is because that memory does not belong to the array variable and probably cannot be interpreted as int. Hope that helps.
you should use one of two ways:
for (int i = 0 ; i < 5 ; i++)
cout << array[i] << " ";
or
for (int i = 1 ; i <= 5 ; i++)
cout << array[i - 1] << " ";
Your array is with 5 elements.
When x=5 in the loop, you are accessing the 6th element, so you are out of the bounds of the array.
I know that array is count from 0.
Correct.
But I want my program to start with 1.
Well, it doesn't. As you just said.
So, at for loop instead of x=0, I write x=1.
Simply don't do that.
Then at my last x it started to being weird.
Yes, because you tried to access an array element that doesn't exist.

C++: using for loop to allow user input of numbers into array

I'm new to the community and to coding as well. Right now I'm taking Intro to Computer Science at my CC and we're learning C++. Anyways, I have to create a program which asks the user for a number, which will be the size indicator of the array new_array. The program then asks the user to input the numbers one by one and afterwards, outputs them in reverse.
#include
using namespace std;
int main()
{
cout << "How many numbers?\n";
int numbers; // holds amount of numbers to be entered into array
cin >> numbers;
int new_array[numbers];
for(int counter = 0; counter < numbers; counter++)
{
cout << "Enter number " << counter << endl;
cin >> new_array[counter];
}
cout << "You entered: " << endl;
for(int i = numbers; i >= 0 ; i-- )
{
cout << new_array[i] << endl;
}
return 0;
}
I understand how to do this and for the most part, my program worked. It outputs the numbers entered in reverse just fine, but before it does so, it outputs large, strange numbers. For example, if the user enters 5 as the amount of numbers to be entered, and then enters 1, 2, 3, 4 and 6 as the 5 numbers respectively, the program outputs the number 4669476 first and then outputs the numbers in the array in reverse. Can anyone explain to me what I did wrong and how I could fix this? Thank you in advanced!
PS be gentle! I'm a newbie at this
This loop reads out of bounds:
for(int i = numbers; i >= 0 ; i-- )
{
If you follow i through in your head you will see that you output entries numbers through to 0, when in fact you should output entries numbers-1 through to 0.
An alternative patterns is:
for( int i = numbers; i--; )
Or you can use the fabled --> operator.
It would be possible to "simply" start from numbers - 1, however the loop pattern you have used would not work for an unsigned counter (because they are always >= 0). IMHO it is a good idea to use a pattern which works for all types; then you are less likely to make a mistake in future.
In your display for loop, you started from i = numbers which is out of the array's range. Since the array starts from 0 till size - 1, then you need to start from i = numbers - 1 all the way to >=0.
Because you start from array[numbers] which is not defined.
array[0], array[1], ... array[numbers-1] are defined.
In C arrays are stored from 0 instead of 1. So the last number is stored in array[4]
So when you're writing it out you should start an numbers - 1 instead of just numbers.
Because you are starting the index from out of range giving you garbage value.
your code should look some thing like this
for(int i = numbers-1; i >= 0 ; i-- )
{
cout << new_array[i] << endl;
}

c++ vector not updating in nested for loop

So I create and initialize a vector (of size nmask+3) to 0, and I assign an initial value to one of the elements. I then make a for loop that goes through the first nmask elements of the vector and assigns to each element an average of 26 other elements in the vector (defined by the 4D int array voxt, which contains vector addresses).
My problem is that when I check the values of nonzero elements in my vector (phi) within the nested loop (the first cout), the values are fine and what I expect. However, when the loop finishes going through all nmask elements (for (int i= 0; i<nmask; i++) exits), I check the nonzero elements of phi again, and they are all lost (reset to 0) except for the last non-zero element (and element tvox which is manually set to 1).
I feel that since phi is initialized outside of all the loops, there should be no resetting of values going on, and that any updated elements within the nested loop should remain updated upon exit of the loop. Any ideas as to what is going on / how to fix this? Code is below; I tried to comment in a sense of the outputs I'm getting. Thanks in advance.
vector<double> phi(nmask+3, 0); //vector with nmask+3 elements all set to 0 (nmask = 13622)
phi[tvox]= 1; //tvox is predefined address (7666)
for (int n= 0; n<1; n++)
{
vector<double> tempPhi(phi); //copy phi to tempPhi
for (int i= 0; i<nmask; i++)
{
for (int a= -1; a<=1; a++)
{
for (int b= -1; b<=1; b++)
{
for (int c= -1; c<=1; c++)
{
if (!(a==0 && b==0 && c==0))
{
//oneD26 is just (double) 1/26
phi[i]= tempPhi[i]+oneD26*tempPhi[voxt[i][1+a][1+b][1+c]];
if (phi[i]!=0)
{
//this gives expected results: 27 nonzero elements (including tvox)
cout << n << " " << i << " " << a << b << c << " " << phi[i] << endl;
}
}
}
}
}
}
phi[svox]= 0; //svox = 7681
phi[tvox]= 1;
for (int q= 0; q<nmask; q++)
{
//this gives only 2 nonzero values: phi[tvox] and phi[9642], which was the last nonzero value from 1st cout
if (phi[q]!=0)
cout << q << " " << phi[q] << endl;
}
}
Difficult to tell just what is going on, but the easiest explanation is that after phi[i] gets set to non-zero and displayed to cout, it gets set to zero again in one of the later iterations through the inner loops.
If you do some tracing and check phi[i] just before updating you'll see that you often overwrite a non-zero element with zero.
Note: I have no idea what your code does, this is pure Sherlock Holmes reasoning.. if after the loops you find only 2 non-zero elements then the only logical consequence is that after updating something to non-zero later in the loop you update it to zero.
phi[i]= tempPhi[i]+oneD26*tempPhi[voxt[i][1+a][1+b][1+c]];
The nested for-loops using a, b, and c run for a combined 9 iterations with the same value of i. Since you overwrite phi[i] to a new value every time, you only retain the value from the last iteration where a, and c are all 1. If that last iteration happens to produce zero values, then phi[i] will have lots of zeroes. Perhaps you meant to do something like phi[i] += ... instead of phi[i] = ...?
I do suggest to replace the meat of the loop with something like
const boost::irange domain(-1,2);
for (int i: boost::irange(0, nmask)) for (int a: domain) for (int b: domain) for (int c: domain)
{
if (a==0 && b==0 && c==0)
continue;
//oneD26 is just (double) 1/26
phi[i]= tempPhi[i]+oneD26*tempPhi[voxt[i][1+a][1+b][1+c]];
if (phi[i]!=0)
{
//this gives expected results: 27 nonzero elements (including tvox)
cout << n << " " << i << " " << a << b << c << " " << phi[i] << endl;
}
}
Of course, for brevity I assume both boost/range.hpp and c++0x compiler. However, with trivial macro's you can achieve the same. That is without writing/using a proper combinations algorithm (why is that not in the standard, anyway).