Home > Software design >  Can't add numbers to an existing index in an array
Can't add numbers to an existing index in an array

Time:10-17

I'm new to C and can't understand what is wrong here. This code was made for problem 339A from CodeForces.

I get an unsorted sum str input with numbers from 1-3 (Ex. 1 2 3 2 1).

I'm trying to find the total ocurrences of every number, but when trying to sum to an index of the array, it just overflows or gives me an unrelated number.

Why is this so?

Example

Input: 1 2 3 2 1
Output of array: [0, -13008, 5]

I have the following code:

#include <iostream>
using namespace std;

int main(){

    string s;
    int arr[3];

    cin >> s;

    for(int i=0; i<s.size(); i = 2){
        if(s[i] == 1){
            arr[0]  = 1;
        }
        else if(s[i] == 2){
            arr[1]  = 1;
        }
        else{
            arr[2]  = 1;
        }
    }
    ...

CodePudding user response:

For starters you need to initialize the array

int arr[3] = {};

And you need to compare characters like for example

if(s[i] == '1'){

If you are sure that s[i] contains only characters '1'-'3' then instead of the if statements you could write for example

  arr[s[i] - '1'];

or you could use only one if statement

if ( '1' <= s[i] && s[i] <= '3' )
{
      arr[s[i] - '1'];
}
  • Related