functions in c programming - c

I am new to c ,while i am writing a basic program in c ,it is showing two answers ..1)when i declare and intialize variables separately 2)when I declare and initialize variable in a same line.can any one tell me my mistake please?
#include <stdio.h>
#include <stdlib.h>
void sum()
{
printf("enter the numbers to be added\n");
int x=scanf("%d",&x);
int y=scanf("%d",&y);
int sum=(x+y);
printf("the sum of two numbers is %d\n",sum);
}
int main()
{
printf("welcome to addition calculator\n");
sum();
return 0;
}
I am getting 2 as answer when i gave 3 and 4 as inputs

scanf("%d", &x) will store the read number into x. It will return the number of successfully read fields (1 in your case). If you assign that return value to x afterwards, you overwrite whatever the user entered with that 1. And 1 + 1 produce 2.
Solution:
int x;
int y;
scanf("%d",&x);
scanf("%d",&y);
As David reminds in comments, you might want to check that all fields were read successfully. For example, in your case, if you enter a non-digit, scanf will not resolve the %d field as successful, and will return 0. You can test this result to make sure the user did what they were supposed to do:
int x;
int y;
while (scanf("%d", &x) != 1) {
printf("Enter a NUMBER, you illiterate buffoon!\n");
}
while (scanf("%d", &y) != 1) {
printf("Enter a NUMBER! You managed with %d, how is this suddenly hard now?!\n", x);
}

scanf() function returns 1 if it scan successfully otherwise it return 0. That's why when you put an integer to x, scanf() return 1 and assign it to x(x=1). Same for y(y=1).
As x=1 and y=1.
sum = 2

Related

C Program to find prime number

Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}

While loop for only accepting integer value and exiting on any other input

I'm running this program in C to convert Fahrenheit to Celsius and need to accept only integer value from the user.
Please tell me how I can modify this?
int main() {
int x;
double y;
while(x>0) {
printf("Enter the temperature in Fahrenheit:");
scanf("%d", &x);
y=((x-32)/1.8)
printf("%f\n",y);
}
}
The reason your code does not work is that sometimes scanf does not read anything, so it does not modify x.
You know that scanf read something by checking its return value. It returns the number of "scanned" items. In this case, the number must be 1.
When scanf returns 0 instead, you should read and discard the data in the buffer. You do it by supplying %*[^\n] format specifier, which means "read and discard input up to '\n' character. The complete snippet that reads an int until success looks like this:
while (scanf("%d", &x) != 1) {
printf("Please enter a valid number:");
scanf("%*[^\n]");
}
Note: It goes without saying that you should fix your syntax error with the missing semicolon ; on the line that computes y.
You can use below code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
double y;
char str1[5];
int num1,i;
bool yes = true;
while(x>0)
{
printf("Enter the temperature in Fahrenheit:");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
if(!(str1[i]>=48&&str1[i]<=56))
{
printf("The value is invalid \n");
yes = false;
}
num1 = atoi(str1);
if(yes == true)
{
printf("This Number is %d\n",num1);
y=((num1-32)/1.8);
printf("%f\n",y);
}
}
}

Finding if a Number if Prime or not In C

I was writing a C Program to find if a number is prime or not. Everytime I run it and enter a number, the value of the input changes. PLease point out the loopholes.
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
y=getchar();
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
I use the Code::Blocks IDE with GCC Compiler
As the name implies, getchar() gets a single character from standard input. For example, if you enter 3, the y gets the ASCII code of the character '3', which is obviously not what you want.
Try scanf:
scanf("%d", &y);
getchar returns the ASCII code of a single character. Consequently, your program picks up the ASCII code of the first character of the number you input and checks if it is prime.
Instead, you need to read an integer:
scanf("%d", &y);
The complete program:
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
scanf("%d", &y);
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else {
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
}
Note: You can stop when x >= sqrt(y)
Well, you are calling getchar() which is used to input a single character and this is what happens in your case:
getchar() returns a character.
Character is then converted into integer when you store it in variable of type int.
Hence that integer contains the ASCII of input character i.e. 3 will be stored as 51 that is the reason input changes.
What you need to do is to input an integer instead of character. Try this:
scanf("%d", &y);
Hope this helps.
First answers are correct about input for y:
scanf("%d", &y);
Also, please note that you should loop until square root of x, and not more if your want to optimize your algorithm (I won't demonstrate here why, it's a mathematical property).
#include <stdio.h>
#include <math.h>
// ...
int x;
int x_max;
int y;
scanf("%d", &y);
x_max = (int)floor(sqrt(y));
for(x=2;x<=x_max;++x){
// ...

Need help terminating program when secret number is found

I'm trying to write a c program that uses a function that adds 2 integers to a random number. Which I have accomplished below. My problem is, I set a variable to a secret number and when that number is found, I need the program to terminate and it does not.
int x,y,secretnumber;
secretnumber = 5;
do
{
printf("Please enter two integers to be added together to a random number from 0-99 \n"
"Keep entering numbers until you hit the secret number!\n");
scanf("%i%i", &x, &y);
if(sumintsrand(x,y) != secretnumber)
{
printf("The summation of integers %i and %i and a random number is %i \n\n",x,y,sumintsrand(x,y));
}
else
{
printf("You have found the secret number: %i! Goodbye!\n", secretnumber);
}
}
while(sumintsrand(x,y) != secretnumber);
return 0;
}
int sumintsrand(int x, int y)
{
int sumintsrand = x + y + rand()%5;
return sumintsrand;
}
If anyone has any idea where I'm going wrong I would really appreciate it
UPDATE
I compiled your program with my earlier suggested mod, and I didn't get silly large numbers, so pass on that - different question?
It seems a bit strange to keep changing the random number - the same guess might fail once but work the next time. Also there is a confusion about whether the range is 5 or 99.
So I've simplified your work, to make you guess two numbers that sum to the secret number. If that's not your intention, perhaps you can draw on my code.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAXVAL 5
int main(){
int x, y, secretnumber, testval;
srand ((unsigned)time(NULL));
secretnumber = rand() % (MAXVAL+1);
do
{
printf("Enter two integers to be added to equal a secret random number from 0-%d\n"
"Keep entering numbers until you hit the secret number!\n", MAXVAL);
if (scanf("%d%d", &x, &y) != 2)
return 0; // exit program
testval = x + y;
if(testval != secretnumber)
printf("Sorry - try again!\n\n");
else
printf("You have found the secret number: %d + %d = %d! Goodbye!\n",
x, y, secretnumber);
}
while(testval != secretnumber);
return 0;
}
You are calling your sumintsrand() function thrice. Each time, the result of the function is going to be different based on what rand() returns.
Your call to sumintsrand()within the while loop may have found the secret number, but that is not retained. You need to store it for checking whether while loop needs to be terminated.
UPDATE:
int sum = 0;
do {
scanf("%i%i", &x, &y);
sum = sumintsrand(x,y);
} while(sum != secretnumber);
It's not working, because in that line while(sumintsrand(x,y) != secretnumber); you are calling sumintsrand a second time - and it gives other result.
Possible solutions:
Save the result of first call of sumintsrand and check if it(the saved result) is the same as secretnumber
Use break
Make bool variable which will end the loop - at the beginning it will be true, when you will find the number just set it to false.

How to generate a new number each time my program loops?

I'm trying to right a program in C where I have to ask the user a certain multiplication question, I'm using rand() to generate the numbers.
If the user gets the answer wrong, then they will be asked to enter it again once they get it right, when they do get it right, the program should loop and ask the user a different question.
I'm using a separate function to generate the answer each time the 2 random values are passed to that function.
My problem is that once I get the answer correct, the program loops and asks the same question, it picks the same number! so how do I make it that everytime it loops, it picks a different number?
#include <stdio.h>
int multiply(int x, int y);
int main()
{
srand (time(NULL));
int x = rand()%20;
int y = rand()%20;
int i, answer;
i = multiply(x,y);
do {
printf("what is %d multiplied by %d?:", x, y);
scanf("%d", &answer);
while(answer != i)
{
printf("wrong try again!");
scanf("%d", &answer);
}
printf("very good!\n");
} while(i==answer);
}
int multiply(int x, int y)
{
int k;
k=x*y;
return k;
}
You need to move the assignments of x and y into the loop. This way they will get a new value in each round. In fact, you can move their whole definition in there.
Moreover, the loop coondition while(i==answer) is superfluous as at that point it is always going to be true. For the sake of clarity, you should replace it with true to make it explicit that it is an infinite loop. (And you may want to extend your program with a way to exit gracefully, e.g. if 'q' or an empty string is entered - but I will leave this as an exercise for you :-).
while(true) {
int x = rand()%20;
int y = rand()%20;
int i, answer;
i = multiply(x,y);
printf("what is %d multiplied by %d?:", x, y);
scanf("%d", &answer);
while(answer != i)
{
printf("wrong try again!");
scanf("%d", &answer);
}
printf("very good!\n");
}
Abstractly, your logic should go like this:
// seed random number generator
while (true) // ask infinitely many questions
{
int x, y, expected_result; // populate randomly
printf("Please compute the result of %d and %d: ", x, y);
while (read_answer() != expected_result)
{
printf("Sorry, wrong answer. Try again: ");
}
}
That is, for each question you generate new parameters.
You just need to implement read_answer() as a helper function that reads one integer from the input, e.g. using fgets and strtol.

Resources