I am new to programming, my starting language is c++ right now. I'm having trouble printing some arrays in a reverse order. After looping and incrementing a the variable each incrementing inputs a value.
#include <iostream>
using namespace std;
int main(){
int x=0;
int a=0;
int y=0;
int arrayOne[40];
int numberofTimes;
int decrement;
int operatorx;
cout<<"Enter first number: ";
cin>>numberofTimes;
for(int x; x<numberofTimes;x++){
cout<<"Enter second number: ";
cin>>y;
arrayOne[x]=y;}
decrement=numberofTimes*2;
while(decrement>numberofTimes){
cout<<arrayOne[x]<<endl;
x=x-1;
decrement=decrement-1;
}
return 0;}
Actually, your code has only two real errors (but lots of 'dodgy' stuff), The following is a corrected/annotated: working version:
#include <iostream>
using namespace std;
int main()
{
int x;// = 0; // It is better to initialize this at the start of the FOR loop!
// int a = 0; // You never use this variable!
int y = 0;
int arrayOne[40];
int numberofTimes;
// int decrement; // Better to declare and initialize this in one go (below)
// int operatorx; // This is never used!
cout << "Enter first number: ";
cin >> numberofTimes;
// for (int x; x < numberofTimes; x++) { // Here, you create a new variable, 'x' that hides the one you
for (x = 0; x < numberofTimes; x++) { // have already defined; instead, use this to initialise x to zero
cout << "Enter second number: ";
cin >> y;
arrayOne[x] = y;
}
int decrement = numberofTimes * 2; // Declare and initialise when needed!
while (decrement > numberofTimes) {
x = x - 1; // At the end of the first (FOR) loop, x will point to BEYOND the end of the array ...
cout << arrayOne[x] << endl; // ... so you need to decrement it BEFORE accessing the elements!
// x = x - 1;
decrement = decrement - 1;
}
return 0;
}
Feel free to ask for further explanations!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.