Reputation: 71
I'm new to C and wrote a code where I would like to display "?" on the screen where it matches the value in an array. If I have an array initialized with index_location[6] = {0, 1, 5, 8, 9, 12}; my expected output is detailed below. Any help or assistance in helping me is greatly appreciated.
Output: ??@@@?@@??@@?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//
int main(void)
{
int index_location[6] = {0, 1, 5, 8, 9, 12};
int len=sizeof(index_location)/sizeof(int);
for (int a = 0; a < len; a++)
{
for(int b = 0; b < len; b++)
{
if ( a == index_location[b])
{
printf("%c",'?');
} else {
printf("%c",'@');
}
}
}
printf("\n");
}
Upvotes: 0
Views: 41
Reputation: 1934
The error lies in your for loops. I would go with the below solution.
If the array index_location[] is sorted in ascending order, use this for loop with double initialization intead:
int max = index_location[len-1];
for(int i = 0,j = 0; i <= max; i++)
{
if ( i == index_location[j])
{
printf("%c",'?');
j++;
}
else {
printf("%c",'@');
}
}
Upvotes: 0
Reputation: 753795
You only need a single loop. You need to go through index positions 0..12 inclusive (where 12 is the last entry in the index_location
array), checking whether you need to print a ?
or @
each time. When you've printed the character corresponding to one of the index_location
entries, you need to move on to looking at the next one. You could add a liberal collection of assert()
invocations to ensure that things are under control, but as long as the array is in sorted order, you should be OK (and you might get away with it even if it's not, though you might miss some requested ?
marks).
#include <stdio.h>
int main(void)
{
int index_location[6] = {0, 1, 5, 8, 9, 12};
int len = sizeof(index_location) / sizeof(index_location[0]);
int max = index_location[len - 1];
int idx = 0;
for (int a = 0; a <= max; a++)
{
if (a < index_location[idx])
putchar('@');
else
{
putchar('?');
idx++;
}
}
putchar('\n');
return 0;
}
Output:
??@@@?@@??@@?
Upvotes: 3