HackerRank Sum and Difference of Two Numbers solution in c

In this Sum and Difference of Two Numbers problem solution in C Programming The fundamental data types in c are int, float and char. Today, we're discussing int and float data types.

The printf() function prints the given statement to the console. The syntax is printf("format string",argument_list);. In the function, if we are using an integer, character, string or float as argument, then in the format string we have to write %d (integer), %c (character), %s (string), %f (float) respectively.

The scanf() function reads the input data from the console. The syntax is scanf("format string",argument_list);. For ex: The scanf("%d",&number) statement reads integer number from the console and stores the given value in variable number.

To input two integers separated by a space on a single line, the command is scanf("%d %d", &n, &m), where n and m are the two integers.

Task

Your task is to take two numbers of int data type, two numbers of float data type as input and output their sum:

  1. Declare 4 variables: two of type int and two of type float.
  2. Read 2 lines of input from stdin (according to the sequence given in the 'Input Format' section below) and initialize your 4  variables.
  3. Use the + and - operator to perform the following operations:
  4. Print the sum and difference of two int variables on a new line.
  5. Print the sum and difference of two float variables rounded to one decimal place on a new line.

HackerRank Sum and Difference of Two Numbers solution in c


HackerRank Sum and Difference of Two Numbers problem solution in c programming.

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

int main()
{
	int a,b,sum=0,sub=0;
    float c,d,s=0,su=0;
    scanf("%d%d",&a,&b);
    sum= a+b;
    sub=a-b;
    printf("%d %d\n",sum,sub);
    scanf("%f%f",&c,&d);
    s=c+d;
    su=c-d;
    printf("%0.1f %0.1f",s,su);
    
    return 0;
}


Second solution

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

int main()
{
	int a, b;
    float c, d;
    scanf("%d %d", &a, &b);
    scanf("%f %f", &c, &d);
    
    printf("%d %d\n%.1f %.1f", a+b, a-b, c+d, c-d);
    
    return 0;
}


Post a Comment

0 Comments