Answer to Question #325695 in C++ for Naqibhangu

Question #325695

Write a C++ program that displays the row numbers of a matrix containing at least two prime numbers. First, the program should create a 2D array (5 rows, 5 columns). Then, ask the user to input values in the matrix or 2D array. After that, program should display row number (or index) which has at least two prime numbers. If no row (of the matrix) contains at least two prime numbers then the program should display the message “No row found containing two prime numbers”.

1
Expert's answer
2022-04-08T06:08:15-0400
#include <iostream>
using namespace std;


bool is_prime(int x) {
    if (x <= 1) {
        return false;
    }
    if (x == 2) {
        return true;
    }
    if (x % 2 == 0) {
        return false;
    }


    int i = 3;
    while (i*i <= x) {
        if (x % i == 0) {
            return false;
        }
    }
    return true;
}


int main() {
    int arr[5][5];


    for (int i=0; i<5; i++) {
        cout << "Enter 5 values for row " << i+1 << ": ";
        for (int j=0; j<5; j++) {
            cin >> arr[i][j];
        }
    }


    int rows_with_pr[5];
    int rows_cnt = 0;
    for (int i=0; i<5; i++) {
        int pr_count = 0;
        for (int j=0; j<5; j++) {
            if (is_prime(arr[i][j])) {
                pr_count++;
            }
        }
        if (pr_count >= 2) {
            rows_with_pr[rows_cnt++] = i+1;
        }
    }


    if (rows_cnt == 1) {
        cout << "Row with more than two prime numbers is " << rows_with_pr[0] << endl;
    }
    else if (rows_cnt > 1) {
        cout << "The rows with more than two primes numbers are ";
        for (int i=0; i<rows_cnt; i++) {
            cout << rows_with_pr[i] << " ";
        }
        cout << endl;
    }
    else {
        cout << "No row found containing two prime numbers" << endl;
    }
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS