Reputation: 37
I need to find a way to shorten my if-else statements with switch. The if-else statements are really long and they look really unprofessional and I hope there is a way to shorten them into a couple of lines instead of the mess of multiple lines as I have it now.
I tried to implement a switch block but it didn't go correctly and the way I wanted it to go.
int numbers(int tal[]) {
int choice,a;
printf("\nWrite a specific number: ");
scanf("%d", &choice);
int b = 0;
for(a = 0 ;a < MAX ;a++){
if(tal[a]== choice){
b = 1;
printf("\nExists in the sequence on this location: ");
if(a <= 9)
printf(" Row 1 och column %d\n",a +1);
else if (a > 9 &&a <= 19)
printf(" Row 2 och column %d\n", (a +1) - 10);
else if (a > 19 &&a <= 29)
printf(" Row 3 och column %d\n", (a +1) - 20);
else if (a > 29 &&a <= 39)
printf(" Row 4 och column %d\n", (a +1) - 30);
else if (a > 39 &&a <= 49)
printf(" Row 5 och column %d\n", (a +1) - 40);
else if (a > 49 &&a <= 59)
printf(" Row 6 och column %d\n", (a +1) - 50);
else if (a > 59 &&a <= 69)
printf(" Row 7 och column %d\n", (a +1) - 60);
else if (a > 69 &&a <= 79)
printf(" Row 8 och column %d\n", (a +1) - 70);
else if (a > 79 &&a <= 89)
printf(" Row 9 och column %d\n", (a +1) - 80);
else if (a > 89 &&a <= 99)
printf(" Row 10 och column %d\n", (a +1) - 90);
break;
}
}
if (b == 0)
printf("\n%d It does not exists in the sequence", choice);
}
I got it working, and I changed all the if-else statements to this one; edit: nvm the column answer I get is incorrect.
int choice,a,row,col;
printf("\nWrite a specific number: ");
scanf("%d", &choice);
int b = 0;
for(a = 0 ;a < MAX ;a++){
if(tal[a]== choice){
b = 1;
printf("\nExists in the sequence on this location: ");
if(a <= 9)
col = a % 10 + 1;
row = a / 10 + 1;
printf("Row %d och column %d\n", row, col);
break;
}
}
if (b == 0)
printf("\n%d It does not exists in the sequence", choice);
Upvotes: 1
Views: 100
Reputation: 18410
You can make it look a bit better by:
>
like that:
if(a <= 9)
printf(" Row 1 och column %d\n",a +1);
else if (a <= 19)
printf(" Row 2 och column %d\n", (a +1) - 10);
else if (a <= 29)
printf(" Row 3 och column %d\n", (a +1) - 20);
...
But in this case you can completely avoid the if-block by calculating the values, for example like that:
col = a % 10 + 1;
row = a / 10 + 1;
print("Row %d och column %d\n", row, col);
Upvotes: 7