Thursday, September 29, 2016

Square of given number using function with an argument and a return value.

/* C program to find square of given number using function.
Use of function with an argument and a return value.
*/
#include<stdio.h>

int square(int); // function prototype declaration.

void main()
{
     int number, answer;
    
     printf("Enter your number:");
     scanf("%d", &number);
    
     answer = square(number);  //Call function.
    
     printf("Square of %d is %d.", number, answer);
}

int square(int n)
{
     //function logic is written here..
     return(n*n); //This will return answer to main function.
}



Output of the Program:

Enter your number:5
Square of 5 is 25. 

18 comments:

  1. What is function logic represented here

    ReplyDelete
    Replies
    1. The main objective of this program is to demonstrate use of function with an argument and a return value.

      Execution of following statement from main program

      answer = square(number); //Call function.

      will call the function: int square(int n).

      The function will return multiplication of parameter (n) passed during function call. Hence, if function call is square(5); it will return 5 X 5, i.e. 25 value to main program; which is printed using printf() function of main program.

      Delete
  2. in this program it should be int main()

    ReplyDelete
  3. Nice programming....try to write the same program for c++

    ReplyDelete
  4. In this program may have some errors please cjeck it

    ReplyDelete
    Replies
    1. Dear Visitor,
      This program works fine. Share the error which you are facing in this program for further investigation.

      Delete
  5. Can you write this same program without argument and with return type

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Dear Reader, refer the following link to see the C program without argument and a return value: Square of number without argument and a return value.

      Delete
  6. why it said "error :main must return 'int'

    ReplyDelete
    Replies
    1. Dear Visitor,

      Instead of void main() you can also use int main() with return 0 at the end of main() function. Try the following code:

      =========
      #include

      int square(int); // function prototype declaration.

      int main()
      {
      int number, answer;

      printf("Enter your number:");
      scanf("%d", &number);

      answer = square(number); //Call function.

      printf("Square of %d is %d.", number, answer);
      return 0;
      }

      int square(int n)
      {
      //function logic is written here..
      return(n*n); //This will return answer to main function.
      }

      Delete