return value from a void function?

So my teacher for C++ has some very specific requirements on his assignments, he gives 0 credit for assignments that are completed that aren't EXACTLY how he wants them, regardless of if they work or not, or solve the problem, or provide the correct answer.

His specifications for this problem are as follows:

Write a function named toUpper. This function is passed a null terminated string. The function should convert each lowercase character in the string to its uppercase equivalent. No other characters in the string should be changed. The function declaration will be as follows:
void toUpper (char string []);
Note that the parameter is an IN/OUT parameter since it is used to pass data to the function and return the result. The result should be returned. DO NOT DISPLAY THE RESULT.


So my question/problem is, everything I've read about the return statement is that I can't return a value like that from a void function unless it's pass by reference, but he will give me a big fat zero for this assignment if I do that, soooo, what do?

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
using namespace std;
void toUpper (char string[]);

int main ()
{

//I just have all this in the main function here to test my toUpper function, teacher only wants the toUpper function part turned in.

  char myArray [25];
  int result;
  cout << "Enter up to 24 characters" << endl;
  cin.getline (myArray, 25);
  cout << myArray << endl;
  toUpper (myArray);
  cout << myArray << endl;

return 0;
}


void toUpper(char string[])
{
    char ch;
    int index = 0;
    ch = string[index];
    while (ch != '\0')
    {
        if (ch >= 'a' && ch <= 'z') string[index] -= 32;
        index++;
        ch = string[index];
    }
    //I'm assuming he wants some kind of return statement here that returns the result to the main function... But this function type void.  What do?
}
When you pass an array to a function it is passed by reference automatically so anything you do to the array will end up effecting the original. I am guessing that is what he is saying here....
Note that the parameter is an IN/OUT parameter since it is used to pass data to the function and return the result.
Although using the word "return" so much with "void" isn't the best way to say it.

You are correct that it is impossible to return a variable directly from that function as it's defined.
closed account (E3Uiz8AR)
I am no expert, but am studying OOP and C++ paradigms and conventions HARD lol.

VOID functions / methods cannot return any value. Instead in this case I believe he is looking for the function to perform the output itself.

Please see my solution below, hope you get my train of thought! (Oh and P.S. Please do read up on the STL! There's loads of functions built in that help with stuff like this. For example the function toupper(char) which converts a char from lower to uppercase!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void toUpper(char String[], int arrayLength)
{
    char upperCase[arrayLength];

    for(int x = 0; x < arrayLength; x++)
    {
        char current = String[x];
        upperCase[x] = toupper(current);
    };

    for(int y = 0; y < arrayLength; y++)
    {
        cout << upperCase[y];

        if(y == arrayLength - 1)
        {
            cout << endl << "Reached end of array. All uppercase now!" << endl;
        };
    };
}


There are some other issues too:

string[] cannot be called such as the word string is reserved for C++.
- I replaced this with 'S'tring.

Your main doesn't require a cout function. Also, you cannot just cout an array.
- I fixed this by
- - A: merely calling the function and pausing in main.
- - B: Used a for loop to 'cout' all individual letters in array by subscript INSIDE the function.

the if(ch >= 'a' && ch <= ' z') won't work either as they are non-consecutive in the ascii table. Whichever, I never got the result I expected from that.

Hope this helps you out! I did manage to get it to run using this whole script!

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
#include <iostream>
#include <array>
#include <Windows.h>

using namespace std;

void toUpper(char String[], int arrayLength)
{
    char upperCase[arrayLength];

    for(int x = 0; x < arrayLength; x++)
    {
        char current = String[x];
        upperCase[x] = toupper(current);
    };

    for(int y = 0; y < arrayLength; y++)
    {
        cout << upperCase[y];

        if(y == arrayLength - 1)
        {
            cout << endl << "Reached end of array. All uppercase now!" << endl;
        };
    };
}
int main()
{

    char message[5] = {'H','e','l','l','o'};

    toUpper(message, 5);

    system("PAUSE");
    return 0;
}


Tech1337
Actually if the character array ends with a null terminator '\0' you may output it like cout << array << endl; it is a special case. Also arrays are pretty much pointers. So when you pass an array you are passing the memory address of it so when you modify it in the function it is also being modified outside of it since they will have the same address.

So possibly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

void toUpper( char array[] ); //or *array

int main()
{
    using std::cout;
    using std::endl;

    char array[6] = "Hello"; //by default it should append the null since I used double
    //quoteswhich indicates it is a string and is not an ordinary array
    
    toUpper( array );

    cout << array << endl;
}

void toUpper( char array[] )
{
    for( int i = 0; array[i]; ++i )
        array[i] = toupper(array[i]); //http://www.cplusplus.com/reference/cctype/toupper/?kw=toupper
}


http://ideone.com/tO0BEL

closed account (N36fSL3A)
You can't do that with arrays. The variable that sets the size of an array must be constant.

If you want to do that, look into pointers:
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
void toUpper(char String[], int arrayLength)
{
    char* upperCase = nullptr;

    // Allocate a dynamic array with the specified length.
    upperCase = new char[arrayLength];

    for(int x = 0; x < arrayLength; x++)
    {
        char current = String[x];
        upperCase[x] = toupper(current);
    };

    for(int y = 0; y < arrayLength; y++)
    {
        cout << upperCase[y];

        if(y == arrayLength - 1)
        {
            cout << endl << "Reached end of array. All uppercase now!" << endl;
        };
    };

    // Don't forget that you MUST free allocated memory.
    delete[] upperCase;
}


Of course - std::strings are better, so you may want to use those instead of char arrays.
Last edited on
closed account (E3Uiz8AR)
Ahh, OK. This is why I joined!

I (think) I've learned 2 things.

Giblit uses array[i] as the condition in the for loop.

Would I be correct in saying that if the array subscript goes out of bounds the loop exits?

And Lumpkin - I understand the issue with const. I merely forgot this as I am new to C++, but arrays initialized with a non static pointer are dynamic as the pointer variable can change?

EDIT: Also, I know the use of system is awful, and I could have spent more time, but this does specify college work and I was trying to simplify (or simply make a script that compiles and produces right effect) :P
Last edited on
It's c++ hackery. Basically a string of characters ends with a null terminator '\0' which happens to be 0 on the ascii table. And in c++ if something is 0 it is false and if it is anything else it is true. So basically it will loop until the condition is false (the null).

Just like you can do something like this

1
2
3
4
5
6
int a = 10;

while( a )
{
    --a;
}
closed account (E3Uiz8AR)
Also - I should sleep more! I really missed a lot of info there, perhaps in eagerness to help, perhaps in tiredness.

Forgive my sleepy hubris!

I understand the whole shebang now, instead of outputting the values, merely reassigning the array inside the function will yield the result asked for without the use of return.

I am unsure who this helped more, me or the guy posting it!

Thanks anyway guys, perhaps I can take another crack at solving this in the (later) morning after some kip!
closed account (E3Uiz8AR)
giblit, that is legendary!

I understand the while loop, and have used that, but only just got the NULL array termination.

That has solved an issue I am currently having rewriting 'Hamurabi' for my coding module at uni.

I love this place. People speak my language and teach me things!

:D

EDIT: Not a bad haul for the first 20~ minutes! Haha!
Last edited on
Wow, I appreciate the quick replies. Thank you everyone.
I laughed hard when I found out that toupper () exist. I would love to just turn in a function that calls that if I knew that wouldn't earn me a 0.
I also appreciate everyone's knowledge on here, but I must also regret to inform that if I turned in anything that was written here I'd also earn a 0.
He requires things in a very exact way, and if they aren't done to his EXACT specification, doesn't matter if it works, is elegant, simple, or... anything, it earns a 0 because it isn't what he wants.

void toUpper(char String[], int arrayLength)
will earn me a 0 because it isn't
void toUpper (char string []);
Which is what he is requiring...

Using:
array[i] = toupper(array[i]);
Will also earn me a zero because it's calling another function to do the dirty work.

I think the first answer might have said it best
Although using the word "return" so much with "void" isn't the best way to say it.


Thinking teacher is just very poor at wording instructions for someone who requires things in such an exact manner.

Not even joking I've got about a 60% for a grade in this class and got a zero on the last 3 assignments because I did something like use pass by reference instead of pass by value in a function, or named my program the wrong file name, or named a variable wrong... I've never taken a class where I could do every problem in the book up to the point we are at, get the right answer, everything compiles, runs without errors, and yet get so many zeros for grades... Pretty sure I'm going to have to retake this class with a different teacher, at least that means I can concentrate on my other classes then... :-/
It really is a disappointment when classes turn from learning as much as you can to learning as much as the teacher wants you to learn (and will fail you as soon as you try something different that works).

I have had math teachers with similar outlooks where any problem that isn't done exactly how they specify is instantly wrong. My only advice to you is to keep trying to learn as much as you can by yourself and don't let this turn you off programming!
closed account (E3Uiz8AR)
Oh Arctic, what a cruel master you have.

Everytime I think I get the answer, here the game changes, but I think I have won!

I can imagine this bastard with all manner of fine torture devices and black leather in his basement for setting you this puppy.

I do believe I have cracked this fucker!

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
#include <iostream>
#include <stdlib.h>
#include <Windows.h>

using namespace std;

void toUpper(char string[])
{
	for(char* p=string; *p !='\0'; p++)
    {
		if(*p >= 'a' && *p <= 'z') //Only if it's a lower letter
		{
			*p -= 32;
		}
    }
};

int main(void)
{
	char message[25];

	cout << "Please enter a message (24 Characters MAX): ";
	cin.getline(message, 25);

	toUpper(message);

	cout << endl << message << endl << endl;

	system("PAUSE");
	return 0;
};


This has kept me tapping away like a beast for about 4 hrs now!

To meet his 'specifications' I have followed his shit to almost the letter! This is the only working example I can muster, and would love to invite fellow, more experienced members to critique my work!

See if this works for you.

EDIT: I feel for you friend, guy seems like a tough nut. I got downgraded recently for being "Too Advanced and Efficient" by using classes, a topic we had not yet covered in lectures!
Last edited on
Your code looks alright tech1337. The only thing that would be wrong in this case is that the instructions explicitly stated not to print the result.

EDIT* By the wording of the instructions, it could mean two things:

1.) He doesn't want you to print the result at all.

2.) He doesn't want you to print the result in the toUpper() function, but it's alright (and probably expected) for you to do so later on.
Last edited on
closed account (E3Uiz8AR)
Only do not print from inside the method, from my understanding of it?

EDIT: The guy also says that the tutor expects only the method, the rest I added for testing purposes.

I am still new so this was kind of a win for me! I was 30 minutes working out why spaces terminated the loop.

The answer was cin.getline() lol! I could've cried! Haha!

And yeah those are some pretty ambiguous instructions!

* If this helped you Arctic, please let me know! :)
Last edited on
you guys are awesome. Yes, you all have helped me very much with this. As far as the printing goes, he is only having us turn in the toUpper function part. The main function is only there for testing purposes. He has his own main function for grading. That's why he wants the answer to be returned to the main function. I think the way he grades these is he has his own main function in a library, and compiles the function separately to create an obj file, and puts it all together. I think that is why he is so exacting, because obviously, if instructions aren't followed to the letter, it isn't going to compile. I just wish that if he was going to do that he'd give us a copy of the library he was using with the assignment so we can actually test everything before it's turned in, so we know that it will work with his code. I appreciate all the help with this, 1 problem down, 4 to go on this assignment, hahah...
Almost forgot too, James2250; this doesn't really turn me off to programming, I enjoy the act of programming. It is the programming teachers I hate. I've taken two programming classes, and both times had horrible teachers. This first time was about 10 years ago, and it was a C+ class, it was Dr. Nomura at UTA, I don't know how his English is today, but at the time, he could barely speak English. He had a grad student translating everything he said to the class, and some things just do not translate well. I dropped this class, really didn't learn very much aside from very basic programs, don't think I even made it to arrays, I think loops was about as far as I made it. This time the class is going much better as far as learning goes, but the grade part sucks pretty hard. I think the trouble is, a lot of teachers teach like you already know the language, or even, anything about programming in general. It's really difficult to be told, type this this and this to make your first program and have no idea what any of it means. For example, take the main function itself, functions aren't even introduced in my book until chapter 6, but from chapters 1-5 they say, just type "this" at the beginning of your program so it works, we will explain what "this" means later. I can appreciate what they are doing is trying to have you hit the ground with running programs for instant gratification, but it doesn't mean anything to me if I don't know why it works. I honestly wouldn't mind if I didn't get to write my first working program until chapter 6 if it meant I understood everything I was coding, and why I was typing int main() and using #include <iostream> and using return 0; at the end.
Topic archived. No new replies allowed.