0% found this document useful (0 votes)
13 views

Function Sample Programs

Uploaded by

wokejo9684
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Function Sample Programs

Uploaded by

wokejo9684
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Simple Function Definition and Call:

#include <stdio.h>
int greet(void)
{ printf("Hello, world!\n");
return 0; }
int main()
{ greet();
return 0; }

Function with Parameters and Return Value:

#include <stdio.h>

int add(int x, int y) {


return x + y;
}

int main() {
int a = 5, b = 3, sum;

sum = add(a, b);


printf("Sum of %d and %d is %d\n", a, b, sum);

return 0;
}

Function with Default Arguments (may not work in c):

#include <stdio.h>

int multiply(int x, int y = 1) {


return x * y;
}

int main() {
int a = 5;
printf("Product of %d and 1 is %d\n", a, multiply(a));
printf("Product of %d and 3 is %d\n", a, multiply(a, 3));

return 0;
}

Function with Variable Number of Arguments:

#include <stdio.h>
#include <stdarg.h>

int sum(int count, ...) {


va_list args; // variable argument list
int i, sum = 0;

va_start(args, count); // system function


for (i = 0; i < count; i++) {
sum += va_arg(args, int);
}
va_end(args);//system function

return sum;
}

int main()
{
int result;

result = sum(3, 10, 20, 30);


printf("Sum of 10, 20, and 30 is %d\n", result);

return 0;
}

Switching between functions


#include <stdio.h>
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);

void main() {
int a = 6, b = 2, result,ch;
printf(" Accept choices for calculator : \n 1 for sum \n 2 for subtract \n 3 for multiplication
\n 4 for divison \n ");
scanf("%d",&ch);
if(ch==1)
{

result = add(a, b);


printf("Sum of %d and %d is %d\n", a, b, result);}
else if(ch==2)
{

result = sub(a, b);


printf("Minus of %d and %d is %d\n", a, b, result);}
else if(ch==3)
{

result = mul(a, b);


printf("Product of %d and %d is %d\n", a, b, result);}
else if(ch==4)
{

result = div(a, b);


printf("Quotient of %d and %d is %d\n", a, b, result);}

else
{printf("Wrong input");}

int add(int x, int y) {


return x + y;
}

int mul(int x, int y) {


return x * y;
}
int sub(int x, int y) {
return x - y;
}
int div(int x, int y) {
return x / y;
}

You might also like