Showing posts with label Check Prime. Show all posts
Showing posts with label Check Prime. Show all posts

Sunday, April 27, 2014

Menu Driven Factorial Prime Odd Even - C Program

Problem Question


Write a menu driven program which has following options:
1. Factorial of a number.
2. Prime or not
3. Odd or even
4. Exit

Explanation of Problem


Make use of switch statement.

The outline of this program is given below:


/* A menu driven program */
main( )
{
int choice ;
while ( 1 )
{
printf ( "\n1. Factorial" ) ;
printf ( "\n2. Prime" ) ;
printf ( "\n3. Odd/Even" ) ;
printf ( "\n4. Exit" ) ;
printf ( "\nYour choice? " ) ;
scanf ( "%d", &choice ) ;
switch ( choice )
{
case 1 :
/* logic for factorial of a number */
break ;
case 2 :
/* logic for deciding prime number */
break ;
case 3 :
/* logic for odd/even */
break ;
case 4 :
exit( ) ;
}
}
}
Note: The statement while ( 1 ) puts the entire logic in an infinite loop. This is necessary since the menu must keep reappearing on the screen once an item is selected and an appropriate action taken.

Code


#include <stdio.h>
/*Factorial Prime Odd Even.C*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 27-04-2014**/

int main()
{
  while(1)
  {
    int choice, num, i;
    printf("\nChoose an option:\n\t1. Factorial\n\t2. Prime Check\n\t3. Odd or Even\n\t4. Exit\nChoice: ");
    scanf("%d", &choice);
    switch(choice)
    {
      case 1:
      {
        printf("\nEnter a number: ");
        scanf("%d", &num);
        int factorial = 1;
        for (i = num; i > 1; i--)
          factorial *= i;
        printf("\nThe factorial is: %d\n", factorial);
        break;
      }
      case 2:
      {
        printf("\nEnter a number: ");
        scanf("%d", &num);
        int flag = 0;
        for (i = 2; i < (num / 2 + 1); i++)
        {
          if ( num % i == 0)
          {
            printf("\nNot Prime\n");
            flag = 1;
            break;
          }
        }
        if (!flag)
          printf("\nPrime\n");
        break;
      }
      case 3:
      {
        printf("\nEnter a number: ");
        scanf("%d", &num);
        if (num % 2)
          printf("\nODD\n");
        else
          printf("\nEVEN\n");
        break;
      }
      case 4:
      {
        exit(0);
      }
      default:
      {
        printf("Wrong Choice");
        break;
      }
    }
  }
  system("pause");
  return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This function has to be named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

switch ( choice )
{
case 1 :
/* logic for factorial of a number */
break ;
case 2 :
/* logic for deciding prime number */
break ;
case 3 :
/* logic for odd/even */
break ;
case 4 :
exit( ) ;


This part of code represents the menu part. The 'switch' is a block that takes an argument 'choice' (the name can be anything, it is a variable), the value of which drives the program flow to one of the 'case' logics. A 'default' case is a case that executes if the value of the 'choice' doesn't match that of any of the cases. So here, if the user enters '1', '1' gets stored in variable 'choice' and upon seeing the switch statement, the program goes to case 1, that is, 'factorial of a number' in our case.

case 1:
{
printf("\nEnter a number: ");
scanf("%d", &num);
int factorial = 1;
for (i = num; i > 1; i--)
factorial *= i;
printf("\nThe factorial is: %d\n", factorial);
break;
}


In this case, we calculate the factorial of a number. The logic is simple, keep multiplying until the number comes down to 1 from it's value 'n'. That's what the loop above does. It decrements the 'num' entered by 1 each time through the loop, and multiplies it with the running product, the factorial, until 'num' has a value 1.

case 2:
{
printf("\nEnter a number: ");
scanf("%d", &num);
int flag = 0;
for (i = 2; i < (num / 2 + 1); i++)
{
if ( num % i == 0)
{
printf("\nNot Prime\n");
flag = 1;
break;
}
}
if (!flag)
printf("\nPrime\n");
break;
}


In this case, the usr enters a number and the statements check whether the number is Prime or not. How do we acheive this? Simple! If a number is not divisible by any number (less than or equal to half the number itself), it is a prime number. The loop does the same thing. It divides the number by every natural number except 1, till the counter reaches half the number. As soon as the number is found to be divisible, we break out of the loop and print 'NOT PRIME' on the screen. Once the program is out of the loop, the 'flag' value is tested if the program came out of the loop normally, or the break made it to come out of the loop. If the former is tha case, we print 'PRIME' on the screen.

case 3:
{
printf("\nEnter a number: ");
scanf("%d", &num);
if (num % 2)
printf("\nODD\n");
else
printf("\nEVEN\n");
break;
}


In this case, the user enters a number, and we divide it by 2. If the number is divisible by 2, it is even, else odd and we print the result.

case 4:
{
exit(0);
}
default:
{
printf("Wrong Choice");
break;
}


Case 4 represents the case when the user wants to exit the program. In such a scenario, we call the 'exit()' function, with a value '0' which represents a normal exit status. The defaul case, represents the case when the yser enters a choice for which no case is defined in the switch block. In my program, I just print 'Wrong Choice' on the screen.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



Sunday, March 16, 2014

Check if the number is prime – Linux Shell Script

Problem Question


Write a script to check whether the given number is prime or not

Explanation of Problem


Here we wish to write a Linux Shell Script that would take a command line argument and check if that number is prime or not and print the result (PRIME or NOT PRIME) on the terminal.

Code



#*Check Prime*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 16-03-2014
x=`expr $1 / 2`
i=2
while [ $i -le $x ]
 do
  if [ `expr $1 % $i` -eq 0 ]
   then
    echo Not Prime
    exit
  fi
  i=`expr $i + 1`
 done
echo Prime

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

x=`expr $1 / 2` -> We declare a variable ‘x’ and assign it a value which is equal to half that of the first command line argument. This will help us know where to stop our loop which will divide the number with every integer until it finds the remainder of the division to be zero. Thus we can limit the loop counter to half the value of the number to be checked. Thus we use while [ $i -le $x ] as our loop.

i=2 -> This is our loop counter. We start at 2 since every number is divisible by 1.

if [ `expr $1 % $i` -eq 0 ] -> As soon as we find the remainder of the division is zero, we use echo Not Prime to display Not Prime on the terminal, and with the exit command we close our shell running the script, i.e., the script terminates.

i=`expr $i + 1` -> Loop counter incremented by one.

echo Prime -> If the control reaches here, it means that the number is not prime since it was not divisible by any of the numbers (upto half the number itself). Thus, we print Prime on the terminal.

then fi -> if block delimiters.

do done -> while block delimiters.

Output(s)