C/array

Advertisement


Question
how to create a program using array....for example.. make a program that would input five integers and output in ascending order..if i input...1,4,3,5,2(any numbers).. the output will be ...1,2,3,4,5... for the beginner like me..i would appriently need your help !

Answer
ydur, here is a simple example to get you started. It is up to you to write the sorting function. I have put explanations into the code. The code compiles and runs, but doesn't sort. It also doesn't do any error checking, but that is a more advanced subject anyway.

Best regards
Zlatko

#include <stdio.h>
#include <stdlib.h>

#define SIZE 5 /* define the array size */
int myArray[SIZE]; /* declare the array of integers */

void sort(void)
{
   /* sort the myArray
   This is left for you to do
   */
}

void printArray(void)
{
   /* print out the contents of myArray */
   int ix;
   for(ix = 0; ix < SIZE; ++ix)
   {
       printf("Item [%d] = %d\n", ix, myArray[ix]);
   }
}

int main(void)
{
   /* This loop gets SIZE (5) elements
   from the user. The input is stored in
   a character array of 64 characters. Then the
   atoi function is called to change the characters
   into an integer. No error checking is done to make
   sure the user entered valid characters and no error
   checking is done to make sure the user's input fits into
   the input buffer. With more experience you will know
   how to do that.
   */
   int ix;
   for(ix = 0; ix < SIZE; ++ix)
   {
       char input[64]; /*  choose an input buffer large enough */

       printf("Enter number %d :", ix);
       gets(input);
       myArray[ix] = atoi(input);
   }

   printf("The array is:\n");
   printArray();

   sort(); /* this is left for you to do */
   
   printf("The sorted array is:\n");
   printArray();
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.