r/CodingHelp • • Jun 24 '19

[C] Please help me writing code for this?

Post image
15 Upvotes

46 comments sorted by

View all comments

Show parent comments

1

u/thatlowkey Jun 26 '19

Actually I was entering %d for string that's why was getting numeric value 😅 Now when I enter %s, output is 'one'

2

u/KuntaStillSingle Jun 26 '19

Alright, one more thing, is it giving you "one" for an input of 1? I think you need the i-1 index right?

printf("%s",strings[i-1]);

Also you will want to handle instances where i is less than 1, so I think you will want this:

if(i<1) printf("less than 1");
if(i<=9) printf("%s",strings[i-1]);
if(i>9) printf("greater than 9");

1

u/thatlowkey Jun 27 '19

Now it prints 'less than 1'

1

u/KuntaStillSingle Jun 27 '19

What number are you entering for which you get "less than 1" ?

1

u/thatlowkey Jun 27 '19

5

1

u/KuntaStillSingle Jun 27 '19

Can you comment out the if statements, and instead just have it print i? All i can think is scanf isn't replacing i with your input character so i is always zero.

1

u/thatlowkey Jun 27 '19

I tried using switch cases. It doesn't work too

1

u/KuntaStillSingle Jun 27 '19

What I mean is something like

int main(){
int i=0;
scanf("%d",&i);
printf("%d", i);
}

To test that you are actually getting the value into i, as opposed to it staying at 0.

1

u/thatlowkey Jun 28 '19

i'm coding on an online IDE(HackerRank) so do you think it will matter there?

2

u/KuntaStillSingle Jun 29 '19

I don't know, I'm not going to sign up to HackerRank, what I can tell you is this:

#include <stdio.h>

int main(){
    static const char *strings[9]= 
    {"one","two","three","four","five","six","seven","eight","nine"};
    int i=0;
    scanf("%d",&i);
    if(i<1) printf ("%s","less than one"); 
    else if(i<=9) printf("%s",strings[i-1]); 
    else printf("greater than 9");
}

Works on onlinegdb.com:

https://i.imgur.com/tox7ggn.png

https://onlinegdb.com/ByTOgHExB