C++ Programming/Exercises/Static arrays

< C++ Programming < Exercises

Static arrays

EXERCISE 1

Write a program that asks the user to type 10 integers of an array. The program must compute and write how many integers are less than or equal to 10.

Solution

Solution #1

#include <iostream>
#include<conio.h>
void main()
{
    int a[10],i,b=0;
    cout<<"enter the array\n";
    for(i=0;i<N;i++)
    {
      cin>>a[i];
      if (a[i]>=10)
      b++;   
    }

    cout<<"the number of integers greater or equal to 10 is: "<<b;
    getch();
}


Solution #2

//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;

#define X 10
//---------------------------------------------------------------------------
void outputFunc(int array[]);

int testFunc(int array[]);

void inputFunc(int array[]);

int main(int argc, char* argv[])
{  int array[X];

   inputFunc(array);

   outputFunc(array);

   system("pause");
   return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int array[])
{  cout << "Please enter " << X << " integer elements of an array.\n" << endl;
   for(int count = 0; count < X; ++count)
   {  cout << "array[" << count << "]: ";
      while(! (cin >> array[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array[" << count << "]: ";
      }
      fflush(stdin);
   }
}

int testFunc(int array[])
{  int count = 0;

   for(int i = 0; i < X; ++i)
      if(array[i] >= 10)
         ++count;

   return count;
}

void outputFunc(int array[])
{  cout << "\n\tYou entered " << testFunc(array) << " integers greater than or equal to"
        << " 10.\n" << endl;
}

Solution #3

//by blazzer12
//input 10 integers and print number of integers grater than or equal to 10

#include <iostream>

using namespace std;

int main()
{
	const int limit = 10;
	int list[10], count=0;
	
	cout<<"Enter 10 integers :"<<endl;
	
	for(int i=0; i<limit; i++)
	{
		cout<<"Enter Number "<<i+1<<" :";
		
		cin>>list[i];
		
		(list[i]<10) ? : count++; //observe closely and if needed, recall the syntax of ?: operator
	}
	
	cout<<"Number of interger(s) greater than 10 = "<<count;
}

Solution #4

#include <iostream>
using namespace std;

int main () {
    int i; //"for" loop counter 
    //EXERCISE 1
    int cinArray1; //integer value of array indexes
    int overTen = 0; //integer value of the amount of numbers in the array that are greater than ten, starts of at 0 as we do not know yet
    int array1[10]; //array of 10 integers
    cout << "Enter 10 numbers for array1. ";
    for (i = 0; i < 10; i++) { //for loop to gather data
        cout << "Enter number " << (i + 1) << ": ";
        cin >> cinArray1;
        array1[i] = cinArray1; }
    for (int j = 0; j < 10; j++) {
        if (array1[j] > 10) {
            overTen++;}
        }
    cout << "There are " << overTen << " numbers in array1 that are greater than ten.";
    cin.get();
    cin.get();

Solution #5:

#include <iostream>
using namespace std;
int main()
{
	int arr[10], n,greaterIntergers = 0;

	for (n = 0; n < 10; n++) {
		cout << "Input an Interger ";
		cin >> arr[n];

		if (arr[n] >= 10) {
			greaterIntergers++;
		}
	}

	cout << greaterIntergers << " intergers are greater than or equals to 10" << endl;

	return 0;
}

Solution #6:

/* Note by editor GReaperEx:
   This program uses pre-standard/really old code,
   therefore its use is discouraged. Please try using
   newer/standard code instead.                       */

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

void main()
{
    int no[10],i,c=0;
    for(i=0;i<10;i++)
    {
        cin>>no[i];
        if(no[i]>=10)
            c++;
    }
    cout<<"Number Greater or Equal to 10 are"<<c;
    getch();
}

Solution #7:

#include <iostream>
using namespace std;

void searching(int[]);
void printarray(int[]);
void main() {

	int array[10];
	
	cout << "Enter 10 integers: ";

	for (int x = 0; x < 10; x += 1) {
		cout << "Enter the " << x + 1 << "'st element: ";
		cin >> array[x];
	}
	searching(array);
	printarray(array);
}
void searching(int a[]) {
	int total = 0;
	for (int i = 0; i < 10; i += 1) {
		if (a[i] <= 10) {
		total = total + 1;
		}
	}
	cout << "there is a total of " << total << " less or equal to 10!" << endl;
}
void printarray(int a[]) {

	cout << "the number entered are: ";
		for (int j = 0; j < 10; j += 1) {
			cout <<"\t"<<a[j];
		}
}


EXERCISE 2

Write a program that asks the user to type 10 integers of an array and an integer V. The program must search if V is in the array of 10 integers. The program writes "V is in the array" or "V is not in the array".

Solution

Solution #1

#include <iostream>

using namespace std;

const int N = 10;

int main ()
{
    int t[N], i=0, V;
    

    for (i = 0; i < N; i++)
    {
        cout << "Type an integer: ";
        cin >> t[i];
    }

    cout << "Type the value of V: ";
    cin >> V;

    for (i = 0; i < N; i++)
    {
        if (t[i] == V)
        {
          cout << "V is in the array" << endl;
          return 0;
        }
    }
    
    cout << "V is not in the array" << endl;

    return 0;
}

Solution #2

#include <iostream>
using namespace std;

int main(void)
{
	int V,input[10];
	bool equalsV(false);

	cout << "Type the value of V: ";
	cin >> V;

	for(int currentBlock(0); currentBlock < 10; currentBlock++)
	{
		cout << "Enter input[" << currentBlock << "]: ";
		cin >> input[currentBlock];

		if (input[currentBlock] == V)
			equalsV = true;
	}

	cout << "V is ";
	if (!equalsV)
		cout << "not ";
	cout << "in the array" << endl;

	system("PAUSE");
	return 0;
}

Solution #3

//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;

#define X 10
//---------------------------------------------------------------------------
void outputFunc(int array[], int V);

bool testFunc(int array[], int V);

void inputFunc(int array[], int& V);

int main(int argc, char* argv[])
{  int V, array[X];

   inputFunc(array, V);

   outputFunc(array, V);

   system("pause");
   return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int array[], int& V)
{  cout << "Please enter " << X << " integer elements of an array.\n" << endl;
   for(int count = 0; count < X; ++count)
   {  cout << "array[" << count << "]: ";
      while(! (cin >> array[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array[" << count << "]: ";
      }
      fflush(stdin);
   }

   cout << "\nNow, enter the integer, \"V\": ";
   while(! (cin >> V) )
   {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
      cin.clear();
      cin.ignore(10000, '\n');
      cout << "Enter the integer, \"V\": ";
   }
   fflush(stdin);
}

bool testFunc(int array[], int V)
{  int isIn = 0;

   for(int count = 0; count < X; ++count)
      if(array[count] == V)
         isIn = 1;
   if(isIn == 1)
      return true;
   else
      return false;
}

void outputFunc(int array[], int V)
{  cout << "\nV is ";

   if(! (testFunc(array, V) ) )
      cout << "not ";
   cout << "in the array.\n" << endl;
}

Solution #4

// by blazzer12
// input 10 integers into an array. Find if an integer(that is input by user) is in the array.
#include<iostream>
#include<conio.h>

using namespace std;

int main()
{
	int arrNum[10], V, count=0;
	bool found=false;
	
	while(count<10)
	{
		cout<<"Enter Number "<<count+1<<" : "; //count+1 because it prints from 1,2,3..  not from 0. Value of count is not affected
		cin>>arrNum[count++]; // post increaments count by one
	}
	
	cout<<"Enter a Number (V) : ";
	cin>>V;
	
	for(int i=0; i<10; i++)
		if(arrNum[i]==V)
		{
			found = true;
			break; // gets out of loop after V is found; no need to run the remaining iterations :)
		}
			
	if(found)
		cout<<"V is in the array";
	else
		cout<<"V is not in the array";
}

Solution #5

//By iCheats--------------------------------------------------------------//>
#include <iostream>

using namespace std;

//variables
int basArray[10];
int askNum;
int V;
bool youWin = false;

int main()
{
	while(1)
	{
		for (int f = 0; f < 10; f++)
		{
			cout << "Type a number: ";
			cin >> basArray[askNum];
		}

		cout << "Enter number to guess!!";
		cin >> V;

		for (int n = 0; n < 10; n++)
			if (basArray[n] == V)
			{
				youWin = true;
				break; // found match, don't check any more
			}

		if (youWin)
		{
			cout << "V is in the array";
			break; // exit program
		}
		else
		{
			cout << "V is not in the array";
		}
	}

	return 0;
}

Solution #6

#include <iostream>
using namespace std;
int main()
{
	int arr[10], intergerV, n;
	bool inArray;
	cout << "Type an Interger: (it will be labaled Integer V): ";
	cin >> intergerV;
	for (int n = 0; n < 10; n++) {
		cout << "Type an integer: ";
		cin >> arr[n];
	if (intergerV == arr[n]) {
			inArray = true;
		}		
}
	if (inArray)
		cout << "Interger V is in the Array";
	else
		cout << "Integer V is not in the Array";
		
	return 0;
}
by MAK JUNIOR


#include <iostream>
#include <stdio.h>

using namespace std;

int main() {

	int v = 0, ar[10]; bool flag = false;

	printf("Enter a value for the variable V\n");
	cin >> v;
	cout << "enter values for the array"<< endl;

	for (int i = 0; i < 10; ++i)
	{
		cin >> ar[i];
		if (ar[i] == v)
			flag = true;
			break;
	}
	flag  ? cout << "match" : cout << "mismatch";

	cout << endl;

}


EXERCISE 3

Write a program that asks the user to type 10 integers of an array. The program must output the largest element in the array, and the index at which that element was found.

Solution

Solution #1

#include <iostream>
using namespace std;

const int N=10;
int main()
{
    int t[N],i,index;

    for(i=0;i<N;i++)
    {
        cout << "Type an integer";
        cin >> t[i];
    }
    index=0;
    for(i=1;i<N;i++)
	if(t[index]<t[i])
            index=i;

    cout << "The greatest element of the array is: "
         << t[index] << " (index " << index << ")" << endl;
    return 0;
}

Solution #2

#include <iostream>
using namespace std;

int main()
{
      int index = 0, nb = 0;
      int arr [10];
      
      for ( int i = 0; i < 10;  i++)
      {
          cout << "Type an integer ";
          cin >> arr[i];
          if (arr[i] > nb) 
          { 
            nb = arr[i];
            index = i;
          }
      }
      cout << index;
      return 0;
}

Solution #3

//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;

#define X 10
//---------------------------------------------------------------------------
void outputFunc(int array[]);

int testFunc(int array[]);

void inputFunc(int array[]);

int main(int argc, char* argv[])
{  int array[X];

   inputFunc(array);

   outputFunc(array);

   system("pause");
   return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int array[])
{  cout << "Please enter " << X << " integer elements of an array.\n" << endl;
   for(int count = 0; count < X; ++count)
   {  cout << "array[" << count << "]: ";
      while(! (cin >> array[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array[" << count << "]: ";
      }
      fflush(stdin);
   }
}

int testFunc(int array[])
{  int index = 0;

   for(int count = 1; count < X; ++count)
      if(array[count] > array[index])
         index = count;

   return index;
}
                   
void outputFunc(int array[])
{  cout << "\nThe index of the greatest element in the array is " << testFunc(array)
        << ".\n" << endl;
}

Solution #4:

#include <iostream>
using namespace std;
void LargestElement(int arg[], int list) {
	int Index;
	int Largest = arg[0];
	
	for (n = 0; n < list; n++) {
		
		if (Largest < arg[n]) {
			Largest = arg[n];
			Index = n;
}
}
        cout << Largest << " " << Index << endl;
}
int main()
{
	int UserArray[10], input, x = 0;
        cout << "Please input 10 numbers: ";
	while (x < 10)
	{
                cin >> input;
		UserArray[x]=input;
		x++;
	}
	
	LargestElement(UserArray, 10);


return 0;
	
}
//By David J
#include <iostream>

using namespace std;
const int SZ = 10;

int main()
{
    int arr[SZ];
    int Largest = 0, index = 0;
    cout << "Please enter " << SZ << " integers:" << endl;
    for (int i = 0; i < SZ; i++)
    {
        cin >> arr[i];
    }

    for (int i = 0; i < SZ; i++)
    {
        if (arr[i] >= Largest)
        {
            Largest = arr[i];
            index = i+1;
        }
    }
    cout << "Largest number = " << Largest << ", at index: " << index << endl;

    return 0;
}
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
	int size;
	cout<<"enter the size of array\n";
	cin>>size;
	
	ray[size];
        for(int i=0;i<size;i++)
	{
	    cout<<"\n\n   enter the "<<i+1<<" element of array";
	    cin
	>>array[i];
        }
	int p=array[0];
	int index;
	for(int i=0;i<size;i++)
	{
		if(p<array[i])
		{
			p=array[i];
			index=i;
		}
	}
 		cout<<"\nthe largest element of an array is "<<p;  
               cout<<"\n\nthe index of the valus is "<<index;
getch();
return 0;
}


EXERCISE 4

Write a program that asks the user to type 10 integers of an array and an integer value V. The program must search if the value V exists in the array and must remove the first occurrence of V, shifting each following element left and adding a zero at the end of the array. The program must then write the final array.

Solution

Solution #1

#include <iostream>
using namespace std;

const int N=10;

int main()
{
    int t[N],i,j,V;
    bool found;
    for(i=0;i<N;i++)
    {
        cout << "Type an integer: ";
        cin >> t[i];
    }
    cout << "Type the value of V: ";
    cin >> V;

    for (i=0;i<N;i++)
        if (t[i]==V)
        {
            for (j=i;j<N-1;j++)
                t[j]=t[j+1];
            t[N-1]=0;
            break;
        }

    for(i=0;i<N;i++)
        cout << t[i] << endl;

    return 0;
}

Solution #2

//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;

#define X 10
//---------------------------------------------------------------------------
void outputFunc(int array[], int V);

int searchFunc(int array[], int V);

void inputFunc(int array[], int& V);

int main(int argc, char* argv[])
{  int V, array[X];

   inputFunc(array, V);

   outputFunc(array, V);

   system("pause");
   return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int array[], int& V)
{  cout << "Please enter " << X << " integer elements of an array.\n" << endl;
   for(int count = 0; count < X; ++count)
   {  cout << "array[" << count << "]: ";
      while(! (cin >> array[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array[" << count << "]: ";
      }
      fflush(stdin);
   }

   cout << "\nNow, enter the integer, \"V\": ";
   while(! (cin >> V) )
   {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
      cin.clear();
      cin.ignore(10000, '\n');
      cout << "Enter the integer, \"V\": ";
   }
   fflush(stdin);
}

int searchFunc(int array[], int V)
{  int index_V;

   for(int count = 0; count < X; ++count)
      if(array[count] == V)
      {  index_V = count;
         break;
      }

   return index_V;
}

void outputFunc(int array[], int V)
{  int count, newArray[X];

   for(count = 0; count < X - 1; ++count)
      newArray[count] = array[count];
   for(count = searchFunc(array, V); count < X - 1; ++count)
      newArray[count] = array[count + 1];
   if(count < X)
      newArray[X - 1] = 0;
   else
   {  newArray[X - 1] = array[X - 1];
      cout << "\nThe number, " << V << ", is not contained within the array.\n"
           << endl;
   }

   cout << "\nThe final array is:\n" << endl;
   for(count = 0; count < X; ++count)
      cout << "array[" << count << "]: " << newArray[count] << endl;
   cout << endl;
}

Solution #3

// by blazzer12
 
#include <iostream>
#include <cstdlib>
 
#define SIZE 4
 
using namespace std;
 
void getVal(int *x)
{
 
        for(int i=0; i<SIZE; i++)
        {
                cout<<endl<<"Please Enter Values of Array["<<i<<"] = ";
                cin>>x[i];
        }
}
 
int getSearchCriteria()
{
        int V;
 
        cout<<endl<<endl<<"Please enter the integer you want to find (V) = ";
        cin>>V;
 
        return V;
}
 
int searchArray(int *y,int s)
{
        int index;
        bool notFound = true;
 
        for(index = 0; notFound && index<SIZE; index++)
        {         
                if(y[index]==s)
                        notFound=false;                      
        }
 
        if (notFound)
        {
                cout<<endl<<"Element "<<s<<" is not found."<<endl;           
                index = 0;
        }
        else
        {
                cout<<endl<<"Element "<<s<<" is found at array["<<index-1<<"]"<<endl;
        }
 
 
        return index-1;
}
 
void deleteElement(int *z,int loc)
{
        for(int i=loc; i<SIZE; i++)
        {
                z[i]=z[i+1];
        }
 
        z[SIZE-1]=0;
}
 
void display(int *a)
{
        cout<<endl<<"Values of array : "<<endl;
 
        for(int i=0; i<SIZE; i++)
                cout<<endl<<*a++;
}
 
int main()
{
        int array[SIZE],V,location=-1;
        char choice;
        bool tryAgain=false;
 
        // get values for array[] from user
        getVal(array);
 
 
        do
        {
                // ask user the element to be searched for
                V=getSearchCriteria();
 
                // search V and report
                location = searchArray(array,V);
 
                if(location==-1)
                {
                        cout<<endl<<"Do you want to search again (Y/N) : ";
                        cin>>choice;
 
                        if(choice == 'Y' || choice == 'y')
                                tryAgain = true;
                        else
                                exit(0);
                }
                else
                        tryAgain= false;
        }while(tryAgain);
 
 
 
        // delete the element V
        deleteElement(array,location);
        cout<<endl<<"Element "<<V<<" at array["<<location<<"] is deleted!"<<endl;
 
        // diplay array;
        display(array);
 
        return 0;
}

Solution #4

//By David J
#include <iostream>

using namespace std;
const int SZ = 10;

int main()
{
    int arr[SZ];
    int V;
    cout << "Please enter 10 integers: " << endl;
    for (int i = 0; i < SZ; i++)
    {
        cin >> arr[i];
    }
    cout << "Enter V: ";
    cin >> V;

    for (int i = 0; i < SZ; i++)
    {
        if (V == arr[i])
        {
            for (int j = i; j < SZ-1; j++)
                arr[j] = arr[j+1];
            arr[SZ-1] = 0;
        }
    }
    for (auto i : arr)
        cout << i << endl;

    return 0;
}


EXERCISE 5

Write a program that asks the user to type 10 integers of an array and an integer value V and an index value i between 0 and 9. The program must put the value V at the place i in the array, shifting each element right and dropping off the last element. The program must then write the final array.

Solution

Solution #1

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

void word_shift(int[], int, int);

int main()
{
	int insert;
	int index1;
	int num_in[10];

	cout << "Enter the value to insert:";
	cin >> insert;
	cout << "Enter index to place the value:";
	cin >> index1;
	cout << "Enter the 10 integer values:";

	for(int index=0; index<=9; index++)
	{
		cin >> num_in[index];
	}
	
	word_shift( num_in, insert, index1 );
	getch();
 return 0 ;
 }

void word_shift(int array[10], int ins, int index)
{
	int temp;
	
	//array[index]=ins;
	for(int index1=0; index1<=9; index1++)
		if (index1==index)
			array[index1]=ins;
			
	cout << endl;

	for(index1=0; index1<=9;index1++)
		cout << array[index1] << endl;

	for(index1=0; index1<=9; index1++)
	{
		if(array[index1]==ins && index1<9)
		{
			temp = array[index1];
			array[index1]=array[index1+1];
			array[index1+1]=temp;
		}
	}

	cout << endl;

	for(index1=0; index1<=9;index1++)
		cout << array[index1] << endl;
}

Solution #2

//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;

#define X 10
//---------------------------------------------------------------------------
void outputFunc(int array[], int V, int i);

int* insertFunc(int array[], int V, int i);

void inputFunc(int array[], int& V, int& i);

int main(int argc, char* argv[])
{  int V, i, array[X];

   inputFunc(array, V, i);

   outputFunc(array, V, i);

   system("pause");
   return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int array[], int& V, int& i)
{  cout << "Please enter " << X << " integer elements of an array.\n" << endl;
   for(int count = 0; count < X; ++count)
   {  cout << "array[" << count << "]: ";
      while(! (cin >> array[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array[" << count << "]: ";
      }
      fflush(stdin);
   }

   cout << "\nNext, enter a new integer element, \"V\": ";
   while(! (cin >> V) )
   {  cout << "\n\tSorry, invalid input... was expecting an integer."
           << "  Please try again:\n" << endl;
      cin.clear();
      cin.ignore(10000, '\n');
      cout << "Enter a new integer element, \"V\": ";
   }
   fflush(stdin);

   cout << "\nNow, enter the index, i(0 - " << X - 1 << "), in which to place"
        << " the new element, \n";
   cout << "\t" << V << ", into the array: ";
   while(! (cin >> i) || i < 0 || i > X - 1)
   {  cout << "\n\tSorry, invalid input... was expecting an integer."
           << "  Please try again:\n" << endl;
      cin.clear();
      cin.ignore(10000, '\n');
      cout << "\nNow, enter the index, i(0 - " << X - 1 << "), in which to place"
           << " the new element, \n";
      cout << "\t" << V << ", into the array: ";
   }
   fflush(stdin);
}

int* insertFunc(int array[], int V, int i)
{  int count, newArray[X], * newArrayPtr = newArray;

   for(count = 0; count < i; ++count)
      newArrayPtr[count] = array[count];
   newArrayPtr[count] = V;
   for(count = i + 1; count < X; ++count)
      newArrayPtr[count] = array[count - 1];

   return newArrayPtr;
}

void outputFunc(int array[], int V, int i)
{  cout << "\nThe new array is:\n" << endl;
   for(int count = 0; count < X; ++count)
      cout << "array[" << count << "]: " << insertFunc(array, V, i)[count] << endl;
   cout << endl;
}

Solution #3

// By J0nDaFr3aK
#include <iostream>
using namespace std;

#define LENGTH 10

int main()
{
    int array[LENGTH], v, i(-1), j, temp1, temp2;
    
    for (j = 0; j < LENGTH; j++) {
        cout << "enter number: ";
        cin >> array[j];
    }
    
    cout << "\nenter value of V: ";
    cin >> v;
    
    do {
        cout << "\nenter value of i (0 to " << LENGTH - 1 << "): ";
        cin >> i;
    } while (i < 0 || i > LENGTH - 1);
    
    // saves value to copy in next one before replacing it with V
    temp1 = array[i];
    array[i] = v;
    
    for (j = i + 1; j < LENGTH - 1; j++) {
        temp2 = array[j];
        array[j] = temp1;
        temp1 = temp2;        
    }
    
    array[j] = temp2; // j == LENGTH - 1 (9)
    
    // prints new values
    for (j = 0; j < LENGTH; j++) {
        cout << array[j] << " ";
    }
    
    return 0;
}

Solution #4

// By Tinnin
// Inserting element into array

#include <iostream>
using namespace std;

int main()
{
    int array[10], V, i;
    cout << "Enter ten integers into the array: \n";
    for(int j=0;j<10;j++)
    {
        cin >> array[j];
    }
    for(int j=0;j<10;j++)
    {
        cout << array[j] << " | ";
    }
    cout << "\nEnter an integer V to insert into the array: ";
    cin >> V;
    cout << "Choose the index i between 0 and 9 at which to enter V: ";
    cin >> i;
    while(i<0||i>9)
    {
        cout << "Choose the index i between 0 and 9 at which to enter V: ";
        cin >> i;
    }
    for(int j=0;j<10;j++)
    {
        if(j==(i+1))
        {
            for(int k=9;k>i;k--)
            {
                array[k]=array[k-1];
            }
            break;
        }
    }
    array[i]=V;
    for(int j=0;j<10;j++)
    {
        cout << array[j] << " | ";
    }
    return 0;
}

Solution #5

//by David J
#include <iostream>

using namespace std;
const int SZ = 10;

int main()
{
    int arr[SZ];
    int V, i;
    cout << "Please enter 10 integers: " << endl;
    for (int x = 0; x < SZ; x++)
    {
        cin >> arr[x];
    }
    cout << "Enter value to insert in array: ";
    cin >> V;
    cout << "Enter Index (0-9) to place the value: ";
    cin >> i;
    while (i < 0 || i > 9)
    {
        cout << "Index must be within range 0-9: ";
        cin >> i;
    }
    int z = SZ-1;
    while (z != i)
    {
        arr[z] = arr[z-1];
        z--;
    }
    arr[i] = V;

    for (auto y : arr)
        cout << y << endl;

    return 0;
}


EXERCISE 6

Write a program that asks the user to type 10 integers of an array. The program will then display either "the array is growing", "the array is decreasing", "the array is constant", or "the array is growing and decreasing."

Solution

Solution #1

#include <iostream>
using namespace std;

const int N=10;

int main()
{
    int a[N],i;
    bool found=false;
    bool up=false,down=false;

    cout << "Please enter an integer: ";
    cin >> a[0];
    for(i=1;i<N;i++)
    {
        cout << "Please enter an integer: ";
        cin >> a[i];
        if(a[i-1]>a[i]) down=true;
	if(a[i-1]<a[i]) up=true;
    }

    cout << "the table is " << (up?
        (down?
            "increasing and decreasing":
            "increasing"):
        (down?
            "decreasing":
            "constant")) << endl;
    return 0;
}

Solution #2

//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;

#define X 10
//---------------------------------------------------------------------------
void outputFunc(bool increasing, bool decreasing);

void inputFunc(int array[], bool& increasing, bool& decreasing);

int main(int argc, char* argv[])
{  int array[X];
   bool increasing, decreasing;

   inputFunc(array, increasing, decreasing);

   outputFunc(increasing, decreasing);

   system("pause");
   return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int array[], bool& increasing, bool& decreasing)
{  cout << "Please enter " << X << " integer elements of an array.\n" << endl;
   for(int count = 0; count < X; ++count)
   {  cout << "array[" << count << "]: ";
      while(! (cin >> array[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array[" << count << "]: ";
      }
      if(array[count] < array[count - 1] && count != 0)
         decreasing = true;
      else if(array[count] > array[count - 1] && count != 0)
         increasing = true;
      fflush(stdin);
   }
}

void outputFunc(bool increasing, bool decreasing)
{  cout << "The array is " << (increasing ? (decreasing ? "growing and decreasing.\n" :
           "increasing.\n") : (decreasing ? "decreasing.\n" : "constant.\n") ) << endl;
}

Solution #3

// by blazzer12
#include <iostream>

#define SIZE 10

using namespace std;

int main()
{
	int numbers[SIZE];
	
	bool increase=false, decrease=false;
	
	cout<<"Welcome, enter integers to know the nature of sequence."<<endl;
	
	for(int i=0; i < SIZE; i++)		//get values for numbers[] array from user
	{
		cout<<"numbers["<<i<<"] = ";
		
		while(!(cin>>numbers[i]))
		{
			// avoid and handle invalid input
			cin.clear();			
			cin.ignore(10000, '\n');
			
			cout<<"Expected Integer, please try again."<<endl;			
			cout<<"numbers["<<i<<"] = ";
		}
			
			
	}
	
	for(int i=0; i<SIZE-1; i++)		// to check the nature of values
	{
		if(numbers[i+1]>numbers[i])
			increase = true;
			
		if(numbers[i+1]<numbers[i])
			decrease = true;
		
	}
	
	
		// print result
		
		if(increase && decrease)
			cout<<"Array is Increasing & Decreasing";
		else if(increase)
			cout<<"Array is Increasing";
		else if(decrease)
			cout<<"Array is Decreasing";
		else if(!(increase && decrease))
			cout<<"Array is Constant";
				
	
	return 0; //successful termination
}

Solution #4:

#include <iostream>
using namespace std;
 
const int N=10;
 
int main()
{
    int a[N],i;
    bool found=false;
    bool up=false,down=false;
 
    cout << "Please enter an integer: ";
    cin >> a[0];
    for(i=1;i<N;i++)
    {
        cout << "Please enter an integer: ";
        cin >> a[i];
        if(a[i-1]>a[i]) down=true;
        if(a[i-1]<a[i]) up=true;
    }
 
    cout << "the table is ";  if (up&&down)
    
            cout<<"increasing and decreasing";
	else if(up)
         cout<<   "increasing";
	else if (down)
         cout<<   "decreasing";
	else if (!(up&&down))
           cout<< "constant" << endl;
 system("pause");
    return 0;
}

Solution #5:

// by Ismail Zouaoui
#include <iostream>

using namespace std;

int main()
{
    int const SIZE = 10;
    int arr[SIZE];
    bool order = true;

    cout << "Please enter 10 integers: ";

    for(int i=0; i < SIZE; i++)
    {
        cin >> arr[i];
    }

    cout << "\nThe table is: ";
    if(arr[0] < arr[SIZE-1]) // it's possibly growing
    {
        // we'll go over the loop to search for contradiction
        // if it does exist order will change
        for(int i=0; i<SIZE-1; i++)
        {
            if(arr[i] > arr[i+1])
            {
                cout << "growing and decreasing.\n";
                order = false;
                break;
            }
        }
        // if order still = true, means we did not found contradiction
        // so, its growing
        if(order == true)
        {
            cout << "growing.\n";
        }
    }
    else if(arr[0] > arr[SIZE-1]) // it's possibly decreasing
    {
        for(int i=0; i<SIZE-1; i++)
        {
            if(arr[i] < arr[i+1])
            {
                cout << "growing and decreasing.\n";
                order = false;
                break;
            }
        }
        if(order == true)
        {
            cout << "decreasing.\n";
        }
    }
    else if(arr[0] == arr[SIZE-1]) // it's possibly constant
    {
        for(int i=0; i<SIZE-1; i++)
        {
            if(arr[i] != arr[i+1])
            {
                cout << "growing and decreasing.\n";
                order = false;
                break;
            }
        }
        if(order == true)
        {
            cout << "constant.\n";
        }
    }

    return 0;
}


EXERCISE 7

Write a program that asks the user to type 10 integers of an array. The program will then sort the array in increasing order and display it.

Solution

PS: this is a Selection sort.

Solution #1

#include <iostream>
using namespace std;

const int N=10;

int main()
{
    int a[N],i,j,min,imin,tmp;

    for (i=0;i<N;i++)
    {
        cout << "Please enter an integer: ";
        cin >> a[i];
    }

    for (i=0;i<N-1;i++)
    {
        imin=i;
        min=a[i];
        for (j=i+1;j<N;j++)
            if (a[j]<min)
            {
                min=a[j];
                imin=j;
            }

        tmp=a[imin];
        a[imin]=a[i];
        a[i]=tmp;
    }
    cout << "The sorted array:" << endl;
    for (i=0;i<N;i++)
    cout << "a[" << i << "] = " << a[i] << endl;

    return 0;
}

PS: this is another sorting algorithm (a Bubble sort).

Solution #2

#include <iostream>
using namespace std;

const int N=10;

int main()
{
    int a[N],i,nb,tmp;

    for(i=0;i<N;i++)
    {
        cout << "Please enter an integer: ";
        cin >> a[i];
    }
    do {
        nb=0;
        for (i=0;i<N-1;i++)
            if (a[i]>a[i+1])
            {
                tmp=a[i];a[i]=a[i+1];a[i+1]=tmp;
                nb++;
            }
    } while(nb!=0);

    cout << "The sorted array:" << endl;
    for (i=0;i<N;i++)
        cout << "a[" << i << "] = " << a[i] << endl;

    return 0;
}

The following is also a Selection sort.

Solution #3

//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;

#define X 10
//---------------------------------------------------------------------------
void outputFunc(int array[]);

void sortFunc(int array[]);

void inputFunc(int array[]);

int main(int argc, char* argv[])
{  int array[X];

   inputFunc(array);

   outputFunc(array);

   system("pause");
   return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int array[])
{  cout << "Please enter " << X << " integer elements of an array.\n" << endl;
   for(int count = 0; count < X; ++count)
   {  cout << "array[" << count << "]: ";
      while(! (cin >> array[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array[" << count << "]: ";
      }
      fflush(stdin);
   }
}

void sortFunc(int array[])
{  for(int startIndex = 0; startIndex < X; ++startIndex)
   {  int smallestIndex = startIndex;
      for(int currentIndex = startIndex + 1; currentIndex < X; ++currentIndex)
         if(array[currentIndex] < array[smallestIndex])
            smallestIndex = currentIndex;
      swap(array[smallestIndex], array[startIndex]);
   }
}

void outputFunc(int array[])
{  cout << "\nThe array, sorted from least to greatest, is as follows:\n" << endl;

   sortFunc(array);

   for(int count = 0; count < X; ++count)
      cout << "array[" << count << "]: " << array[count] << endl;
   cout << endl;
}

Solution #4

// By J0nDaFr3aK
#include <iostream>
using namespace std;

#define LENGTH 10

int main()
{
    int array[LENGTH], i, j, lowest, index, temp;
    
    // input
    for (i = 0; i < LENGTH; i++) {
        cout << "enter value " << i << ": ";
        cin >> array[i];
    }
    
    // sorting
    for (i = 0; i < LENGTH; i++) {
        lowest = array[i];
        index = i;
        for (j = i; j < LENGTH; j++) {
            if (array[j] < lowest) {
               lowest = array[j]; // saves lowest number
               index = j;         // saves position index of lowest number
            }
        }
        temp = array[i];
        array[i] = lowest;
        array[index] = temp;
    }
    
    // prints array
    for (i = 0; i < LENGTH; i++) 
        cout << array[i] << " ";
    
    cout << endl;
    
    return 0;
}

Solution #5

// by J0nDaFr3aK
#include <iostream>
using namespace std;

#define LENGTH 10

void input(int array[], int size);
void sorting(int array[], int size);
void display(int array[], int size);

int i;

int main()
{
    int array[LENGTH];
    
    cout << "\nI will sort elements using bubble sort algorythm\n\n";
    input(array, LENGTH);
    
    cout << "\nSorting array...\n";
    sorting(array, LENGTH);
    
    cout << "\nDisplaying sorted array in ascending order\n";
    display(array, LENGTH);
    
    cout << endl;
    
    return 0;
    
}

void input(int array[], int size) {
     for (i = 0; i < size; i++) {
         cout << "type element " << i << ": ";
         cin >> array[i];
     }
}

void sorting(int array[], int size) {
     int j, lowest, ilowest, tmp;
     
     for (j = 0; j < size; j++) {
         lowest = array[j];
         ilowest = j;
         for (i = j; i < size; i++) {
             if (array[i] < lowest) {
                lowest = array[i];
                ilowest = i;
             }
         }
         tmp = array[j];
         array[j] = array[ilowest];
         array[ilowest] = tmp;
     }
}

void display(int array[], int size) {
     for (i = 0; i < size; i++)
         cout << array[i] << " ";
}

Solution #6

//By David J
#include <iostream>

using namespace std;
const int SZ = 10;

void desc_Sort(int *arr, int sz) //recursive function
{
    int temp;
    for (int i = 0; i < sz-1; )
    {
        if (arr[i] < arr[i+1])
        {
            temp = arr[i+1];
            arr[i+1] = arr[i];
            arr[i] = temp;
            i++;
        }
        else
            i++;
    }
    for (int j = 0; j < sz-1; j++)
    {
        if (arr[j] < arr[j+1])
            desc_Sort(arr, sz);
    }
}


int main()
{
    int arr[SZ];
    cout << "Enter 10 integers:" << endl;
    for (int i = 0; i < SZ; i++)
    {
        cin >> arr[i];
    }


    cout << "Your numbers in descending order:\n";
    desc_Sort(arr, SZ);
    for (auto a : arr)
        cout << a << endl;
    return 0;
}

Solution #7 by xeeshan

#include<iostram>
using namespace std;
int main()
{
int a[10]={33,10,1,87,6,44,23,3,11,82};
int i,j,temp; 
int N=10;
 
for (i=0; i<N; i++)
{
	for (int j=0; j<N-i-1; j++)
		if (a[j] > a[j+1])
		{	temp = a[j];
			a[j] = a[j+1];
			a[j+1] = temp;
		}
}

}


EXERCISE 8

Write a program which takes 2 arrays of 10 integers each, a and b. c is an array with 20 integers. The program should put into c the appending of b to a, the first 10 integers of c from array a, the latter 10 from b. Then the program should display c.

Solution

Solution #1

#include <iostream>
using namespace std;

const int N=10;

int main()
{
    int a[N],b[N],c[2*N],i;

    cout << "Enter table a:" << endl;
    for (i=0;i<N;i++)
    {
        cout << "Please enter an integer: ";
        cin >> a[i];
    }

    cout << "Enter table b:" << endl;
    for (i=0;i<N;i++)
    {
        cout << "Please enter an integer: ";
        cin >> b[i];
    }

    for (i=0;i<N;i++) c[i]=a[i];
    for (i=0;i<N;i++) c[i+N]=b[i];

    cout << "Table c:" << endl;
    for (i=0;i<2*N;i++)
        cout << c[i] << " ";
    cout << endl;
    return 0;
}

Solution #2

//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;

#define X 10
#define Y 10
//---------------------------------------------------------------------------
void outputFunc(int a[], int b[]);

int* concatenate(int a[], int b[]);

void inputFunc(int a[], int b[]);

int main(int argc, char* argv[])
{  int a[X], b[Y];

   inputFunc(a, b);

   outputFunc(a, b);

   system("pause");
   return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int a[], int b[])
{  cout << "Please enter " << X << " integer elements of an array.\n" << endl;
   for(int count = 0; count < X; ++count)
   {  cout << "array a[" << count << "]: ";
      while(! (cin >> a[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array a[" << count << "]: ";
      }
      fflush(stdin);
   }

   cout << "\nPlease enter " << Y << " integer elements of another array.\n"
        << endl;
   for(int count = 0; count < Y; ++count)
   {  cout << "array b[" << count << "]: ";
      while(! (cin >> b[count]) )
      {  cout << "\n\tSorry, invalid input... was expecting an integer."
              << "  Please try again:\n" << endl;
         cin.clear();
         cin.ignore(10000, '\n');
         cout << "array b[" << count << "]: ";
      }
      fflush(stdin);
   }
}

int* concatenate(int a[], int b[])
{  int count, c[X + Y], * cPtr = c;

   for(count = 0; count < X; ++count)
      cPtr[count] = a[count];
   for(count = X; count < X + Y; ++count)
      cPtr[count] = b[count - X];

   return cPtr;
}

void outputFunc(int a[], int b[])
{  cout << "\n\tThe final array, \"c\", is:\n" << endl;
   for(int count = 0; count < X + Y; ++count)
      cout << "c[" << count << "]: " << concatenate(a, b)[count] << endl;
   cout << endl;
}

// interesting note... I thought of using the old *strcat from C, but since I
// am trying to hone my function and pointer handling skills, I had more fun
// doing it this way :)

Solution #3

// by blazzer12

#include <iostream>

#define SIZE 10
#define dSIZE SIZE*2

//tempArray is global variable, so its values are not overwritten; to see, try declaring it as local variable
int tempArray[dSIZE];

using namespace std;

void getVal(int *x)
{
	
	for(int i=0; i<SIZE; i++)
	{
		cout<<endl<<"Please Enter Values of Array["<<i<<"] = ";
		cin>>x[i];
	}
	delete x;
}

int* appendArrayTo(int *x, int *y)
{	
	
	for(int i=0; i <SIZE; i++)
	{
		tempArray[i]=*x++;		// values of array A i.e *x are stored in tempArray from 0-9
		tempArray[SIZE+i]=*y++;	// values of array B i.e *y are stored in tempArray from 10-19, where SIZE=10
	}
	
	delete x;
	delete y;
	
	return tempArray;
	
	
}

void display(int *x)
{
	cout<<endl<<"Values of C"<<endl;
	
	for(int i=0; i<dSIZE; i++)
		cout<<endl<<*x++;
    delete x;
}

int main()
{
	int A[SIZE];
	int B[SIZE];
	int *C;
	
	cout<<"\t\tWELCOME"<<endl;
	cout<<"Array B is appended to array A. Then stored in C and displayed."<<endl;
	
	//get values of array A & B
	getVal(A);
	getVal(B);
	
	//append A to B and store in C
	C = appendArrayTo(A,B);
	
	//display C
	display(C);
		
	return 0;

}

Solution #4

// by J0nDaFr3aK
#include <iostream>
using namespace std;

#define LENGTH 10

int main()
{
    int a[LENGTH], b[LENGTH], c[LENGTH*2], i;
    
    cout << "type numbers into first array:\n";
    for (i = 0; i < LENGTH; i++) {
        cout << i << " = ";
        cin >> a[i];
    }
    
    cout << "type numbers into second array:\n";
    for (i = 0; i < LENGTH; i++) {
        cout << i << " = ";
        cin >> b[i];
    }
    
    for (i = 0; i < LENGTH * 2; i++) {
        if (i < LENGTH)
           c[i] = a[i];
        else
            c[i] = b[i - LENGTH];
    }
    
    for (i = 0; i < LENGTH * 2; i++)
        cout << c[i] << " ";
        
    return 0;
}


Edit
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.