hello,
I am building an application where I have two integers and I have to add them or multiply.
I have to use a function to add/multiply this two numbers and call it from the main.

I have done this so far.

int main()
{
  int user_choice; 
 int num1;
 int num2;
 int ans; // ans stands for answer

switch(user_choice){
    case add: printf(" Enter number "); // if user choose addition write "enter number"
		scanf("%d",&num1); // scan number
			printf("Added to "); // ask for second number
			scanf("%d", &num2); // scan second number
			ans = num1 + num2; // add both numbers and place it in variable ans
			printf("sum is: %d\n",ans); // show answer

How can I put that into a function and how do I call it from the main as I am using switch function?
Thank you in advance

Recommended Answers

All 5 Replies

It would look like this:

int add(int a, int b)
{
    /* ... */
}

int mul(int a, int b)
{
    /* ... */
}

int main(void)
{
    /* ... */

    switch (/* ... */) {
    case ADD: add(num1, num2);
    case MUL: mul(num1, num2);
    default: /* Handle bad input */
    }

    return 0;
}

Your job is to fill in the blanks.

Thank you, I have changed the code, however I still get errors.

switch(user_choice){
    case add: printf("\n%d",add(num1,num2));


int add(num1,num2)
{
printf(" Enter number "); 		
scanf("%d",&num1);			
printf("Added to ");
scanf("%d", &num2); 

	return num1 + num2

Your code is both incomplete and wrong. Please post everything, and keep in mind that function definitions cannot be nested within each other:

void foo()
{
    /* This is not legal C */
    void bar()
    {
    }
}

Also you cannot use variables as case numbers in a switch statement. It has to be to contants

Check out this link

Sorry I have posted the code wrong. I have not nested any functions

#include "stdafx.h"

const int add = 1;  
const int multiply = 2;  
int num1;
 int num2;

int main()
{
int user_choice; 
 
switch(user_choice)
{
    case add: printf("\n%d",add(num1,num2));
break;
case multiply: printf("\n%d",multiply(num1,num2));
break;
default:printf("invalid choice");
}
}
int add(num1,num2)
{
printf(" Enter number "); 		
scanf("%d",&num1);			
printf("Added to ");
scanf("%d", &num2); 

	return num1 + num2

}

int multiply(num1,num2)
{
printf(" Enter number "); 		
scanf("%d",&num1);			
printf("multiplied by ");
scanf("%d", &num2); 

	return num1 * num2

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.