My complete attempt of a very difficult c problem

  • Thread starter ming2194
  • Start date
  • Tags
    Complete
In summary, the user enters three-digit positive integers and the program checks to see if any of the integers are prime. If so, the prime numbers less than or equal to that number are printed. The user is allowed to enter up to MAX_ARRAY_SIZE integers. After printing the prime numbers, the user is allowed to enter another integer and the prime numbers less than or equal to that number are printed again.
  • #1
ming2194
32
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
  • #2


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.
 
  • #3


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:
  • #4


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.
 
  • #5


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;
 
  • #6


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);
    ...
 
  • #7


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?
 
  • #8


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().
 
  • #9


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.
 

Related to My complete attempt of a very difficult c problem

1. What is the most difficult aspect of the c problem you attempted?

The most difficult aspect of the c problem I attempted was understanding the complex logic and syntax required to solve it. It took a lot of time and effort to familiarize myself with the language and its intricacies.

2. How did you approach solving the c problem?

I started by breaking down the problem into smaller, more manageable parts. Then, I researched and studied the relevant concepts and techniques needed to solve each part. I also sought help from other experts and consulted online resources for guidance.

3. What challenges did you face while attempting the c problem?

I faced many challenges while attempting the c problem, such as debugging errors, optimizing code efficiency, and ensuring the program could handle all possible scenarios. It also required a lot of trial and error and constant revision to improve the solution.

4. Did you encounter any roadblocks or setbacks during your attempt?

Yes, I encountered several roadblocks and setbacks during my attempt. There were times when I got stuck on a particular part of the problem and could not find a solution. It was frustrating, but I persevered and eventually found a way to overcome the obstacle.

5. What did you learn from your complete attempt of the c problem?

I learned a lot from my complete attempt of the c problem. I gained a deeper understanding of the language and its features, as well as problem-solving skills and perseverance. I also learned the importance of seeking help and utilizing available resources when facing a challenging task.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
705
  • Engineering and Comp Sci Homework Help
Replies
3
Views
925
  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
3
Replies
80
Views
8K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
17
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
19
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
981
  • Engineering and Comp Sci Homework Help
Replies
17
Views
1K
Back
Top