Swapping elements in Arrays

This is a discussion on Swapping elements in Arrays within the C Programming forums, part of the General Programming Boards category; I have to do 2 things: 1). Make the program find the smallest number and place it at the top ...

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    61

    Swapping elements in Arrays

    I have to do 2 things:

    1). Make the program find the smallest number and place it at the top of the list.

    2). Make the program reverse the order of the elements in the list.
    __________________________________________________ _________
    I looked online and I followed this guide to swap the smallest number with the first value of the element.


    Code:
     printf("Array is now:");
           
                    temp = x[0];
                    x[0] = small;
                    small = temp;
    
            for(count = 0; count < amount; count++) {
                
                printf("\n x[%d] = %.2lf ",count,x[count]);
                        
            
            }
            printf("\n\n");
    But this is what happens when i run the program.

    http://i42.tinypic.com/34j1vew.png.

    And I'm not really sure how to do the 2nd part.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You didn't include the actual program -- are we supposed to just guess what is going on? The code you posted involves a correct swap [actually, not it doesn't], but none of the things being swapped are defined. Swapping things properly does not necessarily mean that you swapped the right things.

    Don't bother thinking about the second part until you get the first part to work. Post the actual program you used (not just random pieces of it).

    You don't throw a screenshot up. Just cut and paste.
    Last edited by MK27; 03-09-2012 at 04:52 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Mar 2012
    Posts
    61
    Sorry about that.

    Here is the whole program.

    Code:
    #include <stdio.h>
    #include <math.h>
    
    #define SIZE 100
    
    
    void main()
    {
    
    int count,choice,amount,temp;
    double x [SIZE],sum=0,average,small,large,stddev=0,sumofsquares=0,sdif=0,avgdev=0;
    
    do{
    do {
    printf("Select the desired operation:\n");
    printf("\t0 - Enter list of numbers\n");
    printf("\t1 - Find the average of the numbers\n");
    printf("\t2 - Find the smallest number\n");
    printf("\t3 - Find the largest number\n");
    printf("\t4 - Find the standard deviation of the numbers\n");
    printf("\t5 - Reverse the list of numbers\n");
    printf("\t6 - Place the smallest number at the top of the list\n");
    printf("\t7 - Exit the program\n");
    printf("Choice?");
    
    scanf("%d",&choice);
    flushall();
    if(choice < 0 || choice > 7)
        printf("Invalid operation.\n");
    }
    while(choice < 0 || choice > 7);
    
    
    switch (choice)
    {
        case 0:
            do {
                printf("How many numbers? ");
                flushall();
                scanf("%d", &amount);
                flushall();
                    if(amount < 2 || amount > SIZE)
                        printf("Amount must be a positive number between 2 and 100\n");
    
        } 
                while(amount < 2 || amount > SIZE);
    
            for(count = 0; count < amount; count++) {
    
                printf("x[%d] = ",count);
                flushall();
                scanf("%lf", &x[count]);
            }
            printf("\nThe Entered array is: ");
            for(count = 0; count < amount; count++) {
    
                
                printf("\n x[%d] = %.2lf ",count,x[count]);
                        
            
            }
            printf("\n\n");
    
            break;
    
            
        case 1:
            for (count = 0; count < amount; count++)
                sum = sum + x[count];
                average = sum / amount;
                printf("\nThe average is: %.2lf\n\n\n", average);
    
            break;
            
        case 2:
            small= x[0];
            for (count = 0; count <amount; count++){
                if (x[count] < small){
                    small = x[count];
                    }}
                printf("The smallest number is: %.2lf\n\n",small);
                            
            break;
    
        case 3:
            large= x[0];
            for (count = 0; count <amount; count++){
                if (x[count] > large){
                    large = x[count];
                    }}
                printf("The largest number is: %.2lf\n\n",large);
            break;
    
        case 4:
            for (count = 0; count <amount; count++){
                sdif =fabs(x[count]-average);
                printf("sdif is = %lf\n\n",sdif);
                sumofsquares = sumofsquares + sdif*sdif;
                printf("sumofsquares is = %lf\n\n",sumofsquares);
                }
    
            avgdev= fabs(sumofsquares/(amount-1));
            printf("avgdev is = %lf\n",avgdev);
            stddev= sqrt(avgdev);
    
            printf("Standard Deviation is = %.2lf\n\n",stddev);
                
                    
            break;
    
        case 5:
            printf("choice 5\n\n");
    
            break;
    
        case 6:
            printf("choice 6\n\n");
            
            printf("Array is now:");
    
    
                temp = x[0];
                x[0] = small;
                small = temp;    
                    
            
            
            for(count = 0; count < amount; count++) {
                    
                
                    
                
                printf("\n x[%d] = %.2lf ",count,x[count]);
                        
            
            }
            printf("\n\n");
                    
            
            break;
    
    
        case 7:
            printf("Good bye!");
            
    
    
    
    }
    }
    while(choice<7);
    
    getch();
    }

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    The problem is you assigned the value to small, but small is not part of the array. So you correctly assign the existing value in x[0] to temp, then the smallest value to x[0] -- but you have lost track of where the smallest value was, so you cannot replace it with the value from x[0] which is now in temp. Simply replacing small won't do that (and it may also screw up some other logic in the program).

    You could keep track with a pointer or index (and reassign that correctly when you move the smallest value) or you could just find it again and move it:

    Code:
    	int i, n[] = { 3, 2, 1}, pos = 0, tmp;
    
    	// find the index (position) of the smallest, not the value itself
    	for (i = 0; i < 3; i++)
    		if (n[i] < n[pos]) pos = i;
    
    	// now swap the value in that position with the first one
    	tmp = n[0];
    	n[0] = n[pos];
    	n[pos] = tmp;
    
    	// report
    	for (i = 0; i < 3; i++)
    		printf("%d ", n[i]);
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    Mar 2012
    Posts
    61
    That makes sense. I wasn't sure how the program would figure out the position of the smallest number.

    For the second part, I would have to switch :
    x[0] with x[n-1]
    x[1] with x[n-2]
    ...
    x[i] with x[n-i+1]

    I'm not sure how to write that. Since the amount of numbers can be from 2 to 100, I don't think using temps would work.

  6. #6
    Registered User
    Join Date
    Mar 2012
    Posts
    61
    I figured it out.

    I basically used the same thing
    Code:
    for (count = 0; count < lastindex/2; count++){
    
         
    
    temp = x[count];
    x[count] = x[lastindex-count];
    x[lastindex-count] = temp;
    Thanks for the help.

  7. #7
    Registered User
    Join Date
    Mar 2012
    Posts
    61
    I just realized that I'm not supposed to post my code because of the class policy. Would it be possible to remove it?

  8. #8
    Registered User
    Join Date
    Mar 2012
    Posts
    61
    I was reading through my syllabus for my class and it says "Stanford University’s Moss (for Measure Of Software Similarity) program will be used to detect software plagiarism". Does this mean that I will fail since I posted my code above?
    Last edited by november1992; 03-09-2012 at 09:05 PM. Reason: grammar

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by november1992 View Post
    I was reading through my syllabus for my class and it says "Stanford University’s Moss (for Measure Of Software Similarity) program will be used to detect software plagiarism". Does this mean that I will fail since I posted my code above?
    Maybe you should add a comment with a link to this thread. Or maybe you should ask your professor. Or maybe you could rewrite your code so it doesn't look exactly like it does now. Or maybe all of the above.


    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Registered User
    Join Date
    Mar 2012
    Posts
    61
    Well it's too late for me to modify my code since I submitted it. I'll email my professor. If he finds that it's unacceptable would it be possible to remove the code? I understand that I had an hour to change my post, but I don't want to get kicked out of school over this.

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by november1992 View Post
    I was reading through my syllabus for my class and it says "Stanford University’s Moss (for Measure Of Software Similarity) program will be used to detect software plagiarism". Does this mean that I will fail since I posted my code above?
    It doesn't hurt to ask (so ask), but I doubt they would discourage you from participating legitimately in programming forums -- that seems counter the goal of education, kind of like saying, "I don't want to find out any of you spent time in the library doing research". If I were your prof I'd say good for you.

    Plagiarism is the act of copying more-or-less verbatim without acknowledgement. I'm taking some CS courses right now, and we're allowed to incorporate code we did not write, as long as we explicitly credit the source. AFAICT tho, you haven't actually copied any code, you've just applied some very common, basic algorithms. But when in doubt, you can always add a comment:

    Code:
    /* 3-line swap of array elements using a temp variable
    from http://www.wherever/etc */
    Posting code publicly that you've written is not plagiarism, and shouldn't be an issue unless you, eg, start a blog, "GET YOUR ANSWERS TO HOMEWORK QUESTIONS FOR CS 101 HERE".
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #12
    Registered User
    Join Date
    Sep 2011
    Posts
    111
    Quote Originally Posted by november1992 View Post
    I was reading through my syllabus for my class and it says "Stanford University’s Moss (for Measure Of Software Similarity) program will be used to detect software plagiarism". Does this mean that I will fail since I posted my code above?
    First look up what plagiarism actually means. In short it is taking someone's work and saying it is your own. For example, you get an assignment to write a bubble sort, and you go to google and type in bubble sort in c, then find a bubble sort program, then you cut and paste that code and say it is yours.

    Posting your work on a site like this for help "should" be allowed, HOWEVER the catch 22 is if someone in your class sees your post and decides to snag it, use it, and turn it in as his or her own work. Then you submit your code and it is discovered you two have the same code, you both will get hit with the academic dishonesty clause. But each school and professor is different.

    I've had instructors who were perfectly fine with students looking over other student's code and helping each other, as in logic of a function and such, and I've had instructors who said, "You can work together to figure out what the problem is, but as soon as you figure out the solution of the problem you can no longer help," and the only people "allowed" to see our code is the TA or instructor only.

    The general rule about programing for college is, if you use it you should know the code you are using inside and out, meaning if you are asked any questions about your code you should be able to explain it. And comments will save your ass, because how do you use someone's work in a English paper, you cite their work on your work cited page, use your comments as your work cited page, for example lets say you are writing the program tetris (the full game) and you found online the way to rotate the blocks, it is as simple as saying the following

    Code:
    /*
     * ... blockRoation( ... )                       
     * This function rotates the tetris blocks
     * Algorithm was found at www.foo.zap 
     * //explain how the thing works and what it returns, etc
     **/
    As long as you understand and are able to explain how the code works and runs you should be in the clear, but it goes back to what does your instructor say. The thing about professors is they are human and remember what it is like to be in school, and 9.9 times out of 10 if you go to them first and tell them what's up, then they are more understanding and helpful then if they "discovered" what you did. Think about when you were younger, and you did something wrong at school. Did you get it worse if, you told your parents before the school did or if the school told your parents before you did?
    Last edited by Strahd; 03-10-2012 at 02:08 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. The puzzle again...Swapping elements of 2D array
    By crazygopedder in forum C Programming
    Replies: 44
    Last Post: 11-05-2008, 01:53 PM
  2. Replies: 12
    Last Post: 08-04-2008, 09:27 PM
  3. Help swapping 2 arrays
    By Boboki in forum C Programming
    Replies: 8
    Last Post: 03-03-2005, 06:07 AM
  4. Swapping Pointers & Arrays
    By bartybasher in forum C++ Programming
    Replies: 6
    Last Post: 10-25-2003, 03:17 PM
  5. swapping elements in a 2D array
    By axon in forum C++ Programming
    Replies: 9
    Last Post: 03-10-2003, 02:18 PM

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