ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
HI, I'm taking a C programming class and I was assigned to write a program that reads ten integers and then it prints the minimum integer. I did it preciously with a while loop but now I have to do it with a for loop. I know a for loop statement looks sore of like this,
#include <stdio.h>
int main(void)
{
const int NUMBER = 22;
int count;
for (count = 1; count <= NUMBER; count++)
printf("Be my Valentine!\n");
return 0;
}
in this example there is only one statement. For my assignment I have to compare 10 digits. I don't really know how to use a for loop, so some advice would help. Here is the previous code I wrote using a while loop if it helps at all.
#include<stdio.h>
int main()
{
int minimum, number1, number2, number3, number4, number5, number6, number7, number8, number9, number10;
printf("enter any integer you want\t");
scanf("%d", &number1);
I would set up an array of integers with at least ten elements. Then I would set up a for() loop for ten iterations and put a scanf() inside the loop to collect the integers from user input. Store the integers to the array as they are entered.
It would also need another integer variable to store the current lowest integer, which can be determined by a simple "if" block inside the loop.
After the loop completes you can output a message about the lowest integer.
The trick to this kind of program is that the for() loop counter serves double duty as your array index variable. It just works well that way. Don't forget though, that C language arrays always begin at element zero [0]. If you are lazy about this kind of thing, then just setup your array with more elements than you need.
HTH
Last edited by Telengard; 03-03-2011 at 08:20 PM.
Reason: highest -> lowest
Well, firstly, why not use [code][/code] tags? It'll render your code in a monospace font (and preserve the tabs/spaces) so that it'll be much easier to read.
Secondly, a few tips WRT your program:
You can use a loop to repeatedly get input from the user, like so:
Code:
#include <stdio.h>
int main()
{
int intArray[5];
printf("Enter five numbers:\n");
int i;
for(i = 0; i < 5; i++)
{
printf("> ");
scanf("%d",intArray+i);
}
printf("The numbers you entered are:\n");
for(i = 0; i < 5; i++)
{
printf("%i",intArray[i]);
printf(", ");
}
putchar('\n');
return 0;
}
Secondly, as my example illustrates above, it would be far better if you used an array to store the entered numbers.
So your basic idea is correct, but it could have been executed a little better.
Your else {minimum = minimum;} constructs are redundant BTW; the new minimum will only be set if the entered number is less than the current minmum, otherwise it's left alone by default. The else construct could be thought of as implicit...it doesn't really need to be declared.
I hope this makes some kind of sense. I'm trying.
@Mods: I hope this doesn't count as "doing the OP's homework", since I haven't actually provided a complete solution (at least I don't think). Maybe I'm just being overly helpful...
EDIT: Well crud...someone beat me to the punch.
Last edited by MrCode; 03-03-2011 at 08:53 PM.
Reason: cleaned up pointer-related redundancy
Here is the previous code I wrote using a while loop if it helps at all.
Perhaps I need spectacles, but I am unable to see any kind of loops in that long program you showed!
Anyway, there's no need for an array, you can compare the input numbers on the fly too,
1. Store the first input number in a variable.
2. Scanf the remaining input numbers in a for loop.
3. As you get a input number in the for loop, compare it with the one you stored in the variable.
4. If the stored number is greater than the newly received number, overwrite the stored value with the new number. At the end, the stored value will have the smallest number.
Code:
#include <stdio.h>
int main ()
{
int inputNumber;
int numberToBeCompared;
printf ("\nGo on:");
scanf ("%d", &inputNumber);
numberToBeCompared = inputNumber;
int i;
for (i = 0; i < 4; i++)
{
printf ("\nGo on:");
scanf ("%d", &inputNumber);
if (numberToBeCompared > inputNumber)
{
numberToBeCompared = inputNumber;
}
}
printf ("\nSmallest: %d\n" , numberToBeCompared);
}
Last edited by Aquarius_Girl; 03-03-2011 at 11:50 PM.
Anyway, there's no need for an array, you can compare the input numbers on the fly too,
1. Store the first input number in a variable.
2. Scanf the remaining input numbers in a for loop.
3. As you get a input number in the for loop, compare it with the one you stored in the variable.
4. If the stored number is greater than the newly received number, overwrite the stored value with the new number. At the end, the stored value will have the smallest number.
Another idea: get the list of numbers as arguments provided to the program (i.e. argv):
Code:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int main(int argc,char** argv)
{
int* numbers = malloc(argc * sizeof(int));
int minimum = atoi(argv[1]);
int i;
for(i = 1; i < argc; i++)
numbers[i] = atoi(argv[i]);
for(i = 2; i < argc; i++)
{
if(numbers[i] < minimum)
minimum = numbers[i];
}
printf("Smallest is %i\n",minimum);
free(numbers);
return 0;
}
(Tested; it works)
Last edited by MrCode; 03-04-2011 at 01:28 AM.
Reason: ugh...
Why you need to store these things in an array, can be done without that too
I dunno; working directly with the numbers just seems like it might be faster, as opposed to calling atoi every time you need a number from the argument list...?
I know I know...not that speed really *matters* in a tiny program like this, but I guess copying the numbers over into an array just feels somehow more straightforward. Plus, it's a good way to practice pointers.
Quote:
and did you try to run your program without any arguments?
Yeah, so I forgot to wrap it all in a if(argc > 1) block. It segfaults because it's trying to access a value pointed by an offset of numbers where nothing's there, right? I dunno...
I dunno; working directly with the numbers just seems like it might be faster, as opposed to calling atoi every time you need a number from the argument list...?
But you called the atoi function in your starting for loop, and I called it while comparing, both the ways it is called n times, where n is the number of user input numbers, so how does array help in speed?
Last edited by Aquarius_Girl; 03-04-2011 at 01:45 AM.
Anisha made the point that the OPs original "while loop" code didn't contain any loops.
How to tell the OP to get a better teacher or not practice self assessment?
Pseudo code for a single pass.
Code:
Current=Minimum=0
For i to 1 to 10 {
Read a number into N
Print it out.
If Current is equal to 0 then
Current <- 1
End If
If N < Minimum then
Minimun <- N
Next
Print "Mimimum :" Minimum
}
I did it preciously with a while loop but now I have to do it with a for loop.
If you had done it with a while loop, converting to a for loop would be trivial. But as others already commented, you didn't use any kind of loop.
It is hard to guess which basic concept(s) you don't understand yet, that make it hard for you to code that loop. I'm sure an explanation of concepts would do you more good than a sample program, but I don't know which concepts to explain. I'll take a guess and explain one concept anyway:
A variable in a program is typically not used for just one value. It gets assigned different values at different moments during the program execution. Your long version actually demonstrates partial understanding of that concept by having the variable minimum take on different values as the program progresses. But you demonstrate lack of understanding of that concept by having separate variables for number2, number3, number4, etc. You only ever use one of those values at a time, so logically those values could all share the same variable.
In the non loop form of the program sharing the same variable for all those values is a very minor cleanup. The important thing to see is that minor cleanup makes it more obvious how to change the long version into a loop version.
Quote:
Originally Posted by MrCode
Well, firstly, why not use [code][/code] tags?
j360 has been told that before. I hope he finally listens.
Quote:
like so:
I understand it is easier to just write and show the answer than to try to figure out what concepts the OP needs explained. But for these homework posts it really isn't appropriate to show the answer.
Also, I agree with Anisha Kaul regarding the actual answer (the simpler version without an array is much better).
Also, I agree with Anisha Kaul regarding the actual answer (the simpler version without an array is much better).
I agree 100%. Doing it without an array is much simpler. As far as we know from OP, the assignment parameters do not require storing the numbers anywhere.
Now that we know which solution is simpler I just have one question. How will he complete his C programming class without learning arrays?
When I took C programming class in college, I worked 2 weeks ahead of the lessons. Almost every assignment I exceeded the instructor's parameters. This allowed me to concentrate on the parts of the language I found more challenging. It also got me some attention from pretty girls who needed tutoring
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.