Monday, January 6, 2020

Conditional Statements in C - Hacker Rank Solution

Conditional Statements in C - Hacker Rank Solution

Given a number, if it is less than 10, you have to print it's english representation if it is less than 10 else print "Greater than 9". This can be solved using if-else loop. You can see the tester's code below.
One more lazy way to do this is to have a string array which stores all the values possible to possibly avoid if-else statements. you can see the tester's code for this below.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    
    int n;
    scanf("%d", &n);
    if(n == 1) {
        printf("one");
    }
    else if(n == 2) {
        printf("two");
    }
    else if(n == 3) {
        printf("three");
    }
    else if(n == 4) {
        printf("four");
    }
    else if(n == 5) {
        printf("five");
    }
    else if(n == 6) {
        printf("six");
    }
    else if(n == 7) {
        printf("seven");
    }
    else if(n == 8) {
        printf("eight");
    }
    else if(n == 9) {
        printf("nine");
    }
    else {
        printf("Greater than 9");
    }
    
    return 0;
}
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    int n;
    char* represent[10] = {"Greater than 9", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

    scanf("%d", &n);

    if(n > 9) {
        printf("%s", represent[0]);
    }
    else {
        printf("%s", represent[n]);
    }

    return 0;
}

7 comments:

  1. Always else block only executing
    ..... greater than 9

    ReplyDelete
  2. why are u taking char* instead of char while initiliazing

    ReplyDelete
    Replies
    1. He has used pointer for 10 strings. suppose represent[0] is stored at 1000 address then the next pointer will store second string(represent[1]) at 1015
      as 'greater than 9' occupies 15 bytes(one for null character).

      Delete
  3. https://www.youtube.com/watch?v=iE77rU_CnVA&t=28s

    check my easy code here

    ReplyDelete
  4. #include
    #include

    void update(int *a,int *b)
    {

    int t1, t2;
    t1 = *a + *b;
    t2 = abs(*a - *b);
    *a = t1;
    *b = t2;
    }

    int main() {
    int a, b;
    int *pa = &a, *pb = &b;

    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
    }

    ReplyDelete

Powered by Blogger.