My code is not woriking. am I doing it wrong? [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I just have studied programming and english. I'm a newbie.
My code is supposed to show a sum of 1 to entered number.
(ex : if you enter 5, answer is 15 and if you enter 10, answer is 55)
Bu this code is not working. I have tried many times to fix it, but i don't know why this code is not working.
#include <stdio.h>
int main(void){
int i = 0;
int sum;
int j;
scanf("%d\n", sum);
for(j = 1; j <= sum; j++){
i = i + j;}
printf("%d\n", i);
return 0;
}

The problem with your code is a simple one, and a decent compiler will warn you about it:
testprog.c: In function ‘main’:
testprog.c:9:11: warning: format ‘%d’ expects argument of type ‘int *’,
but argument 2 has type ‘int’ [-Wformat=]
scanf("%d\n", sum);
^
The scanf function requires the address of items you want populated since it needs to change them. Passing the actual item (since C is pass-by-value) to a function could only ever change the copy rather than the original.
You can see the correct way to do it in the standard:
d: Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer.
As an aside, I've fixed that issue and added some more improvements, such as:
less confusing variable names (at no stage is your sum variable a sum of anything);
better (more logical) layout of code;
better scoping of temporary variables like i.
prompting the user for input so that they know what they're supposed to enter; and
checking for valid input by checking return value of scanf.
The code is:
#include <stdio.h>
int main(void){
int maxNum;
int sum = 0;
printf("Enter number to sum up to: ");
if (scanf("%d", &maxNum) != 1) {
fprintf(stderr, "Problem getting input\n");
return 1;
}
for (int i = 1; i <= maxNum; ++i) {
sum += i;
}
printf("Sum is %d\n", sum);
return 0;
}

Try this :
#include <stdio.h>
int main(void){
int i = 0;
int sum;
int j;
scanf("%d", &sum);
for(j = 1; j <= sum; j++){
i = i + j;}
printf("%d\n", i);
return 0;
}
Your mistake is just wrote scanf("%d\n", sum) instead of scanf("%d", &sum);

c language supports a type of call by value what transfers data copied.
So, you need to give the memory address that scanf function can write user's input to the sum variable memory.
scanf("%d", &sum)

Related

How to make a prompt in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
New programmer here, I have a few lines of code that I've finally managed to get to function but I'm running into a bit of a design issue. The code itself, at least to me, function as intended but I don't know how to get my terminal to display "Insert number here". This is how to code currently looks.
#include "cs50.h"
#include <stdio.h>
int main(void)
{
int n;
do
{
n = GetInt();
printf("Your number is!"/n);
}
while (n<1)
{
return n;
}
}
I'm looking for a way to get the same outcome as n = get_int ("Insert number: "); but that method brings up errors such as:
prompt.c:10:7: warning: implicit declaration of function 'get_int' is
invalid in C99 [-Wimplicit-function-declaration]
{ n = get_int("Insert number here %i\n", n);
or if I'm using n = GetInt("Insert number: "); I get this error message.
prompt.c:10:14: error: too many arguments to function call, expected 0,
have 2
{ n = GetInt("Insert number here %i\n", n);
~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/cs50.h:87:1: note: 'GetInt' declared here
int GetInt(void);
^
1 error generated.
Is there a way to get this to function so my terminal can prompt me with "Insert number here: ". Thank you and cheers!
If you want to print "Insert Number here:", you may use the prinf function.
#include <stdio.h>
int main()
{
int testInteger;
printf("Insert Number here: ");
scanf("%d", &testInteger);
printf("Your Number is %d",testInteger);
return 0;
}

Primes in C: RunTime Error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
#include <stdio.h>
int isPrime(int n){
int ndiv = 0;
int i;
for(i=1;i<=n;i=i+1){
if(n%i == 0){
ndiv = ndiv+1;
}
}
if(ndiv == 2){
return 1;
}
else{
return 0;
}
}
int nextPrime(int n){}
int main(){
int a = isPrime(7);
printf(a);
//printf(isPrime(4));
}
This code gives me a run time error, I think there's a problem here with the way I deal with data types while using a functions and the printf command, but I can't really figure it out. Help!
f in printf stands for "format". You need to supply a format string for printing: printf("%d\n", a)
Your isPrime is inefficient: you do not need to attempt dividing all the way up to the number itself. You could stop once you reach the square root of the number
Moreover, you could exit the loop early once you see that the number is not prime.
Once you fix these errors, your program would start running and producing the output that you expect.
Here is a small example of how to use printf. You can find more format specifiers here.
#include <stdio.h>
int main()
{
int a = 97;
int b = 98;
char hello[6] = "world";
printf("%d\n", a);
printf("%d\n", b);
printf("%s\n", hello);
return 0;
}
It is because your method of printing a variable is wrong. Here's the right one.
int main(){
int a = isPrime(7);
printf("%d",a);
}
I'm no C/C++ expert, but try
printf("%d", a);
%d is a format placeholder expecting an integer number, essentially.
That looks like an interesting isPrime function. Not very efficient at all, but different from what I have seen in the past. You can also loop over all the numbers between 1 and n, and just return false (or 0) if you find any that divise n. Or look up more efficient algorithms.

Cannot figure out why my code is not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've been trying to figure out what is wrong with my code for days; I can't seem to find it. If statements confuse me quite a bit, so I'm thinking I messed those up, but still not sure. All I know is that I'm super stumped and would love all of the help I can get.
#include <stdio.h>
// function main begins program execution
int main(void)
{
int numberOfDays = 0;
float numberOfMiles = 0;
float milesCharge = 0;
float milesTotal = 0;
float total = 0;
float subtotal = 0;
float tax = 0;
do {
printf("%s", "How many days was car rented?\t");
scanf("%d", &numberOfDays);
} while (numberOfDays < 1 );
do {
printf("%s", "How many miles were driven?\t");
scanf("%d", &numberOfMiles);
} while (numberOfMiles > 1);
if (numberOfMiles > 1 || numberOfMiles < 200) {
milesTotal = numberOfMiles * .40;
} else {
milesTotal = numberOfMiles * .35;
}
subtotal = milesTotal + numberOfDays * 15;
tax = subtotal * .06;
total = tax + subtotal;
printf("\nSubtotal:\t\t\t$%.2f\n", subtotal);
printf("Tax Amount:\t\t\t$%.2f\n", tax);
printf("Total:\t\t\t\t$%.2f\n", total);
printf("\n");
}
If numberOfMiles should be of type float you have to exchange the following line
scanf("%d", &numberOfMiles);
by
scanf("%f", &numberOfMiles);
or you can set the type to int.
--
If you want to avoid an endless loop, exchange
} while (numberOfMiles > 1);
by
} while (numberOfMiles < 1);
Btw. why not allow distances that are shorter than a mile?
e.g. by
} while (numberOfMiles < 0);
For more specific answers, you have to be more precise.
Compiling your program with gcc gives the following warning:
t.c: In function ‘main’:
t.c:21:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘float *’ [-Wformat=]
scanf("%d", &numberOfMiles);
^
The problem is, that scanf() will store the number entered at the location of numberOfMiles using a binary format used for int variables, but numberOfMiles is a float variable. The integer bit pattern interpreted as float will probably have a very different meaning, or even can be an illegal float value.
Changing the type of numberOfMiles from float to int fixes this problem.
You also should change the second while condition to while (numberOfMiles < 1).
I hope, this helps.
73, Mario

Defining a function outside main [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
#include <stdio.h>
#include <math.h>
main()
{
float i;
float x,N,sum;
printf("enter x and N respectively");
scanf ("%f %f", &x, &N);
sum = 0;
for (i=1;i<=N;i++){
sum = sum + ((pow(x,i))/(fact(i)));
}
printf ("%f", sum);
}
int fact(int n){
int i,temp;
temp = 1;
for (i=1;i<=n;i++){
temp = temp*i;
return temp;
}
}
this is to print the summation of the terms accordingly. I tried defining fact inside main but there was some control flow warning and I tried the same outside this time, yet wrong answer. Any help?
You cannot (you are forbidden by the C99 or C11 standard) define a function (like fact) inside another one (like main).
However, some C compilers, in particular GCC accept as an extension to have nested functions.
(I don't recommend using that extension, in particular if you are newbie in C)
Of course you'll better declare
int fact(int n);
before your main and leave its definition after.
Your code is wrong (in particular, better define main as int main(int argc, char**argv) then learn perhaps about getopt and use it). Compile it with all warnings & debug info (e.g. gcc -Wall -Wextra -g homework.c -o binaryprog...) then use a debugger (e.g. gdb ./binaryprog)
You need to add int fact(int n); before main() function to tell the compiler that a function called fact exists or you can add the whole function definition before.
You have to declare fact() above of main. There are 2 ways to do it.
First way: Add int fact(int n); above of main()
Second way: Copy the whole function above main(). So it looks like:
#include <stdio.h>
#include <math.h>
int fact(int n)
{
int i,temp;
temp = 1;
for (i=1;i<=n;i++){
temp = temp*i;
return temp;
}
}
main()
{
float i;
float x,N,sum;
printf("enter x and N respectively");
scanf ("%f %f", &x, &N);
sum = 0;
for (i=1;i<=N;i++){
sum = sum + ((pow(x,i))/(fact(i)));
}
printf ("%f", sum);
}

Program in C to sum each digit in an integer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
int main(){
int x;
int sum;
printf("Enter a positive integer: ");
scanf("%d", &x);
do{
sum += (x%10);
x=(x/10);
if((x/10)==0){
sum += x;
}
}
while((x/10)!=0);
printf("%d",sum);
}
Hey, I'm trying to get this to add up each digit within the entered integer, but the code I'm using keeps returning the wrong output. Would someone please help me fix my equation/code, because I'm not sure why the output is incorrect.
in your code
int sum;
is not initialized. use something like
int sum = 0;
Note: local variables are not automatically initialized [to 0 or anything], without explicit initialization their contents will be garbage. Thereby, using sum += (x%10); will lead to read before-write scenario, producing wrong result.
Here is a small math problem:
Somebody gave you ten apples, then someone else gave you two more. How many apples do you have?
The right answer is that this question is impossible to answer, because nobody told you how many apples you had at the beginning.
Your program suffers from the same problem: you failed to initialize sum before starting to add to it, so it has initial "garbage" value.
Changing the declaration to
int sum = 0;
will fix the problem.
Initialize your variable sum -
int sum = 0;
If you don't initialize your variable in C and some other language then the a garbage/random value is assigned to it when it is used in expression for the first time.
Late Answer
Since you've already found the problem with your code, I would like to provide a more concise alternative:
int x;
int sum = 0
int digit;
printf("Enter a positive integer: ");
scanf("%d", &x);
while (x > 0) {
digit = x % 10;
sum += digit;
x /= 10;
}
printf("%d", sum);
x % 10 extracts the last digit of the number, and then x /= 10 truncates the integer by removing the last digit.

Resources