Saturday, April 19, 2025

C++ Functions with Multiple Arguments

Functions can take multiple parameters/arguments. Every time when we declare function we must state name and data type for those arguments.

When passing values to function, there's no need to prefix them with data type because we already did that while declaring function.

Function down below will just demand 3 individual characters, so we can print them on screen.

Run this code:

#include <iostream>
#include <cstdlib>

using namespace std;

void printMultiChars(char x, char y, char z) {
    cout << x << " " << y << " " << z << endl;
}

int main() {

    printMultiChars('A', 'R', 'B');

    return 0;

}

Result:

A R B

Process returned 0 (0x0)   execution time : 0.057 s
Press any key to continue.

 We can improve our function to have left parts as custom report so we can concatenate it with real values:

#include <iostream>
#include <cstdlib>

using namespace std;

void printMultiChars(char x, char y, char z) {
    cout << "Value of x: " << x << endl;
    cout << "Value of y: " << y << endl;
    cout << "Value of z: " << z << endl;
}

int main() {

    printMultiChars('A', 'R', 'B');

    return 0;

}

Result:

Value of x: A
Value of y: R
Value of z: B

Process returned 0 (0x0)   execution time : 0.171 s
Press any key to continue.

In this example we are taking values using keyboard, run it:

#include <iostream>
#include <cstdlib>

using namespace std;

void printMultiChars(char x, char y, char z) {
    cout << "Value of x: " << x << endl;
    cout << "Value of y: " << y << endl;
    cout << "Value of z: " << z << endl;
}

int main() {

    char x, y, z;

    cout << "Enter char in container x: " << endl;
    cin >> x;
    cout << "Enter char in container y: " << endl;
    cin >> y;
    cout << "Enter char in container z: " << endl;
    cin >> z;

    printMultiChars(x, y, z);

    return 0;

}

Result:

Enter char in container x:
a
Enter char in container y:
b
Enter char in container z:
c
Value of x: a
Value of y: b
Value of z: c

Process returned 0 (0x0)   execution time : 6.807 s
Press any key to continue.

It's easy to create a simple calculator. Function will demand two parameters, integers. Inside function theres result variable (integer). That is simple multiplication operation.

Function will print results on screen, when called with real values.

In this example, we are passing values 5 and 10 as inputs:

#include <iostream>
#include <cstdlib>

using namespace std;

void calculator(int x, int y) {
    int result = x * y;
    cout << "Multiplication: " << result << endl;
}

int main() {

    calculator(5, 10);

    return 0;

}

Result:

Multiplication: 50

Process returned 0 (0x0)   execution time : 0.068 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...