• 0

[C/C++] Help with broken if statement


Question

Hi,

I am having a little trouble figuring out where my mistake is in my assignment. Everything runs fine until the very end where it is supposed to show the largest value in the array. Every time I run the code it always shows arr[19] as the largest. I cannot figure out what I am doing wrong. It is probably something simple but I am not seeing it.

I appreciate the help!

/*
* Author: 
* Date: 14 April 2009
* Assignment: Lesson 4 Chapter 8 Project 5
* Class: 
* Instructor: 
* School: 
*
* Purpose: Create an array named "arr" of type integer with 20 fields. Offer the user the ability to input
* values or offer to autofill the array. After the input is completed display the largest value and its subscript.
*
* Requirements: User input to fill as many array values as wanted or to select the autofill option.
* Output: Largest array value and its subscript
*/

#include <stdio.h>
#include <stdlib.h>

int arr[20];				/*Array used for integer population and manipulation*/

/*Function prototypes*/


int
main(void)
{/*Start Main Function*/

	int counter,			/*Counter used in for loops*/
		tempInt,			/*temp variable used for misc holder*/
		largestInt,			/*Holds largest int value from array*/
		largestIntInd,		/*Holds subscript value of largest integer value in array*/
		optionChosen;		/*Integer used to hold value of menu option chosen*/


	/*Welcome user to program*/
	printf("Welcome to Lesson 4\n");
	printf("Please select an option below by entering its corresponding number\n");
	printf("1) Manually enter values into the array\n");
	printf("2) Have the array auto-filled with values\n");
	printf("Enter option by inputting corresponding number-->(1|2)");

	/*Do loop to take user input until it is validated as a correct input option*/
	do
	{/*Start of while loop*/
		scanf("%d",&optionChosen);
		if (optionChosen == 1 || optionChosen == 2)
			break;
		else 
			printf("%d is not a valid menu option. Please enter only 1 or 2->", optionChosen);	
	}/*End of while loop*/
	while(1==1);

	/*A switch statement is used so that future options may be added without any major code rewrites*/
	switch(optionChosen) {/*Start of switch statement*/
		case 1:
			/*user input*/
			printf("\n\nYou will be prompted to enter 20 integers.\nTo stop early enter -1\n");

			for (counter = 0; counter < 20; counter++)	/*For counter asks user for input to add to array. Breaks if user enters -1*/
			{
				printf("Please enter the value for index %d-->",counter);
				scanf("%d", &tempInt);

				if (tempInt == -1)
				{
					break;
				}
				else 
				{
					arr[counter] = tempInt;
				}
			}
			break;

		case 2:
			/*autofill array- */
			for (counter = 0; counter < 20; counter++)
			{
				arr[counter] = rand();
			}
			break;

		default:
			printf("Somehow you broke me... why did you break me?");
	}/*End of switch statement*/

	/*Used for outputting all array values-commented out for final submission*/
	for (counter = 0; counter < 20; counter++)
	{
		printf("%d%7.2c%d\n",counter,' ',arr[counter]);
	}

	largestInt = arr[0];
	largestIntInd = 0;
	for (counter = 0; counter < 20; counter++) /*For statement to loop through entire array and keep the largest values subscript number*/
	{
		if (arr[counter] >= largestInt)
		{
			largestIntInd = counter;
		}
	}

	/*Displays the largest value and its subscript value*/
	printf("The largest integer in the arry is in subscript %d with a value of %d.\n", largestIntInd, arr[largestIntInd]);

}/*End Main Function*/

Link to comment
Share on other sites

10 answers to this question

Recommended Posts

  • 0

I don't think you ever put anything into arr[20] because when counter = 20 it doesn't run the for loop..??

for (counter = 0; counter < 20; counter++)

should be

for (counter = 0; counter <= 20; counter++)

As I said haven't done in awhile so I maybe completely wrong, and I looked at it real quick.

Link to comment
Share on other sites

  • 0

There isn't really an arr[20] because arr[19] is really the 20th value. The subscripts in C start at [0].

arr[0]

arr[1]

arr[2]

...

arr[18]

arr[19]

Thanks for looking though. I really appreciate it.

Link to comment
Share on other sites

  • 0

Heh - you're not updating the largest int found, just the largest index. I hate when I forget stuff like that ;)

		if (arr[counter] &gt;= largestInt)
		{
			largestInt = arr[counter];
			largestIntInd = counter;
		}

Unrelated, your while(1==1) can just be reduced to while(1) and you might want to seed the random number generator so subsequent executions of the program will produce different numbers:

// seeds the random number generator
void seedrand()
{
	// use the current time to seed the random number generator
	struct timeval time;
	gettimeofday(&amp;time, NULL);		  // gets current time
	srand(time.tv_sec * time.tv_usec);
}

Link to comment
Share on other sites

  • 0

Also, what if the user enters -1 when filling the array? Then you go on to reference an array which isn't fully initialized; so tell the loop to stop if there's less integers...

Link to comment
Share on other sites

  • 0

Horizons beat me to it :) You're not updating the largest int, if you find a bigger one than arr[0];

One addition you could make is to change your number 20 to something like numbersInArray. Initially set it to 0 and increment it each time the user enters a number. This will make sure you only read values which the user has entered.

Link to comment
Share on other sites

  • 0

Thanks for the help guys.

I have changed the while(1==1) to while(1).

I used the numbersInArray idea and made sure to set it to 20 when choosing option 2. Now when a user doesn't fill the array it only compares entered values.

I added the largestInt update and it works.

I am still a little confused. My intention was that if I new the subscript value than I didn't need to also know the largest integer. The if statement compares the largest integer and then assigns the subscript value to largestIntInd.

My idea was to compare the actual integers and only keep the subcript value of the integer that was the largest. So in my last printf statement I only reference the largestIntInd and not largestInt.

Does anybody see where I am missing how this is working???

Link to comment
Share on other sites

  • 0

Here's where your problem is:

largestInt = arr[0];
largestIntInd = 0;

for (counter = 0; counter &lt; 20; counter++) /*For statement to loop through entire array and keep the largest values subscript number*/
{
	 if (arr[counter] &gt;= largestInt)
	 {
		  largestIntInd = counter;
	 }
}

It sounds like you just want to reference the value pointed to by the index, correct? It should look like this:

largestIntInd = 0;

for (counter = 0; counter &lt; 20; counter++) /*For statement to loop through entire array and keep the largest values subscript number*/
{
	 if (arr[counter] &gt;= arr[largestIntInd])
	 {
		  largestIntInd = counter;
	 }
}

"arr[counter]" returns an int at position "counter" within "arr[]", and "arr[largestIntInd]" returns an int at position "largestIntInd" within "arr[]". Assuming I didn't make a stupid mistake, that should be what you were looking for, I think.

Link to comment
Share on other sites

  • 0

The problem that you had before was this:

if (arr[counter] &gt;= largestInt)
		{
			largestIntInd = counter;
		}

That's your original code, so lets run through it.

Initially you had largestInt = arr[0];

so say for example we have this

arr[0] = 10;

arr[1] = 20;

arr[2] = 15;

First time through the loop the IF evaluates to TRUE as (arr[0] >= arr[0]).

largestInt = 10;

largestIntInd = 0;

Next time through the loop the IF evaluates to TRUE as (arr[1] >= largestInt)

Now here's where your problem shows, you store the index, but you do not change the value of largestInt.

So now the value are:

largestInt = 10;

largestIntInd = 1;

Next time through the loop we are now evaluating (arr[2] >= 10) which is TRUE when it should be FALSE (as largestInt should be 20)

This is why you need to store the largest integer using the code

if (arr[counter] &gt;= largestInt)
{
	largestIntInd = counter;
	largestInt = arr[counter];
}

Now when we run through the loop after we compare arr[1] with arr[0], largestInt is updated correctly to 20. This ensures that when we then compare arr[2] with arr[1] we get the correct result, as 20 > 15.

Hope this helps :)

edit: Dammit beaten again!! :laugh:

largestIntInd = 0;

for (counter = 0; counter &lt; 20; counter++) /*For statement to loop through entire array and keep the largest values subscript number*/
{
	 if (arr[counter] &gt;= arr[largestIntInd])
	 {
		  largestIntInd = counter;
	 }
}

"arr[counter]" returns an int at position "counter" within "arr[]", and "arr[largestIntInd]" returns an int at position "largestIntInd" within "arr[]". Assuming I didn't make a stupid mistake, that should be what you were looking for, I think.

Yes you're right. If you want to get rid of a variable you could do it this way :)

Edited by ViZioN
Link to comment
Share on other sites

  • 0

Thank you ViZioN and kylejn for the explanation... That was exactly what I needed to see.

I definitely should have seen that. I will now walk away with that feeling... that feeling you get when someone points out what you should have already seen :wacko: .

Thank you all so much for the help.

Link to comment
Share on other sites

  • 0
Thank you ViZioN and kylejn for the explanation... That was exactly what I needed to see.

I definitely should have seen that. I will now walk away with that feeling... that feeling you get when someone points out what you should have already seen :wacko: .

Thank you all so much for the help.

You're very welcome :)

Don't worry about it. I've seen myself coding away at something for hours, only to come back after a break and realise I could've done what I wanted to do in a few lines of code! :p

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.