C programming- printf statement giving "expression expected" error - c

This is my first posted question, so I apologize in advance if it doesn't make perfect sense. I am having trouble debugging a snippet of code I wrote. When attempting to compile the code, I am getting a weird error that is pointing to my printf statements. Here is the code...
int IsItPrime (int number, int *ptr);
int main(void)
{
int userinput;
printf ("This program is designed to tell wether or not \na number you enter is prime or composite \nType your number, and press Enter: “);
scanf ("%i", &userinput);
int *ptr = &userinput;
if(IsItPrime(userinput,ptr) == 1)
{
printf("The number: %i is a prime number”, userinput);
exit(0);
}
printf("The number: %i is a composite number”, number);
return 0;
}
int IsItPrime (int number, int *ptr)
{
int ceiling, i = 0;
ceiling = number / 2;
for (i = 2; i <= ceiling; i++)
if (number % i == 0)
return 0;
return 1;
}
I've tried everything I could think of at this point. It is probably something blatantly obvious but I am not too experienced in C. Any suggestions would be greatly appreciated!
Thanks!

number is local to the function IsItPrime you cannot access variable number in main function.
syntax error and press Enter: “); in line 6 (printf statement) and other printf statements

Others already pointed out that numbers cannot be accessed in the main function.
It would be more helpful if you posted your error message.
Anyway, here are two things that might help:
Did you include stdio.h ?
Never seen that before so not sure, how that happened: But the closing double quotes of the strings are not the normal double quotes but some sort of German or French closing double quotes.

Related

Why does my program crash after entering an integer? - C

I'm extremely new to C coding and i'm wondering why this is crashing like this? After I input a value and press enter, my program instantly crashes. I remember learning there are times when you use a & with an array in the scanf line and sometimes you don't. So when I remove the & it crashes instantly. I'm not sure how to troubleshoot this problem and would appreciate help.
What i'm trying to accomplish:
"Write a program that asks the user to enter a sequence of integers terminated by 0 ( the last number is 0) and prints all the numbers entered on one line."
The program crashes before I can enter the other variables. I was not done coding but since it keeps crashing instantly I can't go further.
int main () {
int ru[1000];
int read;
int nums;
int counts;
printf("Enter integers, press 0 to end user input \n");
while (nums>0) {
scanf("%d",&ru[nums]);
if (nums==0)
printf("%d ", ru[nums]);
}
system("pause>nul");
return 0;
}
As noted by several people already, you don't ever assign a value to nums at any point in your code, but make use of it in several places.
You should populate nums and whilst it's more than zero (this should probably be not equal to zero if you want to also include negative integers), store it's value into your array. You can track where you are in the array using another variable (I've picked the read one that you'd already declared), making sure that it is first initialised to 0.
Once the while loop is terminated, either by nums being zero or you filling up the array, you can then print out the numbers you've collected.
int main (void) {
int ru[1000];
int read=0;
int nums;
int counts;
printf("Enter integers, press 0 to end user input \n");
scanf("%d",&nums);
while ((nums>0)&&(read<1000)) {
ru[read++]=nums;
scanf("%d",&nums);
}
for(counts=0;counts<read;counts++) {
printf("%d ",ru[counts]);
}
printf("\n");
system("pause>nul");
return 0;
}
The scanf() you are using as the following prototype:
int scanf(const char *format, ...);
you should give the de pointer to the buffer variable as a parameter but your are giving a pointer to an array (pointer to a pointer).:
scanf("%d",&ru[nums]);
A solution to your problem might be:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int ru[1000];
int i = 0;
printf("Enter integers, press 0 to end user input \n");
do
{
scanf("%d",&ru[i]);
}while (ru[i]!= 0 && i++ < 1000);
for(i = 0; ru[i] != 0 ; i++)
printf("%d ", ru[i]);
return EXIT_SUCCESS;
}

While loop not repeating in c

I have to create a program that requests integer numbers from the user
repetitively though the keyboard until the user enters 0. I've gotten to the while loop and its not repeating and I'm not sure why. Any help would be greatly appreciated.
Thanks
Edit: I've fixed the loop in terms of it not repeating but now it's infinitely repeating and I have no clue why.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char first[30], last[30];
int n, even, odd, etotal = 0, ototal = 0;
printf("What is your first name?\n");
scanf("%s", &first);
printf("What is your last name?\n");
scanf("%s", &last);
// asks for name
printf("Enter a number\n");
printf("To quit the program enter 0\n");
scanf("%d", &n);
while (n!=0){
if(n%2==0){
printf("%d is even.\n",n);
etotal++; }
else{
printf("%d is odd.\n",n);
ototal++; }
}
return 0;
}
The loop isn't repeating because you have a return statement in the loop, that will leave the main function immediately. Just remove it.
You also have another problem that's much worse: Undefined behavior. Local non-static variables, like for example n in your code, don't get initialized, instead they have an indeterminate value. Attempting to use such an uninitialized variable leads to said undefined behavior.
You need to explicitly initialize the variable to some value before using it in the condition, for example to reorder the code so you read input before the loop and then also at the end of the loop.
Local variable n is uninitialized producing undefined results collaboratively called undefined behavior. Initialize it before entering loop:
n = 1;
And check result of scanf:
if (scanf("%d", &n) != 1)
// error
Because n is not initialized, so it has a random value:
int n, even, odd, etotal, ototal;
/* ... */
while (n!=0){
Loop is not working because you didn't initialize n and unnecessary return 0 inside the while loop. You can fix it with do..while as below. Because you have the input statement as your first statement, do..while is best opted here.
do{
scanf("%d", &n);
if(n%2==0){
printf("%d is even.\n",n);
etotal++;
}
else {
printf("%d is odd.\n",n);
ototal++;
}
} while (n!=0);
You use scanf to read your input, but after your if/else statement you are returning 0 hence you are leaving the program. So it doesnt matter if you write an even or an odd number.
while (n!=0){
scanf("%d", &n);
if(n%2==0){
printf("%d is even.\n",n);
etotal++; }
else{
printf("%d is odd.\n",n);
ototal++;
}
return 0;
}

scanf() to iterate through an unknown quantity of integers

So I'm trying to find the sum of an unknown amount of user-input numbers. Here's my code
int main()
{
int tmp1 = 1;
int tmp2 = 1;
int total = 0;
printf("Enter numbers for a sum: ");
tmp2 = scanf(" %d", &tmp1);
while(tmp2 > 0){
total+=tmp1;
tmp2 = scanf(" %d", &tmp1);
}
printf("total is %d", total);
return 0;
}
It gets stuck in an endless loop, and then once i hit ctrl-c to end it, it prints the correct sum. So what I'm doing wrong is how will i know when it's done scanning all the integers, and for the loop to end; since i'm not doing it correctly now
Decided to make it stop via ctrl d, and its acceptable. thanks
In your question, it is not clear how you expect your programme to understand that there won't be anymore numbers to input. Shall it be through a specific character? Or shall it just get a line of space-separated numbers and respond with a sum?
From your code, my most sensible guess is: You want it to understand that there won't be any more numbers to add, whenever it encounters a non-digital character. My guess is so, because this is almost exactly what your code does by checking the return value from scanf.
First of all, you have to change that tmp inside your loop into tmp1 because there isn't such a variable as tmp declared. edit: well, never mind
Then try running your programme, putting in any amount of white-space (space, tab or new-line) separated numbers, and then any non-digital character you like. May be a T for example, or ThoAppelsin, it won't matter. Programme won't get beyond the first character, in fact, not even beyond the first character. After that, you shall see that the numbers have been properly added together.
Since you're confused about a non-existent infinite-loop, my second guess is that you might be actually hoping it to get a single line of space-delimited numbers, and have the sum printed; and misinterpret your programme as "in infinite loop" while it merely expects further input from you, just like it does at the very beginning.
You won't get a 0 from non-redirected scanf("%d", &var);, unless you feed it with something that doesn't match to the format string to cause abnormal termination. If there's nothing left in the input stream to consume, it will just wait for more input. But say you give an 'a' to it, then all it can do is to give up and return zero, because it couldn't do a single assignment.
If you really are hoping to have a single line of numbers, then the minimal change I could offer would be something like this:
int main(void)
{
int tmp1 = 1;
char tmp2 = 0;
int total = 0;
printf("Enter numbers for a sum: ");
scanf("%d%c", &tmp1, &tmp2);
while(tmp2 == ' '){
total+=tmp1;
scanf("%d%c", &tmp1, &tmp2);
}
printf("total is %d", total);
return 0;
}
Of course, this approach has many vulnerabilities. However, if user is to input strictly a sequence like:
3 66 2 10 6
// mind the new-line
It will work fine. But if I'm allowed to change more than minimal, this is how I would do it:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void)
{
int LastNumber = 0;
int UpcomingCharacter = 0;
int Total = 0;
printf("Enter numbers for a sum: ");
while(scanf("%d%*[ \t]", &LastNumber) == 1)
{
Total += LastNumber;
UpcomingCharacter = getchar( );
if (!isdigit(UpcomingCharacter)) // eliminates a possible EOF return as well
break;
if (ungetch(UpcomingCharacter, stdin) != UpcomingCharacter)
{
fprintf(stderr, "%d: unexpected error with ungetch\n", __LINE__);
return EXIT_FAILURE;
}
}
printf("total is %d", Total);
return EXIT_SUCCESS;
}
Which should work fine on any whitespace-delimited sequence of numbers, excluding the new-lines of course.

Why am I getting a segmentation fault error with the following code?

I'm a Python programmer studying C. I receive a segmentation fault on the final printf() of the following code. I'm sure it has something to do with the expression but I'm not sure what the problem is. Unfortunately, the expression works in Python so I'm unable to get a more specific error message. I'm using the GCC compiler in Debian.
#include <stdio.h>
int main(void)
{
int n;
printf("Enter a two-digit number: ");
scanf("%d",n);
printf("The reversal is: %d\n", (n % 10) * 10 + (n / 10));
return 0;
}
Pass address of n to scanf() as
scanf("%d", &n);
try scanf("%d",&n);
it has no way to put anything into n unless it has a pointer to n
You need to provide a pointer to an int as the argument to scanf, not the int itself; &n rather than just n.

I am getting a couple errors with my C program. Please assist me with whatever I am doing wrong

I know this is probably a really dumb error on my part but I just started learning C. I wanted to make a basic calculator and I keep getting errors about the program expecting a const char * but I have a float. Also it says the last printf command (line 50 i believe) doesn't have the right syntax or correct form. Again I am really new so sorry for the incovinience. Thank you for all the help! My code is below.
#include <stdio.h>
#include <math.h>
int main()
{
char firstnum, secondnum, answer;
char function;
printf("Hello and welcome to my calculator!");
printf("Please input the function you would like to use");
scanf("%c", &function);
printf("Now please input the two variables.");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
if (function == '+')
{
answer = firstnum+secondnum;
}
else if (function == '-')
{
answer = firstnum-secondnum;
}
else if (function == '*')
{
answer = firstnum*secondnum;
}
else if (function == '/')
{
answer = firstnum/secondnum;
}
else
{
printf("Sorry that was an incorrect function. The correct inputs are +, -, *, /.");
}
printf(answer);
return 0;
}
Couple of things:
1)Change line, as you want to use floating point numbers
char firstnum, secondnum, answer;
should be
float firstnum, secondnum, answer;
2)Change line
printf(answer);
to
printf("Answer %f \n", answer);
Declare your variable like so -
float firstnum, secondnum, answer;
and change last printf to -
printf("Answer is: %f", answer);
Your final printf should be
printf("%f", answer);
or the nicer
printf("Answer : %f \n", answer);
This is because the declaration of printf is as follows
int printf ( const char * format, ... );
First parameter expected is the format of the output, the rest are the variables to be inserted.
In addition to this you should fix your datatypes as others have pointed out.
char firstnum, secondnum, answer;
:
scanf("%f", &firstnum);
This is not going to end well at all. You have to match the datatypes in your scanf to the format specifiers.
Those variables should be of type float although, to be honest, there's no real reason not to use doubles nowadays for the extra range and precision. In that case, make sure you use %lf for the format specifiers.
In addition, your final printf is lacking a format specifier totally which means it will attempt to use the answer variable as a specifier. Once you've fixed the data types as per above, this should be changed to:
printf ("%f\n", answer); // %lf for double.
Change your statement to printf("%f",answer);.
Also, you have declared your variables as chars , declare them as floats.
Recommended:
As you seem to be a beginner, I have an advice for you. Try reducing your program execution time and try to make the program efficient. So , instead of so many if---else blocks, you mmay have used switch case.

Resources