user3268216
user3268216

Reputation: 71

Printing certain arrays

im trying to print and count a certain array from my table. i want to print 'O' and count how many times it pops up. The counting part i got it but to print the 'O' in a table format i cant. Everytime i would try to print the 'O' it gives me happy faces.

char poste[]={'A','P','A','P','A','O','P','P','O'};
for(i=0;i<9;i++)
{
    if(poste[i]=='O') count++;
}

printf("Number of operators :%d\n", count);
printf("Poste\n");

for(i=0; i<9;i++)
{
    printf("%c",poste[i]=='O');
}

Execution gives me these happy faces

Poste   
A       
P       
A      
P      
A      
O       
P      
P       
O      
number of operators :2
Poste
☺  ☺

Upvotes: 0

Views: 53

Answers (4)

McLovin
McLovin

Reputation: 3674

You are printing the result of the expression poste[i]=='O'.
Replace printf("%c",poste[i]=='O');
with if (poste[i] == 'O') printf("O");

Upvotes: 0

Kninnug
Kninnug

Reputation: 8073

printf("%c",poste[i]=='O');

Here poste[i] == 'O', this evaluates to either 1 (true, poste[i] is equal to 'O') or 0 (false, it isn't equal).

This result is of type int, but you're telling printf it is a char. Since ints and chars are not the same type and not equal in size this leads to weird and undefined behaviour. In this case the computer starts grinning like a madman.

If you want to print 1 or 0 to indicate equality change %c to %i (or %d). If you want to print an 'O' everytime it is equal then change it to

if(poste[i] == 'O'){
    printf("%c", poste[i]);
}

note that, by then you might as well just print

printf("O");

since you know it will only print 'O's

Upvotes: 0

Damien Black
Damien Black

Reputation: 5647

Your line printf("%c",poste[i]=='O') is printing a character. Which character? Well, poste[i]=='O' is a condition. Conditions return true or false. When those values get converted into a character, they will first be converted to an int, 1 or 0, and then a char, '☺' (which is the character with ascii value of 1) or 'null'.

What you want is to check the condition with an if statement and then printf the actual character:

if ( poste[i] == 'O' ) {
    printf ( "%c", poste[i] );
}

Upvotes: 0

unxnut
unxnut

Reputation: 8839

You are printing poste[i]=='O'. What you want to do is as follows:

for ( i = 0; i < 9; i++ )
    if ( poste[i] == 'O' )
        printf ( "%c", poste[i] );

Upvotes: 2

Related Questions