Home > database >  How can i find if a number that has been entered by a user on the second array that contains a 7 and
How can i find if a number that has been entered by a user on the second array that contains a 7 and

Time:01-02

So this is my code . What it does is it allows an user to make a smaller array from a larger 100 elemnts array to a smaller custom one. For example the user enter that they want an array of 2 elements . Now those 2 elements can be whatever number they want like 27 or 17. I need to know how to make it so that when the user enters an element that contains a 7 in it and prints it out . I know it needs a string element but i have exhausted every possible thing i can do. Im new to c .

#include <iostream>
#include <string>
 
using namespace std;
 
int main() {
    int a1, j;
    string numbers[100];
 
    // input from user for the wanted array
    cout << "Enter Wanted Array:" << endl;
 
    for (int a1 = 0; a1 < 100;   a1) 
    {
        cin >> a1;
        if (a1 > 100) 
        {
            cout << "Array is larger then what is allowed" << endl;
            exit(1);
        }
        else if (a1 < 0) 
        {
            cout << "Array is smaller then what is allowed" << endl;
            exit(1);
        }
        else
        {
            cout << "The Wanted Array is: " << a1 << endl;
        }
 
        cout << "Enter the numbers: " << endl;
 
        //  Input from User for the second Array
        for (int i = 0; i < a1;   i) 
        {
            cin >> numbers[i];
        }
 
        cout << "The numbers are: ";
        for (int n = 0; n < a1;   n) 
        {
            cout << numbers[n] << "  ";
        }
    }
    system("pause");
    return 0;
}
 


CodePudding user response:

In my understanding, you are trying to filter all the array elements that have the digit 7.

Firstly, you don't need a string input. As a matter of fact, it is much more simple in integer format.

Here is how you do it. For every number that the user inputs in the array, run a while loop that isolates every integer, like this :

//  Input from User for the second Array
for (int i = 0; i < a1;   i) {
    cin >> numbers[i];
    
    int num = numbers[i];
    while(num > 0) {
        int temp = num % 10;
        
        if (temp == 7) {
            cout << numbers[i] << " ";
            break; //to get out of the while loop
        }
        
        temp /= 10;
    }
}

This will print all the numbers that contain the digit 7.

Although this will give you the desired result, I must say that your code is very inefficient. Read more on how to write efficient code, it will help you in the long run. Cheers!!!

  •  Tags:  
  • c
  • Related