Basic C Programs Part: 1 - Ocean of Programming

Thursday 27 April 2017

Basic C Programs Part: 1

           At this point, we learn some basic C programs. Firstly I will compare 2 programs and show you how to reduce extra coding and implement the code with the same output. If you did not read my previous article Constants and Variables In C Programming and Data Types In C Programming I suggest you read it first for better understanding before proceeding further.





 

 

Program For Basic Mathematical Operations

         Let us first see the general method(method 1) and the second method(method 2) is a somewhat smart method that can save coding effort and coding time. 

Method 1:

#include<stdio.h>
main()
{
        float a,b,c,d,e,f;
        printf("Enter value of a and b\n"); 
        scanf("%f %f",&a,&b);   //takes two number
        c=a+b;    //Addition
        d=a-b;    //Subtraction
        e=a*b;    //Multiplication
        f=a/b;    //Division
        printf("Addition is=%f\n",c);        //Print result of addition
        printf("Subtraction is=%f\n",d);     //Print result of subtraction
        printf("Multiplication is=%f\n",e);  //Print result of multiplication
        printf("Division is=%f\n",f);        //Print result of division
        return 0;
}

Method 2:

#include<stdio.h>
main()
{
        float a,b;
        printf("Enter value of a and b\n");
        scanf("%f %f",&a,&b);
        printf("Addition is=%f\n",a+b);         //Print result of addition
        printf("Subtraction is=%f\n",a-b);      //Print result of subtraction
        printf("Multiplication is=%f\n",a*b);   //Print result of multiplication
        printf("Division is=%f\n",a/b);         //Print result of division
        return 0;
}

           By comparing two methods we require less code writing and fewer variables. The output for both codes is the same as below
          In later posts, I will tell you where you can use shortcuts in the code. Let us consider another program to find the entered number is an odd or even number.

Program For Find Entered Number is Even Number Or Odd Number

#include<stdio.h>
main()
{
     int number;
     printf("Enter an integer: \n");
     scanf("%d", &number);
     if(number % 2 == 0)
         printf("%d is even.\n", number);   //if condition is true
     else
         printf("%d is odd.\n", number);   // if condition is false
     return 0;
}
The output for the above program is
           Please feel free to comment if you find anything incorrect or you want to share more information about the topic discussed above.

No comments:

Post a Comment