Fun with Functions

Write a function titled say_hello() that outputs to the screen "Hello"

★ Modify the function so that it takes an integer argument and says hello a number of times equal to the value passed to it.

★★ Make another function that takes two integers arguments and then returns an integer that is the product of the two integers.
(i.e., integer1: 4, Integer2: 5 returns: 20)

I keep getting this error when I debug the program:

Unhandled exception at 0x77d715de in Fun with Functions.exe: 0xC0000005: Access violation reading location 0xccccccc0.

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
// Fun with Functions.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

string Say_hello(int x, string z)
	{
		for(int i = 0; i < x; i ++)
		{
		return(z);
		}
	}
	

int _tmain(int argc, _TCHAR* argv[])
{
	Say_hello(12, "Hello");
	
	return 0;
}
Last edited on
This is probably because your for statement never executes and the function reaches the end of the function without finding a return statement.
Last edited on
So why doesn't the for loop execute properly? I put return (z) so it should return that
It doesn't execute because the loop condition is false. 0 is not greater than 12.
Oh whoop! I meant to say i < x so it loops the return (z) thanks
dang, it doesn't give an error but It just opens and closes the command prompt... Any ideas on why this is? BTW I updated the code above so it shows that i is < x
The first assignment says thet you should write a function that "takes an integer argument and says hello a number of times equal to the value passed to it."
In your example the function takes two arguments and moreover returns a string. So your funcion does not sutisfies the assignment.
And you did not do the second assignment.
I thought sense it wants me to say "hello", the type is a string... The integer argument is int x and the value I picked to be passed is 12 I thought in my main()? Correct me if im wrong! Thanks
Last edited on
Write a function titled say_hello() that outputs to the screen "Hello"


★ Modify the function so that it takes an integer argument and says hello a number of times equal to the value passed to it.

Where do either of these assignments say you need to pass a string into your function? Or return a string from these functions?
Last edited on
I thought outputting a word is utilizing a string?
The first function can be written as

1
2
3
4
void SayHello( unsigned int n )
{
   for ( unsigned int i = 0; i < n; i++ ) std::cout << "Hello" << std::endl;
}
Ah I used "cout << hello" before but I didn't have the loop right! Thanks for everyone who helped me!
Topic archived. No new replies allowed.