Storing values in an array

Hello,

I am a complete beginner and need some help on creating an array (or at least I think it is an array I want to create!)

I am getting a string of values for X.

e.g.
X = 173
X = 176
X = 169
X = 169
X = 200

What I want to do is if the value of X is identical to the value previous, want to print A.

If it is not the same as a previous value, print B.

I have been trying with if and else statements but it is identifing the preious value of X which is really getting me stuck.

Thank You.
just save the current value for comparison check for the next iteration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int main(){
    int last = 0;
    int array[] = {173,176,169,169,200};
    for (int i=0; i<sizeof(array)/sizeof(array[0]); i++){
        if (array[i] == last){
            cout << array[i] << endl;
        }
        last = array[i];
    }
}
Last edited on
closed account (3qX21hU5)
You don't need a array at all if I am understanding you right.

Basically you can do this with simple if statements. All you need to do is have 2 variables, one that stores the current value and one that stores the previous value. You then check the current value vs the previous value and print it out accordingly.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Holds the current value
string currentValue = ""

// Holds the previous value
string previousValue = ""

// Have user enter a current value before entering a loop
cin >> currentValue;

// Enter "quit" to exit loop, You can have it loop however you want
while (currentValue != "quit") {

    // Right here you are going to need to copy currentValue into previousValue
    // So we can compare them
    
    // Then right here you will need to get a new currentValue

    // Do you testing here with a simple if-else. 
}
Topic archived. No new replies allowed.