Thread: Program to check whether given number is prime or not?

  1. #1
    Registered User
    Join Date
    Mar 2015
    Posts
    8

    Program to check whether given number is prime or not?

    Hi there, I've written a c program in answer to the following question:

    write a function prime that returns 1 if its argument is a prime number and 0 if it is otherwise.
    My code is:
    Code:
    // write a program that returns 1 for prime number and 0 if not prime
    //source: stephen kochan, programming in C, chapter 8
    #include<stdio.h>
    
    
    // function to check n is prime or not
    void prime (int n)
    {
      int i, c = 0;
       
          for (i = 1; i <= n; i++) {
              if (n % i == 0) {
                 c++;
              }
          }
          if (c == 2) {
              printf("1\n");
          }
          else {
              printf("0\n");
          }
             
    }
    int main (void)
    {
      void prime (int n);
      int m;
     
     printf("Please Give a number to check whether prime or not\n");
     scanf("%i", &m);
     prime(m);
     return 0;
    }
    The issue is I'm only printing 1 or 0. How am I supposed to RETURN these values from the function? A little confused, any help would be appreciated.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Consider this function that returns 1:
    Code:
    int foo(void)
    {
        return 1;
    }
    As you can see, it has a return type of int, and there is a return statement that returns 1. You would need to modify your prime function to be along these lines.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 12-02-2014, 10:11 AM
  2. Check wheather the entered number is prime also repeat it
    By rajesh10071986 in forum C Programming
    Replies: 6
    Last Post: 01-11-2010, 04:34 AM
  3. Prime number check
    By password in forum C++ Programming
    Replies: 3
    Last Post: 06-25-2007, 10:30 AM
  4. Replies: 3
    Last Post: 03-29-2005, 04:24 PM
  5. How is to check prime number?
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 10-04-2001, 11:36 PM

Tags for this Thread