Question

SIMPLE ASCENDING SORT, EXIT,FLOAT..... NEWBIE

Asked by: samkhool4u

i posted this question and i got replies which solved my problem... partly
here is the link
http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/Q_20646266.html
i am bringing this up because i deparately need a solution.
thanks for all ur efforts..
   
 i tried to impliment  reborn_assassin's program in to my program which is below
----------------------------------------------------------------------------------------------------------------------------------------------------------------

// AUTHOR--SAM
#include <iostream.h>
#include <fstream.h>

#include <conio.h>
//include <stdlib.h>



fstream datafile;
// declaring the file object so that it can communicate with the operating system

    int max=0,min=9999,i;
    float ave,sum2;
    long sum=0;
    int* contents;  // declares variable to read data from file
    char filename[16],words[80];
    double input;
    int keypress,anykey, count=0;

    void exit_prog()
    {
     cout<<"program terminated"<<endl;


    }
 //------------------- Welcom Screen Function-------------------//
    int welcome()
{
    gotoxy(15,5);
    cout<<"****************************************";
    gotoxy(15,6);
    cout<<"*\t\t   ------- COLLEGE\t     *";
    gotoxy(15,7);
    cout<<"*\t        FILE PROCESSING SYSTEM          *";
    gotoxy(15,8);
    cout<<"*\t\t PRESS C TO CONTINUE\t     *";
    gotoxy(15,9);
    cout<<"*                                      *";
    gotoxy(15,10);
    cout<<"****************************************";
    gotoxy(34,9);
    keypress=getche();
    stop:

return 0;
}
//----------------------Menu Screen Function----------------------//
int menu()
{  clrscr();
    gotoxy(15,5);
    cout<<"****************************************"<<endl;
    cout<<"\t      *\t\tFile Processing System\t     *"<<endl;
    cout<<"\t      *     \t  Please input option        *"<<endl;
    cout<<"\t      *                            \t     *"<<endl;
    cout<<"\t      * 1----------Create new data file      *"<<endl;
    cout<<"\t      * 2----------Input data to a file      *"<<endl;
    cout<<"\t      * 3----------View numbers form a file  *"<<endl;
    cout<<"\t      * 4----------Display maximum\t     *"<<endl;
    cout<<"\t      * 5----------Display minimum\t     *"<<endl;
    cout<<"\t      * 6----------Display total\t     *"<<endl;
    cout<<"\t      * 7----------Display the Average value *"<<endl;
    cout<<"\t      * 8----------Ascending sort \t     *"<<endl;
    cout<<"\t      * 9----------EXIT  \t\t     *"<<endl;
    cout<<"\t      *                            \t     *";
    gotoxy(15,18);
    cout<<"****************************************"<<endl;
    gotoxy(34,8);
    keypress=getche();

return 0;
}
//-------------OPTION 1 CREATE FILE---------------------------//
int create_file()
{
    // asking user to input name of the file to create
 cout<<"please enter the name of the file that you wish to create"<<endl;
 cout<<"use .txt as your file extension\n";

 cin>>filename;
 cout<<"\nA file named "<<filename<<" was created"<<endl;
 datafile.open(filename,ios::out);

 datafile.close(); // close file
return 0;
}


//-------------OPTION 2 INPUT DATA TO A FILE---------------------------//
int input_data()
{

// asking user to input name of the file to input data to
 cout<<"please enter the name of the file that you wish to input data to"<<endl;
 cout<<"please use the correct extension\n";

 cin>>filename;

     do
     {
         count++;
         datafile.open(filename,ios::app);
         clrscr();
         cout<<"input number";
         cin>>input;
         datafile<<input<<endl;
         datafile.close();
         cout<<("do you want to input another number... press anykey to continue or N to exit\n");

         keypress=getch();

         }while(keypress!=110&&keypress!=78);

         clrscr ();
         cout<<"You entered "<<count<<" numbers\n"<<endl;

return 0;

}
//-------------OPTION 3 VIEW DATA FORM A FILE---------------------------//
int view_file()
{

      // asking user to input name of the file from which the data needs to reviewed
 cout<<"please enter the name of the file which you wish to view the contents"<<endl;
 cout<<"please use the correct extension\n";
 cin>>filename;
    datafile.open(filename,ios::in);      // open numbers.txt file for reading

     while(!datafile.eof())  // keeps reading till the end of file
     {
         datafile.getline(words,80,'\n'); // read character by character form file ito words

         cout<<words<<endl;    // displays characters on the screen

     };

     datafile.close(); // close file
return 0;
};
//-------------OPTION 4 Maximum---------------------------//

int maximum()
{         contents= new int[count];
    datafile.open(filename,ios::in);      // opens numbers.txt file for reading
// displaying the contents of the file
    for(i=0;i<count;i++)  // keeps reading till the end of file
     {
         datafile>>contents[i]; // read character by character form file  ito words

         cout<<contents[i]<<endl;    // displays characters on the screen

     };

 // find and display max
    for(i=0;i<count;i++)
    {
                   if(contents[i]>max)
                        max=contents[i];
    }
    cout<<"max is "<<max<<"\n";

 datafile.close();
return 0;
}
//-------------OPTION 5 MINIMUM---------------------------//
int minimum()
{     contents= new int[count];
    datafile.open(filename,ios::in);      // opens numbers.txt file for reading
// displaying the contents of the file
    for(i=0;i<count;i++)  // keeps reading till the end of file
     {
         datafile>>contents[i]; // read character by character form file  ito words

         cout<<contents[i]<<endl;    // displays characters on the screen

     };
    //find and display min
    for(i=0;i<count;i++)
    {
         if(contents[i]<min)
              min=contents[i];
     }
     cout<<"min is "<<min<<endl;
 datafile.close(); // close file
    return 0;
}





//-------------OPTION 6 TOTAL---------------------------//
int total()
{
      contents= new int[count];
    datafile.open(filename,ios::in);      // opens numbers.txt file for reading
// displaying the contents of the file
    for(i=0;i<count;i++)  // keeps reading till the end of file
     {
         datafile>>contents[i]; // read character by character form file  ito words

         cout<<contents[i]<<endl;    // displays characters on the screen

     };
 // calcualte and display sum
    for(i=0;i<count;i++)
         sum=sum+contents[i];

    cout<<"sum is "<<sum<<"\n";

    datafile.close(); // close file
return 0;
}

//-------------OPTION 7 AVERAGE---------------------------//
int average()
{     contents= new int[count];
    datafile.open(filename,ios::in);      // opens numbers.txt file for reading
// displaying the contents of the file
    for(i=0;i<count;i++)  // keeps reading till the end of file
     {
         datafile>>contents[i]; // read character by character form file  ito words

         cout<<contents[i]<<endl;    // displays characters on the screen

     };
    // calclate and display average
    sum=sum2;
    ave=sum2/count;
    cout<<"average is "<<ave<<endl;
    datafile.close(); // close file
return 0;
}
//-------------OPTION 8 SORT---------------------------//
int sort()
{
         char ans;
         contents= new int[count];
         int tp, i, j, total;
         total =  sizeof(contents)/4; // Meaning you can change the size of the array
         for (i=1; i<=total-1; i++)
              {
              for (j=i+1; j<=total; j++)
                   {
                     if (contents[i] > contents[j])
                        {
                              tp = contents[i];
                              contents[i] = contents[j];
                              contents[j] = tp;
                        }
                   }
              }
     for (i=1; i<=total; i++)
                   cout << endl << contents[i];
     cin >> ans;

return 0;
}


//-------------MAIN PROGRAM---------------------------//

int main()
{

    welcome();
    while(keypress!=67||keypress!=99)
    {
         if (keypress==99||keypress==67)
         {
              menu();
              while(keypress!=49||keypress!=50||keypress!=51||keypress!=52||keypress!=53||
                        keypress!=54||keypress!=55||keypress!=56||keypress!=57)
              {
                   if(keypress==49||keypress==50||keypress==51||keypress==52||keypress==53||
                        keypress==54||keypress==55||keypress==56||keypress==57)
                        {
                             if(keypress==49)
                                  {            //----- OPTION 1------//
                                       clrscr();
                                       create_file();
                                       cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                       anykey=getch();
                                   }
                             if(keypress==50)
                                  {          //----- OPTION 2------//
                                  clrscr();
                                  input_data();
                                  cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                  anykey=getch();
                                  }
                             if(keypress==51)
                                  {            //----- OPTION 3------//
                                  clrscr();
                                  view_file();
                                  cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                  anykey=getch();
                                  }
                             if(keypress==52)
                                  {            //----- OPTION 4------//
                                  clrscr();
                                  maximum();
                                  cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                  anykey=getch();
                                  }
                             if(keypress==53)
                                  {           //----- OPTION 5------//
                                  clrscr();
                                  minimum();
                                  cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                  anykey=getch();
                                  }
                             if(keypress==54)
                                  {           //----- OPTION 6------//
                                  clrscr();
                                  total();
                                  cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                  anykey=getch();
                                  }
                             if(keypress==55)
                                  {          //----- OPTION 7------//
                                  clrscr();
                                  average();
                                  cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                  anykey=getch();
                                  }
                             if(keypress==56)
                                  {         //----- OPTION 8------//
                                  clrscr();
                                  sort();
                                  cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                  anykey=getch();
                                  }
                             if(keypress==57)
                                  {        //----- OPTION 9------//
                                  clrscr();
                                  cout<<"\a"<<endl;
                                  cout<<"Thank you for using our program"<<endl;
                                  cout<<"We hope you enjoyed it";

                                  cout<<"\n\n\t\t\tPress Any Key exit the program";
                                  anykey=getch();
                                  break;

                                                       //exit(0);
                                  }

                         }


                   cout<<"\a";
                   clrscr();
                   menu();
              }// end while of menu validation
         }

         cout<<"\a";
         clrscr();
         welcome();

    }//end while of welcome validation

return 0;
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------
there are 3 problem with my program...
1) the sort code provided by reborn_Assasin---- i ttried but i could'nt integrate his proram into mine.. i tried to look for the problem but iam having difficulty.
2) the exit function dosent work..  in the opt9.. i tried to puta  break; but  it only goes back to the welcome screenn. .
also i tried to put exit(0);  there fore included stdlib.h as header.. but for no apparent reason it gives me  9 errors.. . please could soemone  provide me with a solution for this.
3) the average option---.  initially  my ave was an int .which gave me an int value. .but when i changed it to float .all it gives me is 0..(i wanted a decimal value)
 please help
 thank you..

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-06-15 at 09:41:48ID20648770
Tags

ascending

,

gotoxy

,

meaning

,

sort

Topic

C++ Programming Language

Participating Experts
1
Points
280
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. void pointers
    Hi, Im having difficulties working with void pointer arguments and doubly linked lists containing data fiels of type void *. The below code works well with structures and strings, however, floats and ints escape me. the functions are to be generic, in that they are to be abl...
  2. Sort in Ascending order then write to a file
    hi! iam trying to sort numbers form an array in ascending order.. and then writing them to a file or on to a new array. for e.g if i have an array of [ 5,6,2,7,4,3,54,133] i want to sort them in ascending order ... any help will be appreciated thankyou

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ExceterPosted on 2003-06-15 at 13:48:12ID: 8727987

You should consider using a global namespace instead of the .h headers as they are not standard. For example, instead of,

>> #include <iostream.h>
>> #include <fstream.h>
>> #include <conio.h>

you should say,

#include <iostream>
#include <fstream>
#include <conio.h>

using namespace std;

>> 1) the sort code provided by reborn_Assasin---- i ttried but i could'nt integrate his proram into mine.. i tried to look for the
>> problem but iam having difficulty.

If you really want a sort you should use std::sort as it is easier to use. For example,

#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;

int main()
{
      vector <int> data;
      unsigned int x;

      srand( (unsigned)time( NULL ) );

      for( x = 0; x < 15; x++ ) // Fill the vector with 15 random values
            data.push_back( rand() );

      sort( data.begin(), data.end() ); // Sort the vector

      for( x = 0; x < data.size(); x++ ) // Display the vector
            cout << data[x] << endl;

      return 0;
}

The problem with your current sort is that you are creating a new array inside the sort function and you are not populating it with the data from the file. I would suggest you change the sort function to look more like this,

int sort()
{
      datafile.open(filename,ios::in);
      vector <int> data;
      int num;

      if( !datafile )
            cout << "Error! The file was not found." << endl;
      else
      {
            cout << "Before sort," << endl;

            while( datafile >> num )
            {
                  cout << num << endl;
                  data.push_back( num );
            }
            cout << endl << "After sort," << endl;
            sort( data.begin(), data.end() );

            for( unsigned int x = 0; x < data.size(); x++ )
                  cout << data[x] << endl;
      }

      datafile.close();

      return 0;
}

>> 2) the exit function dosent work..  in the opt9.. i tried to puta  break; but  it only goes back to the welcome screenn. .
>> also i tried to put exit(0);  there fore included stdlib.h as header.. but for no apparent reason it gives me  9 errors.. .
>> please could soemone  provide me with a solution for this.

Strange, exit(0); should be working. However, the code for option 9 is in main, the following will work.

if(keypress=='9')
{        //----- OPTION 9------//
    clrscr();
    cout<<"\a"<<endl;
    cout<<"Thank you for using our program"<<endl;
    cout<<"We hope you enjoyed it";

    cout<<"\n\n\t\t\tPress Any Key exit the program";
    anykey=getch();
    return 0;
}

What errors was it giving you?

>> 3) the average option---.  initially  my ave was an int .which gave me an int value. .but when i changed it to float .all it
>> gives me is 0..(i wanted a decimal value)

This feature will give you an access violation if you do not specify a datafile, you have a memory leak inside the average function, and the reason you are not getting the averge is simply that you are not tallying up the values you read from the file. Therefore, the average function should look more like this,

int average()
{
      datafile.open(filename,ios::in);

      count = sum = 0;

      if( !datafile )
            cout << "Error! The file was not found." << endl;
      else
      {
            while( datafile >> sum2 )
            {
                  cout << sum2 << endl;
                  sum += sum2;
                  count++;
            }
            ave = (float)sum / (float)count;
            cout << endl << "The average is: " << ave << endl;
      }

      datafile.close();

      return 0;
}

Cheers!
Exceter

 

by: ExceterPosted on 2003-06-15 at 13:49:59ID: 8727991

Note: You will have to include vector for my examples to work. For example,

#include <vector>

Exceter

 

by: ExceterPosted on 2003-06-15 at 15:38:11ID: 8728294

If you are getting errors similar to these,

Error E2356 C:\CPP\BigNumbers\BigInteger\test.cpp 7: Type mismatch in redeclaration of 'std::max<>(const _T &,const _T &)'
Error E2449 C:\CPP\BigNumbers\BigInteger\test.cpp 7: Size of 'std::max<>(const _T &,const _T &)' is unknown or zero
Error E2356 C:\CPP\BigNumbers\BigInteger\test.cpp 7: Type mismatch in redeclaration of 'std::min<>(const _T &,const _T &)'
Error E2449 C:\CPP\BigNumbers\BigInteger\test.cpp 7: Size of 'std::min<>(const _T &,const _T &)' is unknown or zero

the problem is that you have created global varaibles named min and max which are conflicting with std::max and std::min. To fix this, you should rename them.

Exceter

 

by: ExceterPosted on 2003-06-16 at 10:31:38ID: 8733490

samkhool4u?

 

by: samkhool4uPosted on 2003-06-16 at 11:42:07ID: 8734088

hey Exceter!!
 sorry for the late reply
i tried all ur above solutions
   the average and exit functions are working fine.. thank you..
 the average function works fine but..when compiled it gives me

1.)>>>>  no module definition file  specified:using defaults  
at this line >>>>>>>    count = sum = 0;  
    should i just ignore it..... or ....???


2.) whenever i try to compile with ur suggested  sort program .. it gives me error messages..
 
this  using namespace std; .. its not working with my compiler(it gives me syntax error mssg)..

and also that it cannot locate the vector.h  header file.. its nowhere.. i tried  searching for it by myself but i couldnt find it.
   i tried putting  #include<vector>   as  #include<vectro.h>   with out  namespace std..  but it says cant open/locate the header file

iam using borland c++ 4.52

  i search for the vector.h on the net.. found it.. put it in header folder.. compiled it..
and it says " unable to open include file...  matrix.h>
 then i searched for it....... and  compiled it  now it wants  GML.h and istream
 
what in the world is goin on.......
!£"$"£%^£"^£^£%^£$^£&(*^&
 please advice......
 thank you.

 

by: samkhool4uPosted on 2003-06-16 at 12:25:26ID: 8734411

if u could suggest some other method for sorting other than vector and namespace std..  then that will be a gr8 help.. thank you :)

 

by: ExceterPosted on 2003-06-16 at 13:12:08ID: 8734795

Sure, I can modify that example to use a bubblesort, which you were using before. For example,

int sort()
{
      datafile.open(filename,ios::in);
      int* data = new int[100]; // If you know the size you will need, substitute 100 for that value
      int num = 0, temp;

      if( !datafile )
            cout << "Error! The file was not found." << endl;
      else
      {
            cout << "Before sort," << endl;

            while( datafile >> data[num] )
            {
                  cout << data[num] << endl;
                  num++;
            }

            cout << endl << "After sort," << endl;

            for( int x = 0; x < num; x++ )
            {
                  for( int y = 1; y < num; y++ )
                  {
                        if( data[y] < data[y - 1] )
                        {
                              temp = data[y];
                              data[y] = data[y - 1];
                              data[y - 1] = temp;
                        }
                  }
            }

            for( int x = 0; x < num; x++ )
                  cout << data[x] << endl;
      }

      delete[] data;
      datafile.close();

      return 0;
}

However, your problem with my examples is that your compiler appears to be an older version of Borland's C++ compiler which does not support the current standard. If this is the case, I would suggest you get a different compiler. If you decide to follow this path, you can download Borland's C/C++ v5.5 compielr for free.

Exceter

 

by: samkhool4uPosted on 2003-06-17 at 06:00:09ID: 8739977

thanks man
  the sort functiom works like a charm ;)
   
one last thing
   could u please explain ur sort funciton's  these line to me
 
for( int x = 0; x < num; x++ )
         {
              for( int y = 1; y < num; y++ )
              {
                   if( data[y] < data[y - 1] )
                   {
                        temp = data[y];
                        data[y] = data[y - 1];
                        data[y - 1] = temp;
                   }
              }

oh and  what is the syntax to flush the contents  of any array
eg. .this
  int* data = new int[100];
   or this
contents= new int[count];
   how can i flush their data.. so when the loop starts again it is fresh...

  once again thank you for all ur effort.. i really appreciate it :)
sam

 

by: samkhool4uPosted on 2003-06-17 at 06:02:06ID: 8739991

iam increasin the points form 200 to 280...
  thanks
   :)

 

by: ExceterPosted on 2003-06-17 at 06:21:30ID: 8740141

>> for( int x = 0; x < num; x++ )
>>         {
>>              for( int y = 1; y < num; y++ )
>>              {
>>                   if( data[y] < data[y - 1] )
>>                   {
>>                        temp = data[y];
>>                        data[y] = data[y - 1];
>>                        data[y - 1] = temp;
>>                   }
>>              }
>> }

The first loop iterates once for every element in the array. The second loop, which runs every time the other loop iterates, starts at index 1 and continues looping until it has reached the last data element. Aloing the way, it compares the current value to the previous value. If the previous value is greater than the current value, they are swapped. Therefore, we can be assured that once the first loop iterates once, that the largest value has been moved to the highest index. On the second iteration of the first loop we can be ceratin that the second largest value has been sorted. Therefore, the sort can be optimized by saying,

for( int x = 0; x < num; x++ )
{
    for( int y = 1; y < num - x; y++ )
    {
        if( data[y] < data[y - 1] )
        {
            temp = data[y];
            data[y] = data[y - 1];
            data[y - 1] = temp;
        }
    }
}

>> oh and  what is the syntax to flush the contents  of any array
>> eg. .this
>> int* data = new int[100];
>>  or this
>> contents= new int[count];

You have to manually reset their values. You could reload the data from disk or you could simply assign an arbitrary value to each element. For example, to set all elements to the same value,

for( int x = 0; x < count; x++ )
    contents[x] = 0;

or,

for( int x = 0; x < 100; x ++ )
    data[x] = 0;

If you want the data read from disk again, simply repeat the process I used in the beginning of the sort function.

Exceter

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...