codescracker
c++

C++ Program to Find and Print Odd Numbers in an Array



« C++ Tutorial C++ Example »

This article provides some programs in C++ that find and prints all odd numbers in an array entered by user. List of programs covered here are:

Print Odd Numbers in an Array of 10 Elements

The question is, write a C++ program that receives 10 elements (numbers) from user at run-time and print all odd numbers. The program given below is its answer:

#include<iostream>

using namespace std;
int main()
{
   int arr[10], i;
   cout<<"Enter 10 numbers: ";
   for(i=0; i<10; i++)
      cin>>arr[i];
   cout<<"\nList of Odd Numbers are:\n";
   for(i=0; i<10; i++)
   {
      if(arr[i]%2!=0)
         cout<<arr[i]<<" ";
   }
   cout<<endl;
   return 0;
}

The snapshot given below shows the initial output produced by above C++ program on printing all the odd numbers available in a given array:

c++ print odd numbers in array

Now enter any 10 numbers say 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 and press ENTER key to find and print all odd numbers from these ten numbers as shown in following snapshot:

print odd numbers in array c++

Print Odd Numbers in an Array of n Elements

This program allows user to enter the value of n or to define the size of array along with its elements of required size.

#include<iostream>

using namespace std;
int main()
{
   int n, i;
   cout<<"Enter the value of n: ";
   cin>>n;
   int arr[n];
   cout<<"Enter any "<<n<<" numbers: ";
   for(i=0; i<n; i++)
      cin>>arr[i];
   cout<<"\nList of Odd Numbers:\n";
   for(i=0; i<n; i++)
   {
      if(arr[i]%2!=0)
         cout<<arr[i]<<" ";
   }
   cout<<endl;
   return 0;
}

Here is its sample run with user input 5 as size and 100, 101, 102, 103, 104 as five elements or numbers for the array:

c++ program find odd numbers in array

Find and Print Odd Numbers using Another Array

This program uses two arrays, one stores original array, second stores only odd numbers from original array.

#include<iostream>

using namespace std;
int main()
{
   int n, i, j=0;
   cout<<"Enter the value of n: ";
   cin>>n;
   int arr[n], odd[n];
   cout<<"Enter any "<<n<<" numbers: ";
   for(i=0; i<n; i++)
   {
      cin>>arr[i];
      if(arr[i]%2!=0)
      {
         odd[j] = arr[i];
         j++;
      }
   }
   if(j==0)
      cout<<"\nOdd number not found in the array!";
   else if(j==1)
      cout<<"\nOnly one odd number found. That is:\n"<<odd[0];
   else
   {
      cout<<"\nList of Odd numbers:\n";
      for(i=0; i<j; i++)
         cout<<odd[i]<<" ";
   }
   cout<<endl;
   return 0;
}

Here is its sample run with user input 4 as size and 100, 102, 103, 104 as four elements or numbers:

c++ find odd numbers in array

C++ Online Test


« C++ Tutorial C++ Example »



© Copyright 2021. All Rights Reserved.

CodesCracker