comp-prog-module-1
comp-prog-module-1
Learning Objectives:
By the end of this module, students should be able to:
3. Differentiate between functions that return a value and those that don’t (void functions).
Lesson Content
Return nothing (void functions), performing an action without giving back any data.
The return type in a function's declaration defines what type of value it will return:
To return a value, a function must include a return statement with a value of the appropriate type.
#include <iostream>
int getValueFromUser(){
int input{};
int main(){
std::cout << num << " doubled is: " << num * 2 << '\n';
return 0;
In this example:
getValueFromUser asks the user for a number, and the value entered is returned to the main function.
The return value (the user’s input) is then used in the main function to display double the value.
Key Points
Returning a Value: The return keyword is used to exit a function and provide a value back to the caller.
Return Type Matching: The return type must match the type specified in the function signature (e.g., int for
integer).
One Return Per Call: Each call of a function can only return one value at a time.
Common Issue:
If a value-returning function lacks a return statement, it will cause undefined behavior. Make sure that every
possible path in a value-returning function has a return statement.
Activity
1. Code Practice:
Write a function called squareNumber that asks the user for a number and returns the square of that number.
In the main function, call squareNumber, store the result in a variable, and print “The square is: [result]”.
2. Expected Output:
Students should test their program with several values to check that the function correctly returns the square
of the user’s input.
Homework
Task: Create a small program with the following specifications:
Example: The function should return the sum directly to the caller.
2. In main, call sumTwoNumbers and display the result with an appropriate message.
In main, call both sumTwoNumbers and multiplyTwoNumbers and display each result with a message.