Home > Software design >  Can I replace my Nested if loop with something more efficient?
Can I replace my Nested if loop with something more efficient?

Time:01-11

I try to figure out how many 1, 2, 3, 4 and 5 there is by using a for loop and if else statement. My question is: is there a more efficient way of writing it?

int A[15] = {1,5,4,1,3,1,3,4,5,2,3,2,5,3,2};
int B[5] = {};

for (int i = 0; i <= 14; i  )
{
    if (A[i] == 1)
    {
        B[0]  ;
    }
    else if (A[i] == 2)
    {
        B[1]  ;
    }
    else if (A[i] == 3)
    {
        B[2]  ;
    }
    else if (A[i] == 4)
    {
        B[3]  ;
    }
    else if (A[i] == 5)
    {
        B[4]  ;
    }
}

CodePudding user response:

Provided that the elements of array A are greater than 0:

#include <stdio.h>

int main()
{
    int A[15] = { 1, 5, 4, 1, 3, 1, 3, 4, 5, 2, 3, 2, 5, 3, 2 };
    int B[5] = { 0, 0, 0, 0, 0 };
    
    for (int i = 0 ; i < sizeof(A)/sizeof(A[0]) ; i  )
           B[A[i] - 1];
    
    for (int i = 0 ; i < sizeof(B)/sizeof(B[0]) ; i  )
        printf("%d ", B[i]);
        
    return 0;
}

This code produces the following output:

3 3 4 2 3

CodePudding user response:

int[] a = {1, 5, 4,...};
int[] b = new int[5];
for (int n: a) {
    assert 1 <= n && n <= 5;
    b[n - 1]  ;
}

n will be set to every element of a.

Array elements are initialized with 0, 0.0, false, null, that is the default value of the type.

You used square brackets in a C/C compatible syntax. Normally the more logical notation above is used: part of the type.

Variable and function names start with a small letter by convention, and names are in camelCase.

int[] studentScores =

Asserts one rarely sees: my bad conscience for the assumption no value is out of range.

  •  Tags:  
  • Related