C program : User Defined Function Practice

 

1. Function with No Arguments and No Return Value

The function does not take any input and does not return any output.

#include <stdio.h>

 

void greet() {

    printf("Hello, Welcome!\n");

}

 

int main() {

    greet();

    return 0;

}

 

 

2. Function with Arguments but No Return Value

Takes input (parameters) but does not return anything.

 

 

#include <stdio.h>

 

void add(int a, int b) {

    printf("Sum = %d\n", a + b);

}

 

int main() {

    add(5, 3);

    return 0;

}

 

3. Function with No Arguments but Returns a Value

Takes no input but returns some output.

 

#include <stdio.h>

 

int giveNumber() {

    return 10;

}

 

int main() {

    int x = giveNumber();

    printf("Value = %d\n", x);

    return 0;

}

 

4. Function with Arguments and Return Value

Takes input and returns output.

#include <stdio.h>

 

int multiply(int a, int b) {

    return a * b;

}

 

int main() {

    int result = multiply(4, 6);

    printf("Product = %d\n", result);

    return 0;

}

 

 

 Master Example:   All types of function in one program

#include <stdio.h>

 

/* 1. No arguments, no return value */

void func1() {

    printf("This is Function 1: No arguments, No return value.\n");

}

 

/* 2. Arguments but no return value */

void func2(int a, int b) {

    printf("This is Function 2: Arguments but No return value.\n");

    printf("Sum = %d\n", a + b);

}

 

/* 3. No arguments but returns a value */

int func3() {

    printf("This is Function 3: No arguments but Returns a value.\n");

    return 50;

}

 

/* 4. Arguments and returns a value */

int func4(int x, int y) {

    printf("This is Function 4: Arguments and Returns a value.\n");

    return x * y;

}

 

int main() {

 

    func1();  // Call function 1

 

    func2(5, 10);  // Call function 2

 

    int value = func3();  // Call function 3

    printf("Value returned from func3 = %d\n", value);

 

    int product = func4(6, 4);  // Call function 4

    printf("Product returned from func4 = %d\n", product);

 

    return 0;

}

Written By

Helping Students Succeed • •Free Book Solutions and Study Guides • sandesh_Shiwakoti