fb popup

/* remove if it's exist in your template */

How to approach a program

The main thing you should remember while writing a program is that you should behave and think as a compiler as a robot and not like a human.Then only you can understand any programming language.

C,CPP,Java etc everything have same logics and only the difference is the syntax.Of course from one language to the other there are some improved features.But we can understand any programming language and learn easily if we can master any one of the languages.

Whenever a program is given to you (say) to find whether the given number is a Prime or not.

1.Analyse the question:- So,to get prime numbers. first of all we need to know what are prime numbers. 2,3,5,7,11,and so on.  

2.Now break the logic:- the prime numbers are those whose factors are 1 and itself i.e if we take 11 then it's factors are 1 and 11.

now what does it mean.It means that whenever we divide 11 with either 1 or 11 the remainder should be 0.Other than 1 and 11 (say 2,4,6,7,8 etc)the remainder is other than zero.

Now we got the logic.

 3.Apply the possible method from what we learn in C:-
                              In order to get remainder we use the operator called modulus(%).         Ex:-10%5=0,13%2=1.
This will be helpful to us.

 In order to divide the given number with each and every no. from 1 to that number (say if we take 11 then it must be divided with 1,2,3, ......11 and check whether the number when divided can give '0' as remainder or not.).

To do so, we require for loop and a flag (here we took) 'k' as a flag.Flag is a variable which is used for checking whether it is true or not.  

4.the main code of the program now is
 
for(i=1;i<=n;i++)

{

if(n%i==0)

{

k++;

}

}

if(k==2)

{

printf("prime number");

}

else

{

printf("not prime number");

}

When ever the number divided with 'i' gives remainder zero the number in 'k' will be incremented by 1 as initially it is assigned to zero.

The main logic is that the prime numbers will give remainder as zero only 2 times in the entire loop iteration so k becomes 2 at the end of loop if it is prime and if it is other than prime number then it will increment k with more than 2.

suppose let us take 2 numbers
11---factors are 1 and 11 so k=1+1=2

8----factors are 1,2,4,8 so k=1+1+1+1=4

Then k is equal to 2 for 11 so it is prime number and k=4 which is not prime number.

Now the program is
 
#include<stdio.h>

main()

{

int i,k=0;

printf("Enter a number to check whether it is prime or not\n");

scanf("%d",n);

for(i=1;i<=n;i++)

{

if(n%i==0)

{

k++;

}

}

if(k==2)

{

printf("prime number");

}

else

{

printf("not prime number");

}

}

Output:-
Case -1 :-Enter a number to check whether it is prime or not

7

prime number

Case -2:-Enter a number to check whether it is prime or not

8

not prime number

No comments:

Post a Comment