Reputation: 23
#include <stdio.h>
int num, i, k, a[5];
int main() {
a[0]=2;
a[1]=11;
a[2]=12;
a[3]=16;
a[4]=28;
num=a[1+3]
i=4;
while(num>0){
a[i]=num%4;
num=num/3;
printf("%d ",num);
i--;
}
printf("8\n");
for(k=0;k<5;k++){
printf("%c ",65+a[k]);
}
printf("\n);
}
The output of this program is:
9 3 1 0 8
C B D B A
I understand completely how the output for the first line is but am rather confused about the 2nd part.
for(k=0;k<5;k++){
printf("%c ",65+a[k]);
This bit here confused me as the loop the first time from my understanding should go k=0 then print %c which comes from 65+a[k] which k is currently 0 so 65+a[0]. From the earlier part of the where its setting we see a[0]=2 and 65+2 is 67 which is the character "C". which is correct on the output but if I follow this same logic for the 2nd loop 65+a[k] where k=1 so 65+a[1] and a[1] is 11 and 65+11 is 76 that would equal the character "K" but that's wrong as it should be the character "B".
I feel that this line of code is where im missing something:
a[i]=num%4
but it doesn't actually set a number so still confused.
Any help is appreciated
Upvotes: 2
Views: 62
Reputation: 4023
a[i]=num%4
does set the number. This is how:
In your loop:
while(num>0){
a[i]=num%4;
num=num/3;
printf("%d ",num);
i--;
}
num
varies as in the first line of output.
a[i]=num%4;
actually sets the values in the array as follows:
Initially, i=4
and num=28
. Therefore,
a[i]=num%4;
sets a[4]
as 28%4=0
. Therefore, your last character is A+0=A
.
Then i=3
, and num=9
. Therefore,
a[i]=num%4;
sets a[3]
as 9%4=1
. Therefore, your second last character is A+1=B
.
Then i=2
, and num=3
. Therefore,
a[i]=num%4;
sets a[2]
as 3%4=3
. Therefore, your third last character is A+3=D
.
Then i=1
, and num=1
. Therefore,
a[i]=num%4;
sets a[1]
as 1%4=1
. Therefore, your fourth last character is A+1=B
.
Then i=0
, and num=0
. Therefore,
We do not enter the loop. a[0]=C
, its initial value.
Hence we get: C B D B A
Upvotes: 2