I got some problem and need some help to finish the homework

Write a program Q2.cpp that meets the following requirements.
a. Write a function inc()that will increase the value of variable by a specified number.
Calling example:
int x=0;
inc(x); // increase value of x by default value 1
inc(x,10); // increase value of x by specified number 10
b. Overload the function inc()that will also increase variable by specified number but with
different type of paramenters.
Calling example:
int x=0;
inc(&x); // increase value of x by default value 2
inc(&x,20); // increase value of x by specified nymber 20
c. Use the following code as the program template

int main()
{
int x=0;
inc(x);
cout << x << endl;
inc(x,10);
cout << x << endl;
inc(&x);
cout << x << endl;
inc(&x,20);
cout << x << endl;
return 0;
}
The output of program will be
1
11
13
33
What is the "some problem"? The instructions look clear.

Start by implementing the inc() that takes two arguments.
Next, recall the default argument values syntax .
Hi johnlai,
Your teacher is very strange :P... this exercice teaches the wrong way to do things. Anyway, to match the requirements, do this : two functions mofiying their parameter,

1
2
3
4
5
6
7
8
9
int inc(int& value, int delta = 1)
{
	return value += delta;
}

int inc(int*  value, int delta = 2)
{
	return *value += delta;
}

And that's all ^_^

By the way, I don't like the name "inc", increment means "add one to"... so the function is really add() and not increment ^_^.

You can find the overall source code here https://www.punksheep.com/partage/C++/inc_23506.zip

I cannot say I love your teacher heheheh :D


Here's the full code with the test sample :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//[brief]	useless exercice implementing function (inc) overload over pointer and reference + optional parameter
//[forum]	http://www.cplusplus.com/forum/general/235067
//
//[author] punks Marc
//[contact email]	punksheep@kantamal.net
//[web site]	http://www.punksheep.com
//
//[note] delete the line <<#include "stdafx.h">> if it doesn't compile.
#include "stdafx.h"

#include <iostream>


int inc(int& value, int delta = 1)
{
	return value += delta;
}

int inc(int*  value, int delta = 2)
{
	return *value += delta;
}

int main()
{
	using namespace std;

	int x = 0;
	inc(x);
	cout << x << endl;
	inc(x, 10);
	cout << x << endl;
	inc(&x);
	cout << x << endl;
	inc(&x, 20);
	cout << x << endl;

    return 0;
}
Last edited on
Topic archived. No new replies allowed.