Lab P1 β€” Write a program using functions

NBC351 Β· Program 1 ⏱ 8 min read ❓ 5 MCQs

Aim

Aim: Write a C++ program that demonstrates the use of functions β€” declaration, definition, and calling.

Theory

A function is a named block of code that performs a specific task. Functions help break a large program into smaller, reusable pieces. In C++, a function has a return type, a name, a parameter list, and a body.

Functions can be user-defined or library. The main() function is the entry point of every C++ program.

C++ Program

#include <iostream>
using namespace std;

// Function declaration (prototype)
int add(int a, int b);
void greet();

int main() {
    greet();
    int x = 10, y = 20;
    int sum = add(x, y);
    cout << "Sum of " << x << " and " << y << " = " << sum << endl;
    return 0;
}

// Function definition
int add(int a, int b) {
    return a + b;
}

void greet() {
    cout << "Hello! This program uses functions." << endl;
}

Expected Output

Hello! This program uses functions.
Sum of 10 and 20 = 30

Explanation

  • add(int, int) takes two integers and returns their sum.
  • greet() prints a welcome message; returns nothing (void).
  • Prototypes are declared before main() so the compiler knows their signatures.

Viva / Important Questions

Short Questions

  1. What is a function in C++?
  2. Difference between function declaration and definition?
  3. What is a function prototype?
  4. Can a function return multiple values? How?

Long Questions

  1. Explain the advantages of using functions in programming.
  2. Write a program using functions to find factorial of a number.

MCQ Practice

1. Entry point of every C++ program is:

  • start()
  • main()
  • begin()
  • run()
Answer: main().

2. Which statement correctly declares a function prototype?

  • int add(int, int);
  • int add(int a, int b) { return a+b; }
  • function add(int, int);
  • add(int, int);
Answer: int add(int, int); β€” declaration ends with semicolon, no body.

3. A function that returns no value has return type:

  • int
  • null
  • void
  • empty
Answer: void.

4. In C++, functions are resolved at:

  • compile time (for non-virtual)
  • run time always
  • link time only
  • never
Answer: compile time for normal functions.

5. Which of these is NOT a valid function name?

  • calcSum
  • _value
  • 2ndFunc
  • myFunc
Answer: 2ndFunc β€” identifiers cannot start with a digit.

Quick Revision

  • Function = reusable named block of code.
  • Prototype declares signature before use.
  • Return type + name + params + body.
  • void = no return value.
  • main() is the program entry point.