Stuck in a loop

This is a discussion on Stuck in a loop within the C++ Programming forums, part of the General Programming Boards category; Originally Posted by Bench82 That's starting to look better already! ]Assuming you alter vote() to return an int Ok... assuming ...

  1. #16
    Registered User
    Join Date
    Feb 2006
    Posts
    38
    Quote Originally Posted by Bench82
    That's starting to look better already!

    ]Assuming you alter vote() to return an int
    Ok... assuming I change all the 'void's to 'int'...
    then at the end of the code... how do I return the value(total of EACH district) to main and then figure out overall winner?

    I'm a little slow to catch what you're saying... I'll highlight what I've changed so far...
    Code:
    #include <iostream>
    
    using namespace std;
    
    int vote();
    
    int main()
    {
    	cout<<"Welcome to the election gizmo\n\n";
    	int vote();
    	int vote();
    	return 0;				
    
    }
    
    int vote()
    {
    	int voterNum = 1;
    	int candidateA = 0, candidateB = 0;
    	char choice;
    	int district=1;
    
    	cout<<"District "<<district<<" is next.\n";
    
    	while (voterNum <= 10)			
    	{
    		cout<<"Voter Number "<<voterNum<<" please vote now.\n";
    		cout<<"Your choices are candidate 'A' and candidate 'B'\n";
    		cout<<"Please enter your choice now: ";
    		cin>>choice;
    		
    		if (choice=='A'||choice=='a')
    		{
    			candidateA++;
    		}
    			
    		if (choice=='B'||choice=='b')
    		{
    			candidateB++;
    		}
    		
    		
    		voterNum++;
    	}
    	cout<<"District 1 totals: \n\n";
    	cout<<"Candidate A: "<<candidateA<<endl;
    	cout<<"Candidate B: "<<candidateB<<"\n\n";
    	
    	if (candidateA>candidateB)
    	{
    		cout<<"Candidate A is the winner of this District\n\n";
                    return candidateA;
    	}
    		else
    			{
    			if (candidateA<candidateB)
    				{
    				cout<<"Candidate B is the winnder of this District\n\n";
    return candidateB;
    				}
    			else
    				{				
    					cout<<"Tie in this district\n\n";
    return;
    				
    				}
    		}
    		district++;
    
    }

  2. #17
    Registered User
    Join Date
    Feb 2006
    Posts
    38
    Quote Originally Posted by Richie T

    Code:
    void vote()
    {
    	int voterNum;
    	int district;
    	int candidateA, candidateB;
    	int totalA = 0, totalB = 0;
    	char choice;
    
    	for (district = 1; district <= 2; district++)
    	{
    		candidateA = 0;
    		candidateB = 0;
    
    		for (voterNum = 1; voterNum <= 10; voterNum++)
    		{
    			cout<<"Voter Number "<<voterNum<<" please vote now.\n";
    			cout<<"Your choices are candidate 'A' and candidate 'B'\n";
    			cout<<"Please enter your choice now: ";
    			cin>>choice;
    			
    			if (choice=='A'||choice=='a')
    			{
    				candidateA++;
    			}
    				
    			if (choice=='B'||choice=='b')
    			{
    				candidateB++;
    			}
    			voterNum++;
    		}
    
    		totalA += candidateA;
    		totalB += candidateB;
    
    		cout<<"District "<<district<<" totals: \n\n";
    		cout<<"Candidate A: "<<candidateA<<endl;
    		cout<<"Candidate B: "<<candidateB<<"\n\n";
    		
    		if (candidateA>candidateB)
    		{
    			cout<<"Candidate A is the winner of this District\n\n";
    		}
    		
    		else
    		{
    			if (candidateA<candidateB)
    			{
    			cout<<"Candidate B is the winnder of this District\n\n";
    			}
    			
    			else
    			{				
    				cout<<"Tie in this district\n\n";
    			}
    		}
    	}
    
    	if (totalA>totalB)
    	{
    		cout<<"Candidate A is the winner of this Election\n\n";
    	}
    	
    	else
    	{
    		if (totalA<totalB)
    		{
    		cout<<"Candidate B is the winner of this Election\n\n";
    		}
    		
    		else
    		{				
    			cout<<"Election tie!\n\n";
    		}
    	}
    }
    also avoid global variables like the previous poster said - i showed
    you a better way earlier using references

    This code is nice and clean. It makes perfect sense, but when I compile it, (using old Visual C++ 6.0 BTW) it only prints this:

    Code:
    Welcome to the election gizmo (this is in main)
    
    press any key to continue

  3. #18
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    Quote Originally Posted by liquidcourage1
    Ok... assuming I change all the 'void's to 'int'...
    then at the end of the code... how do I return the value(total of EACH district) to main and then figure out overall winner?
    You can only return once from a function (because a return means that the function is finished). Much in the same way that an operation on a calculator will only give you one result.
    [EDIT - Meaning : You can have multiple exit points, but only one of those exit points will actually be called]


    What information are you specifically interested in giving back to main()? Your vote() function calculates the winner, and stores how many votes the winner had. at the moment you're returning the number of votes held by the winner.
    If there's other data you need to pass back, then you need to alter the way your program works (it won't hurt to break down the program into smaller functions - it's usually very clunky to put all your input, processes and output all together like that)

    I'm a little slow to catch what you're saying... I'll highlight what I've changed so far...
    Maybe try a simpler example so that you can experiment with functions and see exactly what is going on. The following should work if you copy and paste into your compiler:
    Code:
    #include <iostream>
    using namespace std;
    
    int maths()
    {
        int answer;
        answer = 2+2;
        return answer;
    }
    
    int main()
    {
        int myNumber;
        myNumber = maths();
        cout << "myNumber is: " << myNumber;
    
        cin.get();
    }
    it should be pretty clear to see what's going on - the function performs an operation (2 + 2), and returns it at the end. then myNumber is assigned the output from the maths() function.

    Better still - let the main function provide the numbers to be added together -
    Code:
    #include <iostream>
    using namespace std;
    
    int addition(int a, int b)
    {
        int answer;
        answer = a+b;
        return answer;
    }
    
    int main()
    {
        int myNumber;
        myNumber = addition(4, 5);
        cout << "myNumber is: " << myNumber;
    
        cin.get();
    }
    These 2 snippets are essentially doing the same operation, but you can see the 2nd is more flexible than the first - I hope this gives you a clearer idea of how functions work, and how they can interact with main() .. (or any other part of a program)



    Code:
    int main()
    {
    	cout<<"Welcome to the election gizmo\n\n";
    	int vote();
    	int vote();
    	return 0;				
    
    }
    When you call a function, don't put the data type right in front of it. the program probably thinks you're declaring the functions (Hence why it doesn't actually call them when you run) - They're already declared by the prototypes before main(), so what you want to do is get rid of the int - so your program will call them instead.

    You will have 2 calls to vote() - meaning you'll get 2 values returned, you need to make somewhere to store those variables.
    either do something like this:
    Code:
    int result1, result2;
    result1 = vote();
    result2 = vote();
    or maybe this..
    Code:
    int result1 = vote();
    int result2 = vote();
    Both have the same effect.
    Last edited by Bench82; 04-27-2006 at 07:36 AM.

  4. #19
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    Your code will be far more flexible if you break down your program into small bits - think about the steps involved. at the moment your vote() function does several things - Gets users votes, calculates the winner, and outputs results to the screen. these steps are fairly exclusive to each other from a real-world point of view, so it would make sense to seperate them into seperate functions.

  5. #20
    Registered User
    Join Date
    Jan 2006
    Posts
    36
    This is what I came up with for him after a PM.

    Code:
    /* 
    Create a voting booth program. Once both districts are completed, report to the administrator.  
    Your totals MUST include which candidate won each district and by how much. 
    Then report the overall winner of the election and by how much.  
     
    ASSUMPTIONS
    There are 2 voting districts.  In each voting district there are 10 voters.
    Each voter has a number, from 1 - 10.  The numbers denote the order in which 
    the voters will be asked to vote.
    */
    
     #include <iostream>
     using namespace std;
    
     void PrintIntro();
    
     void District(int *candidateA, int *candidateB);
    
     void PrintResults(int totalA, int totalB);
    
    int main()
    {
     int candidateA = 0;
     int candidateB = 0;
     int totalA = 0;
     int totalB = 0;
     int count;
     int district = 1;
    
     PrintIntro();
    
     for (count=0; count<2; count++)
    	{
    	cout<< "District "<< district << endl;
    
    	District(&candidateA, &candidateB);
    
    	totalA = candidateA + totalA;
    	totalB = candidateB + totalB;
    
    	cout <<"In District "<< district <<" Candidate A got "<<    candidateA <<" votes and Candidate B got "<< candidateB <<" votes."<< endl;
    		
    	//cout << totalA <<" "<< totalB << endl;
    
    	district = district + 1;
    	
    	candidateA = 0;
        candidateB = 0;
    	}
    
     PrintResults(totalA, totalB);
     
     cout<< "Execution Terminated" << endl; 
     
     return 0;
    }
    
    void PrintIntro()
    {
     cout<< "*****************************************************************" << endl;
     cout<< "               Welcome to the Election Program!" << endl;
     cout<< "This program computes the number of votes for two candidates" << endl;
     cout<< "in two districts. Voters will be called by voter number starting" << endl;
     cout<< "with one going through ten in each district." << endl;
     cout<< "*****************************************************************" << endl;
    }
    
    void District(int *candidateA, int *candidateB)
    {
     int voterNum = 1;
     int choice;
     int count;
    
     for(count=0; count<10; count++)
    	{
    	cout<<"Voter Number "<<voterNum<<" please vote now." << endl;
    	cout<<"Your choices are 1 for candidate 'A' and 2 for candidate 'B'" << endl;
    	cout<<"Please enter your choice 1 or 2 now: ";
    	cin>>choice;
    
    	while((choice != 1) && (choice != 2))
    		{
    		cout<<"Invaled Selection Voter Number "<<voterNum<<" Please Try Again!." << endl;
    		cout<<"Your choices are 1 for candidate A and 2 for candidate B" << endl;
    		cout<<"Please enter your choice 1 or 2 now: "<< endl;
    		cin>>choice;
    		}
    
    	if (choice == 1)
    		{
    		*candidateA = *candidateA + 1;
    		}
    				
    	else 
    		{
    		*candidateB = *candidateB + 1;
    		}
    
    	cout<<endl;
    
    	voterNum++;
    	}
     
     return;
    }
    
    void PrintResults(int totalA, int totalB)
    {
     cout << "The results are in"<< endl;
     cout << totalA <<" votes for Candidate A"<<endl;
     cout << totalB <<" votes for Candidate B"<<endl;
    
     if (totalA > totalB)
    	{
    	cout << "Candidate A Wins!" << endl;
    	}
     else if (totalA < totalB)
    	{
    	cout<< "Candidate B Wins!"<< endl;
    	}
     else if(totalA == totalB)
    	{
    	cout<< "There was a Tie, We need to revote!"<< endl;
    	}
     
     return;
    }
    You still need to comment the code.

    I am far better in C than C++ so any suggestions would be welcome.
    Last edited by jlharrison; 04-26-2006 at 10:12 PM.

  6. #21
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    With regards to the last post made about compiling my code
    under Visual C++ 6.0, my code should work ok, it just sounds like
    main is not calling the function - make sure that the code is set
    up like this:

    Code:
    #include <iostream>
    
    using namespace std;
    
    void vote ();
    
    int main (void)
    {
        cout << "Welcome to the election gizmo\n\n";
        vote ();
        return 0;
    }
    
    void vote ()
    {
        //body of the vote function
    }
    also, you're getting a lot of information about returning values
    from a function - the previous poster has submitted some code
    that should work well, but i'm guessing that you haven't seen
    pointers already, so the small example of using references would
    probably be better. there's a lot of information in this thread, so
    take your time and read the code carefully - the last post by
    Bench82 explains returning a single value from a function in
    good detail. you might find it useful to check out these tutorials
    on functions, pointers and also a short one on references - the
    main one being the functions one though:

    Functions
    Pointers
    References
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Rewriting a for loop as a while/do-while loop
    By Ashfury in forum C++ Programming
    Replies: 7
    Last Post: 04-27-2007, 03:20 PM
  2. return to start coding?
    By talnoy in forum C++ Programming
    Replies: 1
    Last Post: 01-26-2006, 03:48 AM
  3. loop needed also how to make input use letters
    By LoRdHSV1991 in forum C Programming
    Replies: 3
    Last Post: 01-13-2006, 05:39 AM
  4. Help! Stuck in a loop!
    By raell in forum C++ Programming
    Replies: 2
    Last Post: 12-17-2003, 10:47 AM
  5. Stuck in a loop!.....Get me out of here!!
    By rabmaz in forum C Programming
    Replies: 3
    Last Post: 09-01-2002, 10:16 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21