I am trying to compile my practice on functions. I tried many times to compile this and I bumped into this issue.
Here below is my code:
#include <stdio.h>
int displayFlow();
int main(){
int displayFlow();
}
int displayFlow(){
int try1,try2,try3;
printf("enter any given number...\n");
scanf("%d", &try1);
printf("if u entered above 10, ur out\n...please enter another guess...\n");
scanf("%d", &try2);
printf("if u entered below 5 then u won! !");
}
and this is the output I got:
function.c:22:5: note: declared here
int test(){
You declared your function again inside main. Remove int from infront of displayFlow.
#include <stdio.h>
int displayFlow();
int main(){
displayFlow();
}
int displayFlow(){
int try1,try2,try3;
printf("enter any given number...\n");
scanf("%d", &try1);
printf("if u entered above 10, ur out\n...please enter another guess...\n");
scanf("%d", &try2);
printf("if u entered below 5 then u won! !");
}
I come up with another mistake:you define the function displayFlow as 'int' type,but you don't write 'return' in the function when you realize it.
#include <stdio.h>
int displayFlow();
int main(){
displayFlow(); //you just abandon the return value?
}
int displayFlow(){
int try1,try2,try3;
printf("enter any given number...\n");
scanf("%d", &try1);
printf("if u entered above 10, ur out\n...please enter another guess...\n");
scanf("%d", &try2);
printf("if u entered below 5 then u won! !");
//Here is something absent. What do you want to return ? or you just want to return nothing? if so, you should modify the function return value type to 'void',please.
//return ??;
}
Just set return in method main, because he has to return int
int main() {
return displayFlow();
}
Related
I have this silly program with my silly problem. I am a very beginner. Let me tell you what I want to do and what is happening here:
What I want to do: I am basically trying to make a function for input which is named here as inp(). This function will ask for input using these two lines:
printf("Enter the Number: ");
scanf("%d", &dip);
When my program will get the number from the user, it will store that inside a variable, let's say dip and will use this number in our another two functions named squarefn and cubefn. I don't know what's going wrong here. But, I can't use the inp() properly to get the number from user.
Why I want to use the inp() function?: Basically, I just want to keep everything inside each function so whenever I need, I will just call my functions. I created inp() so that, I don't need to ask twice or type twice for input.
**What is the output?: ** It's showing some random value or trash value.
Need more information? Feel free to ask!
#include<stdio.h>
int squarefn(int x);
int cubefn(int cube);
int coic();
int printkor(int printkortesi);
int inp();
int main()
{
coic();
}
int squarefn(int input)
{
input = input * input;
return input;
}
int cubefn(int input)
{
input = input * input * input;
return input;
}
int coic()
{
int coi;
int x;
printf("Which one you want?\n");
printf("1. Square\n");
printf("2. Cube\n");
printf("Enter here: ");
scanf("%d", &coi);
int cubed = cubefn(x);
switch (coi)
{
case 1:
// printf("Enter the Number: ");
// scanf("%d", &x);
inp();
int dear = inp(x);
squarefn(dear);
int squared = squarefn(x);
printkor(squared);
break;
case 2:
printf("Enter the Number: ");
scanf("%d", &x);
cubefn(x);
int cubed = cubefn(x);
printkor(cubed);
break;
default:
printf("Error.");
break;
}
}
int inp()
{
int dip;
printf("Enter the Number: ");
scanf("%d", &dip);
return dip;
}
int printkor(int printkortesi)
{
printf("Printed: %d", printkortesi);
}
There is a lot of redundant code in your program, many of the statements don't do anything except taking CPU time . Read about Function Calls in C. Most of your doubts will be solved after a good read
return_type function_name( parameter list ) {
body of the function
}
You have return type of int, to receive value of function foo
int foo(int x)
{return x*x;}
int main()
{
int y =foo(5); //integer y takes value returned by function foo, that is 5
printf("%d\n",y); // This will print value 25
return 0;
}
Your code altered as below, should work now:
#include<stdio.h>
int squarefn(int x);
int cubefn(int cube);
int coic();
int printkor(int printkortesi);
int inp();
int main()
{
coic();
}
int squarefn(int input)
{
input = input * input;
return input;
}
int cubefn(int input)
{
input = input * input * input;
return input;
}
int coic()
{
int coi;
int x;
printf("Which one you want?\n");
printf("1. Square\n");
printf("2. Cube\n");
printf("Enter here: ");
scanf("%d", &coi);
int cubed = cubefn(x);
int dear = inp();
switch (coi)
{
case 1:
{int squared = squarefn(dear);
printkor(squared);
break;}
case 2:
{int cubed = cubefn(dear);
printkor(cubed);
break;}
default:
printf("Error.");
break;
}
}
int inp()
{
int dip;
printf("Enter the Number: ");
scanf("%d", &dip);
return dip;
}
int printkor(int printkortesi)
{
printf("Printed: %d\n", printkortesi);
}
Edit:
Fixed it, I just noticed there was variable declaration in the switch statement. Case statements are only labels. This means the compiler will interpret this as a jump directly to the label. So I added { } in switch and it should work now.
I am new to programming. I would like to call from functions(first, second, third the variables in function "enter" and in function "math" accordingly).
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void math (void);
void first (void);
void second (void);
void third (void);
void enter(void);
void scan(void);
int main()
{
first(); //function
second(); //function
third(); //function
enter(); //function
printf("\n\n Would you like to edit? (Y/N)\n\n");
scan(); //function
return(0);
}
Here is the user input:
void first (void){
float a;
printf("Enter First number: ");
scanf("%f",&a);
}
void second (void){
float b;
printf("Enter Second number: ");
scanf("%f",&b);
}
void third (void){
float c;
printf("Enter Third number: ");
scanf("%f", &c );
}
How can I call the variables from the user input to the function below?
void enter(){
float a,b,c;
printf("you have entered a: %f, b: %f, c:%f", a,b,c);
}
This is the loop in case the user would like to edit or continue with the initial input numbers.
void scan(void){
int ch;
scanf("%d", &ch);
if (ch==1){
main();
}else{
math();
}
}
Here I would also like to call the input variables from function (first, second third) in order to perform some math calculations.
void math (void){
float a,b,c;
float x,y,z;
x=a+b+c;
y= powf(x,2);
z=sqrt(y);
printf("Final Result of Addition is: %f \n Final Result of
Multiplication is: %f \n Final Result of squareroot is:%f\n
",x,y,z);
}
It's best if functions don't depend or modify data external to them. It's not always possible but it is better if they can be defined with that goal in mind.
In your case, the functions first, second, and third are doing essentially the same thing. It will be better to use just one function and give it a more appropriate name, such as read_float and change the return type so that the value input by the user is returned to the calling function.
Declare it as:
float read_float(char const* prompt);
Then, you can use it as:
float a = read_float("Enter the first number:");
float b = read_float("Enter the second number:");
float c = read_float("Enter the third number:");
etc.
The function enter does not correctly convey what it is doing. It should be renamed to something more appropriate, such as display_input_values. It can accept the values input by the user as its arguments.
Declare it as:
void display_input_values(float a, float b, float c);
and use it as:
float a = read_float("Enter the first number:");
float b = read_float("Enter the second number:");
float c = read_float("Enter the third number:");
display_input_values(a, b, c);
The scan function does not convey its meaning clearly either. You could divide scan to two functions -- one that returns you the option of whether to continue with the next inputs or to call a function that computes something with the user input.
You can get the option from the user by using a function named read_int function as:
int option = read_int("Enter 1 for next round of inputs and 2 to compute with current input:");
and use that returned value as:
if ( option == 2 )
{
// Do the computations
}
You also need another option to exit the program. The call to get the option needs to be:
char const* prompt = "Enter 1 for next round of inputs.\n"
"Enter 2 to compute with current input.\n"
"Enter 3 to exit program.\n";
int option = read_int(prompt);
Always add code to check whether scanf succeeded before proceeding to use the data that you were expecting to read into.
Here's an updated version of your code.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float read_float(char const* prompt);
int read_int(char const* prompt);
void display_input_values(float a, float b, float c);
void math(float a, float b, float c);
int main()
{
while ( 1 )
{
float a = read_float("Enter first number: ");
float b = read_float("Enter second number: ");
float c = read_float("Enter third number: ");
display_input_values(a, b, c);
char const* prompt = "Enter 1 for next round of inputs.\n"
"Enter 2 to compute with current input.\n"
"Enter 3 to exit program.\n";
int option = read_int(prompt);
if ( option == 3 )
{
break;
}
else if ( option == 2 )
{
math(a, b, c);
}
}
}
float read_float(char const* prompt)
{
float num;
printf("%s", prompt);
// For flushing the output of printf before scanf.
fflush(stdout);
if (scanf("%f", &num ) != 1)
{
print("Unable to read number. Exiting.\n");
exit(1);
}
return num;
}
int read_int(char const* prompt)
{
int num;
printf("%s", prompt);
// For flushing the output of printf before scanf.
fflush(stdout);
if (scanf("%d", &num ) != 1)
{
print("Unable to read number. Exiting.\n");
exit(1);
}
return num;
}
void display_input_values(float a, float b, float c)
{
printf("You have entered a: %f, b: %f, c:%f\n", a, b, c);
}
void math(float a, float b, float c)
{
// Do whatever makes sense to you.
}
For example declare float a,b,c; in your Main and change your functions to return a float
float first() { ... }
Then writea = first();
Local variables (as name suggests) are local and can't keep their values after function ends. You have two options:
Make functions first, second and third return their numbers and another functions get them as arguments.
Make a,b,c global variables.
The second one is much easier, but it's so called bad programming style.
I am trying to call a function from the main function, but it gave me a random number when I compiled and ran it. I want to ask from the user to enter a number in the yrBorn function, then return it to the main function and finally display it in the terminal.
int yrBorn(int);
#include<stdio.h>
int yrBorn (int yearBorn)
{
printf("Enter the year you were born in: ");
scanf("%d", &yearBorn);
return yearBorn;
}
int main ()
{
printf("%d",yrBorn);
}
You have to understand your code like this :
int yrBorn(int); // function prototype say it must accept a int argument
#include<stdio.h>
int yrBorn (int yearBorn) //it must accept a argument of int type because of this definition
{
printf("Enter the year you were born in: ");
scanf("%d", &yearBorn);
return yearBorn;
}
int main ()
{
printf("%d",yrBorn); // You are passing function pointer here not a function call use like yrBorn(1994)
printf("%d",yrBorn(1994)); //it will work :)
}
#include<stdio.h>
int yrBorn();
int yrBorn()
{
int yearBorn = 0;
printf("Enter the year you were born in: ");
scanf_s("%d", &yearBorn);
return yearBorn;
}
int main()
{
printf("%d", yrBorn());
}
Modified your program to work as you expect!
Your Syntax is not correct.
Suppose For Example , I want to make a Function That takes a number and returns it square , I would go like ,
#include<stdio.h>
int square(int); //Function Prototype Declaration Telling Compiler
//That there would be function named square whose
//takes an integer and whose return type is integer.
int main()
{
int x = 4;
int y ;
y = square(x); //Calling Square Function passing Value `x`
//And Storing it in `y`.
printf("%d\n" , y); //Printing `y`
//Or You Could As Well Do This
printf("%d" , square(x)); //Without Storing Printing return
//value of square(x)
return 0;
}
int square(int k){ //Function Definition Contains The Code What The
int r = k*k; //Function Does , Here it take the value passed
return r; //to the function in this case `x` and store it
//in `k` , and then initialise `r` to be `k*k`
} //and then returns `
So in your code
int yrBorn(int);
#include<stdio.h>
int yrBorn (int yearBorn)
{
printf("Enter the year you were born in: ");
scanf("%d", &yearBorn);
return yearBorn;
}
int main ()
{
printf("%d",yrBorn); //Here You are not calling function.
printf("%d" , yrBorn(0)); //This will work as in your prototype
//declaration you have declared
//function to take a int parameter and
//return int
}
What You Would Wanted I Suppose Was this
#include<stdio.h>
int yrBorn(void);
int yrBorn (void) //Here Function is Expected to take no arguments
//and return int value.
{
int yearBorn;
printf("Enter Your Birth Year : ");
scanf("%d" , &yearBorn);
return yearBorn;
}
int main(){
printf("%d" , yrBorn()); //You Would Call it like this
}
Notice there is nothing between parenthesis it is because function does not accept any arguments.
Please Read A Decent C Book with complete dedication forgetting everything what you already know or you would face similar misconceptions later too , I would recommend Watching this series Nptel - Introduction to C Programming and checking this The Definitive C Book Guide and List for Best C Programming Books For Beginners.
printf("%d",yrBorn);
This is not how a function is called. What you're doing instead of calling yrBorn is taking its address. That address is then being interpreted as an int and printed as such.
To call a function, you need to use the () operator. Any parameters to the function would go inside the parenthesis.
Also, your function is taking a parameter, but isn't doing anything with its value. Rather than take a parameter, this variable should be local to the function.
So with these fixes, your function would look like this:
int yrBorn ()
{
int yearBorn; // local instead of a parameter
printf("Enter the year you were born in: ");
scanf("%d", &yearBorn);
return yearBorn;
}
And you call it like this:
printf("%d",yrBorn());
I'm trying to create a program in which the user enters three integers, and another function checks to see that their input is valid. If the input is not valid, then the user must input three new numbers.
#include <stdio.h>
int sanitizedInput(int a, int b, int c)
{
if(scanf("%d", &a)==0)
{
printf("Not a number\n");
return 1;
}
else if(scanf("%d", &b)==0)
{
printf("Not a number\n");
return 1;
}
else if(scanf("%d", &c) == 0)
{
printf("Not a number\n");
return 1;
}
else
return 0;
}
int main()
{
int a;
int b;
int c;
int check = 1;
do
{
check = 0;
printf("Enter a number:");
scanf("%d",&a);
printf("Enter a number:");
scanf("%d",&b);
printf("Enter a number:");
scanf("%d",&c);
check = sanitizedInput(a,b,c);
}while(check);
}
However when I run this code, after entering three valid integers nothing shows up in the terminal and the code only terminates after entering 6 integers. (There are other functions and code in the main function, if that code is necessary to find the problem tell me and I will post it.)
Your code and your writing part is not matching.....
You should check the three numbers are valid or not firstly.
int sanitizedInput(int a, int b, int c)
{
if(a==0 || b==0 || c==0)
{
return 1;
}
else
{
printf("They are valid.....\n");
return 0;
}
}
Then if one of them are invalid, you will be able to take another three input for the returning value of 1. Because while(1) is a true condition.
remove
printf("Enter a number:");
scanf("%d",&a);
printf("Enter a number:");
scanf("%d",&b);
printf("Enter a number:");
scanf("%d",&c);
and stay with check = sanitizedInput(a,b,c);, and add printf("something\n") to the
else
return 0; block
and see what happens
In main() you are taking input for three numbers a,b,c and passing these variables as arguments for sanitizedInput().
Here, instead of checking the variables you are again using scanf() which will take new input.
if(scanf("%d", &a)==0)
The above if condition will not check the value of 'a', it will check the return value of scanf() with '0'.
if statement should be like this
if(a==0)
scanf("%d",&a);
this is same for all three variables.
In main function you are passing variables to sanitizedInput(), there you are checking variables and if not valid you are taking input again, so the variable which you changed are local to that function, which will not reflect in main(). So take care about that.
Hope this will help you.
In your while loop,you actually call scanf twice each variable(a,b,c),so you input number for 6 times.When sanitizedInput(a,b,c) finished,it return 0;so check is 0,the loop is over.I think you can do with in your main:
int main
{
int a;
int b;
int c;
int check = 0;
do
{
check = sanitizedInput(a,b,c);
printf("check = %d\n",check);
}while(!check);
return 0;
}
I have written two code for max and min. The first is without, the second with an extra function.
The first one works, but for second one minimum is always 1. Why?
What causes the problem?
(1) Code without function:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int x,n,min=x,max=1,cnt;
while(1){
cnt=0;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
printf("enter your numbers\n");
while (cnt!=n){
scanf("%d",&x);
cnt++;
if(x>max)
max=x;
if(x<min)
min=x;
}
printf("maximum is:%d\n",max);
printf("minimum is:%d",min);
getch();
system("cls");
}
return 0;
}
(2) Code with function:
#include <stdio.h>
#include <stdlib.h>
int maximum(int);
int main(int argc, char *argv[]) {
int n;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
maximum(n);
return 0;
}
//*****************************************
int maximum(int n){
int i,a,max=1,min=a;
printf("enter your number\n");
for(i=1;i<=n;i++){
scanf("%d",&a);
if(a>max)
max=a;
if(a<min)
min=a;
}
printf("maximum is:%d\n",max);
printf("minimum is:%d",min);
getch();
}
Your code causes undefined behavior. Undefined behavior means, anything could happen.
You have not initialized the variable a and you are doing min=a;
C99 section 6.7.8 Initialization:
If an object that has automatic storage duration is not initialized explicitly,
its value is indeterminate.
C99 section 3.18 Un-deļ¬ned behavior:
Behavior, upon use of a non-portable or erroneous program construct, of erroneous
data, or of indeterminately valued objects, for which this International Standard
imposes no requirements.
This means, compiler is free to do anything. It can crash your program, your program might print JLo pic on your monitor...Etc...
Your code invokes undefined behavior because the assignment min=x in first and min=a in second done without initializing x and a. In this case you may get anything, either expected or unexpected result or segmentation fault or program crash.
To fix this issue you can modify your code as
Code 1.
int x,n,min,max=1,cnt;
while(1){
cnt=1;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
printf("enter your numbers\n");
scanf("%d",&x);
min = x;
while (cnt!=n){
scanf("%d",&x);
...
...
Code 2.
int maximum(int n){
int i,a,max=1,min;
printf("enter your number\n");
scanf("%d",&a);
min = a;
for(i=1;i<n;i++){
scanf("%d",&a);
...
...