My complete attempt of a very difficult c problem

  • Thread starter Thread starter ming2194
  • Start date Start date
  • Tags Tags
    Complete
Click For Summary

Discussion Overview

The discussion revolves around a participant's attempt to write a C program that identifies prime numbers and handles user input. The scope includes programming in C, code correctness, and adherence to C language standards.

Discussion Character

  • Homework-related
  • Technical explanation
  • Debate/contested

Main Points Raised

  • The original poster seeks confirmation that their code is written in C and will produce the expected output.
  • Some participants note that the use of variable declarations throughout the code may indicate C++ rather than C.
  • There is a discussion about the use of the 'bool' type, with one participant pointing out that it is not standard in C and suggesting alternatives.
  • Participants suggest changing 'bool' to 'int' and using 1 and 0 to represent true and false, respectively.
  • There is a recommendation to move all variable declarations to the beginning of the main function, as this is a requirement in C.
  • One participant expresses uncertainty about whether the changes suggested would make the code fully compliant with C standards.

Areas of Agreement / Disagreement

Participants generally agree on the need to modify the code to ensure it adheres to C standards, particularly regarding variable declarations and the use of 'bool'. However, there is no consensus on whether the original code can be considered correct without these changes.

Contextual Notes

Limitations include the potential misunderstanding of C versus C++ standards and the implications of using non-standard types like 'bool'. The discussion does not resolve whether the original code meets the assignment requirements without modifications.

Who May Find This Useful

This discussion may be useful for students learning C programming, particularly those interested in understanding language standards and debugging their code.

ming2194
Messages
31
Reaction score
0
[urgent] my complete attempt of a very difficult c problem

Homework Statement


http://u1.imgupload.co.uk/1258070400/9847_untitled.png

Homework Equations


*** i need to write it in C program. (not C++)

The Attempt at a Solution


PHP:
#include <stdio.h>
#include <math.h>

#define N 368

int main ()

{
	int i, j, s;
	int is_prime[N]; /* if is_prime[i] == 0, then i isn't prime */
	int prime_count = 0;

/* initially, all are presumed prime */

	printf ("\nThe prime numbers less than of equal to %d are:\n", N);

	for (i=0; i<N; i++) is_prime[i] = 1;

/* find the limit of the numbers to count up to */

	s = (int) sqrt (N) + 1;

/* for each i in 2..sqrt(N), mark out multiples of i */

	for (i=2; i<s; i++) {

/* mark out 2i, 3i, 4i, ... */

	for (j=2*i; j<N; j+=i) is_prime[j] = 0;
	}

/* print out the numbers that are left */

	for (i=2; i<N; i++){

   	if (is_prime[i]){
       printf ("\t%d\n", i);
       prime_count++;
		}
	}
printf("There total count of prime numbers is: %d\n\n",  prime_count);

#define MAX_ARRAY_SIZE 1000

    bool looping = true;
    while(looping)
			{		//Keep repeating until "looping = false"

    int number = 0;

		printf("\nEnter 3-digit positve integer: ");
       	scanf("%d", &number);

        if (number >= MAX_ARRAY_SIZE)
			{
             printf("\nError: Number out of range");
             return 1; //Return 1 in main() signals an abnormal exit.
             }

       //**********************************************************************
       //Prime Calculation Starts here

       int primes[MAX_ARRAY_SIZE]; 

       //This is a for loop, it will repeat the code until i <= number (i is less then or equal to number)
       //Add all the numbers 2..n to the vector "primes"

       int count = 0;

       for(int i = 0; i <= number; ++i)
            {
            primes[i] = i;
            count += 1;
            }
        primes[count] = -1;
        primes[0] = -2;
        primes[1] = -2;

       int p = 2;
       int pIndex = 2;
       //All this means is go through every item in the vector "primes"
       while( p * p < number ) //Repeat until p^2 is greater then number
           {
           for(int i = p; primes[i] != -1; ++i)
               {
               if( primes[i] % p == 0 && primes[i] != p)
                   {
                   primes[i] = -2;
                   }
               }

               do
                   {
                   pIndex += 1;
                   }
               while(primes[pIndex] == -2);
               p = primes[pIndex];
           }
       //**********************************************************************

        printf("\nThe prime numbers less than or equal to %d are:\n", number);
        int pos = 0;
        int pcount = 0;
        while(primes[pos] != -1)
           {
           if(primes[pos] != -2)
               {
               printf("\t%d\n", primes[pos]);
               pcount++;
               }
           pos++;
           }
        printf("The total count of prime numbers is: %d\n", pcount);

        bool validchoice = false;
        while(!validchoice) //The ! means boolean NOT, aka false becomes true, true becomes false.
            {
            char choice;
            printf("\nWould you like to enter the number again? (y/n): ");
            scanf("%s", &choice);
            if(choice == 'y')
                {
                validchoice = true;
                }
            else if( choice == 'n')
                {
           			printf("\n<<<<< Program Completed >>>>>\n\n");
                validchoice = true;
                return 0;
                }
            }

		}
}

i want to know whether all the code are in C language (not C++) and can my work give the conresponding ourput.

i know it maybe too time consuming for someone helping me to check my work.

but i just hope there are some kind ppl can rly help me.

thx by heart.
 
Physics news on Phys.org


Your code is pretty much straight C. The only thing that might be C++ about it is that you have variables declared throughout your code instead of at the top of your main() definition. If my memory is correct, this is a difference between C and C++. C++ allows you to declare variables anywhere as long is it is before they are used. C requires (or at least it used to) that variables be declared before any executable statements.

As far as "can my work give the conresponding ourput" what you've included looks like output from your program, so I'm not sure what you're asking.
 


Mark44 said:
Your code is pretty much straight C. The only thing that might be C++ about it is that you have variables declared throughout your code instead of at the top of your main() definition. If my memory is correct, this is a difference between C and C++. C++ allows you to declare variables anywhere as long is it is before they are used. C requires (or at least it used to) that variables be declared before any executable statements.

As far as "can my work give the conresponding ourput" what you've included looks like output from your program, so I'm not sure what you're asking.
no, i need to write a program which had the same output as the output in the above image.

so if the question is metioned i need to write it in C, will my work be treated as wrong? since u metioned maybe there are some c++ code in my work. =/

* is "bool" a C code? (oh i just found bool is not a c code..., what should i do..)
* sorry for my wrong spelling.
 
Last edited:


Sorry, didn't notice that you had used bool. Instead of
Code:
bool looping = true;
while (looping) {
...
}
do this:
Code:
int looping = 1;
while (looping) {
...
}
and similar for validchoice, except for false, use 0.
 


Mark44 said:
Sorry, didn't notice that you had used bool. Instead of
Code:
bool looping = true;
while (looping) {
...
}
do this:
Code:
int looping = 1;
while (looping) {
...
}
and similar for validchoice, except for false, use 0.

you mean i just need to change "bool" to "int" and "true" to "1" and "false" to "0" ? Then all my word is in C code?

PHP:
bool validchoice = false;
        while(!validchoice) //The ! means boolean NOT, aka false becomes true, true becomes false.
            {
            char choice;
            printf("\nWould you like to enter the number again? (y/n): ");
            scanf("%s", &choice);
            if(choice == 'y')
                {
                validchoice = true;
                }
            else if( choice == 'n')
                {
                       printf("\n<<<<< Program Completed >>>>>\n\n");
                validchoice = true;
                return 0;

change as:
PHP:
int validchoice = 0;
        while(!validchoice)
            {
            char choice;
            printf("\nWould you like to enter the number again? (y/n): ");
            scanf("%s", &choice);
            if(choice == 'y')
                {
                validchoice = 1;
                }
            else if( choice == 'n')
                {
                       printf("\n<<<<< Program Completed >>>>>\n\n");
                validchoice = 1;
                return 0;
 


Yes, that and moving all your declarations to the beginning of main(). I'm not sure, but I believe that C requires declarations to appear before any executable statements.
IOW, you can't do this (I don't think):
Code:
int main ()
{
    int i, j, s;
    int is_prime[N]; /* if is_prime[i] == 0, then i isn't prime */
    int prime_count = 0;

    printf ("\nThe prime numbers less than of equal to %d are:\n", N);
    int validchoice = 0;
    ...
Instead, do this:
Code:
int main ()
{
    int i, j, s;
    int is_prime[N]; /* if is_prime[i] == 0, then i isn't prime */
    int prime_count = 0;
    int validchoice = 0;

    printf ("\nThe prime numbers less than of equal to %d are:\n", N);
    ...
 


1.
http://u1.imgupload.co.uk/1258329600/082d_2009_11_16_101645.png
2.
http://u1.imgupload.co.uk/1258329600/134a_2009_11_16_101608.png

I just find some problems here. When I build and run my code in code:block, it works prefectly.

However, when I run the .exe which is generated by compiler, there're something that can not be shown.

Let see the above images.

If I try to enter 3-digit numbers,the statement "Error: Number out of range" is supposed to be shown.

Also, if i answer "n" when it asks me "Would you like to enter the number again? (y/n):", "<<<<< Program Completed >>>>>" is supposed to be shown.

Both supposed statement can not be shown correctly. instead of these is the problem exits immediately without asking entering any key.

So what can i do to solve this problem?
 


You aren't doing any checking to verify that the input number is three digits. After this code runs,
Code:
printf("\nEnter 3-digit positve integer: ");
scanf("%d", &number);
you should check that number < 1000.

Also, I think you're going to have some trouble with this code:
Code:
printf("\nWould you like to enter the number again? (y/n): "); 
scanf("%s", &choice);
choice is type char, but you're using a format string of %s, which is used for arrays of type char, not single chars. It would be best to declare choice as type int and use a different input function - getchar() or getc().
 


but why when i run it in compiler, it works fine?

and how can i check the number?
what correction i need to do in last part?
 
  • #10


You're not running it in the compiler. All that the compiler does is to translate your C code into machine code. Next, the linker brings in the machine code for library calls such as scanf and others, and does some other stuff to produce an executable image for your program. You are probably running your code in the debugger that you have with your C package.

Regarding my previous comment about scanf and a format string of %s, what happens if you enter yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy? Your program would allow this string, and it could cause bad results by wiping out what is stored in some other memory location.

Regarding checking the number, you can do something like this:
Code:
printf("\nEnter 3-digit positve integer: ");
scanf("%d", &number);
if (number <= 0 || number >= 1000)
{
    bad_input = 1;
}
else bad_input = 0;

You can then use the value of bad_input to control a while loop, in which you can again prompt the user to enter a positive value that is 3 digits or fewer.

I haven't commented on your overall code before, but it seems to me that you have a very long main function. Have you learned how to write functions yet? If you haven't learned about them, yet, never mind. 

Also, since your code is supposed to provide output that is the same as the output you have given, it is very important to have your control logic (if statements, loops, and so on) exactly reflect the logic of the program that produced the logic. Your program will look somewhat different, but the logic or your program and the one you are trying to mimic has to be almost exactly the same. This is easier to do if you started working with an algorithm in pseudocode, and it's harder to do if you are just making minor adjustments to your code. For example, checking that the input number is positive and three or fewer digits is something you haven't built into your algorithm, and will require a fairly substantial change in your program to implement.
 

Similar threads

  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 80 ·
3
Replies
80
Views
10K
  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 1 ·
Replies
1
Views
11K