Thread: why there's a difference between the 'while' and 'if' in this code

  1. #1
    Registered User
    Join Date
    Aug 2014
    Posts
    26

    why there's a difference between the 'while' and 'if' in this code

    this code is showing the min value .
    with the while loop its working fine- the min is 2
    if you replace the 'while' with 'if' the min is 33 which is wrong.

    i tried to write myself the iterations. i got little confused.
    also if i check the max value instead of min its working fine with if.

    Code:
     #include <stdio.h>
    int main(){
    
    int number[] = {35,32,21,4,33,43,2};
    
    
    int i, j , k ,min;
    i= 0 ; j=6; k = 0;  //j = the end of the array
                               //k = start of the array
    
    
    for(; i<=j; i++){
     while(number[k]>number[0+i]) //put 'if' is wrong.why?
    {
    k++;
     }
    }
    min=number[k]; 
    printf("min=%d",min);
    
    
    
    return0;
    
    } 

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Because you wrote the for loop in a very strange way.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    120
    The correct statement would be:
    Code:
    if (number[k] > number[i])
    {
        k = i;
    }

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    why do you need k at all?
    Code:
    if(min_val > number[i])
    {
       min_val = number[i];
    }
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  5. #5
    Registered User zub's Avatar
    Join Date
    May 2014
    Location
    Russia
    Posts
    104
    Code:
    int find_min(const int* arr, unsigned int siz)
    {
        assert(arr && siz);
        int min = *arr;
        while( --siz ) {
            ++arr;
            if( *arr < min ) { min = *arr; }
        }
        return min;
    }
    Our goals are clear, tasks are defined! Let's work, comrades! -- Nikita Khrushchev

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Code Difference for OS X and Windows
    By Bharat1987 in forum C Programming
    Replies: 8
    Last Post: 09-04-2013, 05:20 AM
  2. Difference.
    By Kitt3n in forum C++ Programming
    Replies: 8
    Last Post: 07-19-2010, 09:25 AM
  3. difference
    By kiranck007 in forum C Programming
    Replies: 1
    Last Post: 01-26-2006, 02:54 AM
  4. Difference b/w int* p1 and int *p1
    By pprabhakar in forum C Programming
    Replies: 16
    Last Post: 08-21-2005, 05:27 AM
  5. Replies: 1
    Last Post: 01-10-2003, 10:08 PM