Printing prime or composite using For Loop in C++


This is a C++ program that prompts the user to input a number, and then determines whether the number is prime or composite. Here is a brief explanation of the program:

  • The program declares four integer variables: i, n, a, and prime, and initializes prime to 0.
  • The program prompts the user to input a number, and reads it from the standard input using the cin object.
  • The program enters a for loop that iterates from 2 to i-1 inclusive, with a step of 1. In each iteration, the loop body is executed.
  • In the loop body, the program checks if the current value of n divides i without leaving a remainder. If so, the variable prime is incremented by 1. This is because a prime number is only divisible by 1 and itself.
  • After the loop terminates, the program checks the value of prime. If it is 0, then i is a prime number and the program outputs "This number is Prime". Otherwise, i is a composite number and the program outputs "This number is Composite".
  • Finally, the program returns 0 to the operating system, indicating successful execution.

Source Code

#include<iostream>
using namespace std;
int main()
{
    int i,n,a,prime=0;
    cout<<"\nEnter the number:";
    cin>>i;
    for(n=2;n<i;n++)
    {
        if(i%n==0)
        {
            prime++;
        }
    }
    if(prime==0)
    {
        cout<<"\nThis number is Prime";
    }
    else
    {
        cout<<"\nThis number is Composite";
    }
    return 0;
}
To download raw file Click Here

Output

Enter the number:10
This number is Composite

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples