LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 03-03-2011, 08:06 PM   #1
j360
Member
 
Registered: Jan 2010
Location: Maryland
Distribution: Ubuntu
Posts: 58

Rep: Reputation: 0
Cool C programming help


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);

printf("enter another integer\t");
scanf("%d", &number2);
if(number1 < number2){
minimum = number1;
}

else {
minimum = number2;
}


printf("enter another integer\t");
scanf("%d", &number3);
if(number3 < minimum){
minimum = number3;
}


else {
minimum = minimum;
}

printf("enter another integer\t");
scanf("%d", &number4);
if(number4 < minimum){
minimum = number4;
}
else {
minimum = minimum;
}

printf("enter another integer\t");
scanf("%d", &number5);
if (number5 < minimum) {
minimum = number5;
}
else {
minimum = minimum;
}

printf("enter another integer\t");
scanf("%d", &number6);
if (number6 < minimum){
minimum = number6;
}
else {
minimum = minimum;
}

printf("enter another integer\t");

scanf("%d", &number7);
if (number7 < minimum) {
minimum = number7;
}
else{
minimum = minimum;
}

printf("enter another integer\t");
scanf("%d", &number8);
if (number8 < minimum) {
minimum = number8;
}
else {
minimum = minimum;
}

printf("enter another integer\t");
scanf("%d", &number9);
if (number9 < minimum)
minimum = number9;
else {
minimum = minimum;
}

printf("enter your final integer\t");
scanf("%d", &number10);
if (number10 < minimum)
minimum = number10;
else {
minimum = minimum;
}


printf("the smallest integer is %d\n", minimum);
return 0;
 
Old 03-03-2011, 08:17 PM   #2
Telengard
Member
 
Registered: Apr 2007
Location: USA
Distribution: Kubuntu 8.04
Posts: 579
Blog Entries: 8

Rep: Reputation: 148Reputation: 148
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
 
Old 03-03-2011, 08:32 PM   #3
MrCode
Member
 
Registered: Aug 2009
Location: Oregon, USA
Distribution: Arch
Posts: 864
Blog Entries: 31

Rep: Reputation: 148Reputation: 148
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
 
1 members found this post helpful.
Old 03-03-2011, 08:43 PM   #4
Telengard
Member
 
Registered: Apr 2007
Location: USA
Distribution: Kubuntu 8.04
Posts: 579
Blog Entries: 8

Rep: Reputation: 148Reputation: 148
Quote:
Originally Posted by MrCode View Post
EDIT: Well crud...someone beat me to the punch.
I was surprised I managed to get in first. It was low hanging fruit anyway.

I do think your critique of the provided examples is spot on though.
 
Old 03-03-2011, 08:49 PM   #5
MrCode
Member
 
Registered: Aug 2009
Location: Oregon, USA
Distribution: Arch
Posts: 864
Blog Entries: 31

Rep: Reputation: 148Reputation: 148
Quote:
I do think your critique of the provided examples is spot on though.
Thanks.

I'm kind of a C n00b myself (although I didn't used to be; got out of practice ), but glad to know that I've still got the dirt basics down.

Again, I hope the code I provided doesn't count as doing the work for the OP...I was just trying to illustrate an example.
 
Old 03-03-2011, 11:46 PM   #6
Aquarius_Girl
Senior Member
 
Registered: Dec 2008
Posts: 4,731
Blog Entries: 29

Rep: Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940
Quote:
Originally Posted by j360 View Post
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.
 
1 members found this post helpful.
Old 03-04-2011, 01:03 AM   #7
MrCode
Member
 
Registered: Aug 2009
Location: Oregon, USA
Distribution: Arch
Posts: 864
Blog Entries: 31

Rep: Reputation: 148Reputation: 148
Quote:
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...
 
Old 03-04-2011, 01:25 AM   #8
Aquarius_Girl
Senior Member
 
Registered: Dec 2008
Posts: 4,731
Blog Entries: 29

Rep: Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940
Why you need to store these things in an array, can be done without that too, and did you try to run your program without any arguments?
Code:
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char **argv)
{
     if (argc > 1)
     {
	  int i;
	  int minimum = atoi (argv[1]);
	  
	  for (i = 2; i < argc; i++)
	  {
		    if (minimum > atoi (argv[i]))
		    {
			 minimum = atoi (argv[i]);
		    }
	  }
	  printf ("Minimum: %d", minimum);
     }
     else
     {
          printf ("Minimum: %d", atoi (argv[1]);
     }
     return 0;
}

Last edited by Aquarius_Girl; 03-04-2011 at 01:29 AM.
 
Old 03-04-2011, 01:35 AM   #9
MrCode
Member
 
Registered: Aug 2009
Location: Oregon, USA
Distribution: Arch
Posts: 864
Blog Entries: 31

Rep: Reputation: 148Reputation: 148
Quote:
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...

...and I wonder what happened to the OP?
 
Old 03-04-2011, 01:43 AM   #10
Aquarius_Girl
Senior Member
 
Registered: Dec 2008
Posts: 4,731
Blog Entries: 29

Rep: Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940
Quote:
Originally Posted by MrCode View Post
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.
 
1 members found this post helpful.
Old 03-04-2011, 01:46 AM   #11
MrCode
Member
 
Registered: Aug 2009
Location: Oregon, USA
Distribution: Arch
Posts: 864
Blog Entries: 31

Rep: Reputation: 148Reputation: 148
I'm stupid...okay fine, whatever. Your way's probably better, as it uses less memory, I guess.

I guess I need to do some more reading up/practicing...
 
Old 03-04-2011, 01:49 AM   #12
Aquarius_Girl
Senior Member
 
Registered: Dec 2008
Posts: 4,731
Blog Entries: 29

Rep: Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940
Quote:
Originally Posted by MrCode View Post
I'm stupid...okay fine, whatever. Your way's probably better, as it uses less memory, I guess.
I didn't mean to upset you, I am sorry if I have, and you are not stupid at all. These discussions just clear off the doubts, in any!
 
Old 03-04-2011, 07:11 AM   #13
AnanthaP
Member
 
Registered: Jul 2004
Location: Chennai, India
Posts: 952

Rep: Reputation: 217Reputation: 217Reputation: 217
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
}
 
Old 03-04-2011, 07:40 AM   #14
johnsfine
LQ Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,286

Rep: Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197
Quote:
Originally Posted by j360 View Post
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 View Post
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).

Last edited by johnsfine; 03-04-2011 at 07:45 AM.
 
1 members found this post helpful.
Old 03-04-2011, 09:32 AM   #15
Telengard
Member
 
Registered: Apr 2007
Location: USA
Distribution: Kubuntu 8.04
Posts: 579
Blog Entries: 8

Rep: Reputation: 148Reputation: 148
Quote:
Originally Posted by johnsfine View Post
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
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:27 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration