Computer Science, asked by sufisayed9260, 1 year ago

Write a C program to print a triangle of prime numbers upto given number of lines of the triangle.#include

int prime(int num); //Function to find whether the number is prime or not.
int main() {
int lines;
scanf("%d", &lines); //Number of lines of the triangle is taken from test data.

//use the printf statement as printf("%d\t", variable_name); to print the elements in a row

Answers

Answered by bishwajeetroy9
9

Int i,j,n=2;

for(i=0;i<lines;i++)

{

for(j=0;j<=i;j++)

{

while(!prime(n))

{

n++;

}

printf("%d\t",n++);

}

printf("\n");

}

}

Int prime(int n1)

{

Int i,flag;

for(i=2;i<n1:i++)

{

If(n1%i!=0)

flag=1;

else

{

flag=0;

break;

}

}

if(flag==1 || n1==2)

return 1;

else

return 0;

}

Answered by codiepienagoya
4

Program of Triangle of prime numbers in C language:

Output:

5

2  

3 5  

7 11 13  

17 19 23 29  

31 37 41 43 47  

Explanation:

Program:

#include<stdio.h>//defining header file

int prime(int num); //method declaration

//method definition

int prime(int num) //defining method prime

{

  int i,x= 1;//defining integer variable

  for(i=2;i<=(num/2);i++)//defining loop to count prime number  

  {

     if (num % i == 0)//check condition for prime number

     {

        x=0;//assign value 0 in x variable

        break;//using break keyword

     }

  }

  if (x==1 || x==2)//defining condition that check input is 1 or 2

     return 1;//return value 1

  else//else block

     return 0;//return 0

}

int main()//defining main method  

{

  int i, j, lines;//defining integer variable

  int n = 2;//defining integer variable and assign value 2

  scanf("%d", &lines);//input value from user end  

  for (i = 1; i <= lines; i++) //defining loop to print column

  {

   for (j = 1; j <= i; j++) //defining loop to print rows

   {

    while(!prime(n))//defining loop to call method prime

       {

           n++;//increment value  

       }

       printf("%d ", n); //print prime number

       n++;//increment n value

     }

     printf("\n"); //user print for next line

  }

  return(0);

}  

Program description:

  • In the above program code, a method prime is declared that accepts the integer variable num in its parameter. inside the method, two integer variables "i and x" are declared, in which "i" is used in the loop.
  • Inside the loop, prime number condition is defined, which counts prime numbers, and returns its value.
  • In the main method, three integer variable "i, j, and lines" is declared, in the lines variable we input the value from the user end and the variable i and j are used in the loop.
  • In the next step, two for loop and one while is used, in which for loop is used to print triangle and while loop used to call and print prime numbers.    

Learn more:

  • prime number: https://brainly.in/question/3660390
Similar questions