...
/Solution Review: Find out if the Given Number is Prime
Solution Review: Find out if the Given Number is Prime
Let's go over the solution review of the challenge given in the previous lesson.
We'll cover the following...
We'll cover the following...
Solution #
Press + to interact
C++
#include <iostream>using namespace std;int main() {// Intitialize variablesint number = 7;bool isPrime = true;// if block/*Checks if the value of a `number` is less than or equal to1. If yes, then execute line No. 13 to 16. If no, then executeline No. 18*/if (number <= 1) {//Sets the value of `isPrime` to falseisPrime = false;}// for blockfor (int counter = 2; counter <= number / 2; counter++) {// if blockif (number % counter == 0) {isPrime = false;// jump to line No. 27break;}}// if-else block/*If isPrime = true then execute line No. 30.If no, then execute line No. 32*/if (isPrime) {cout << "Number is prime";} else {cout << "Number is not prime";}return 0;}
Explanation
We have initialized the variable isPrime
of type bool
that keeps track of the number
. If the given number is prime, we ...