#include <stdio.h>
#define PI 3.14159
int Circle (int);
int Rectangle (int, int);
int main()
{
int a;
int b;
int c;
int d;
int area;
int AreaOfCircle;
int AreaOfRectangle;
int area1;
printf("Program to calculate area\n");
printf("1 - Circle\n");
printf("2 - Rectangle\n");
printf("\n");
printf("What option = \n");
scanf("%d", &a);
if(a=1)
{
area=Circle(b);
printf("Area= %d\n", area);
}
else if(a=2)
{
area1=Rectangle(c,d);
printf("Area= %d\n", area1);
}
return 0;
}
int Circle (int b)
{
int area;
printf("radius= \n");
scanf("%d", &b);
area=PI*b*b;
return area;
}
int Rectangle(int c, int d)
{
int area1;
printf("length= \n");
scanf("%d",&c);
printf("width= \n");
scanf("%d",&d);
area1=c*d;
return area1;
}
//I want to ask if my coding is ok .. but as I run it the output only ask for radius which is the calling function for circle .. but if i want to call rectangle the output also shows calculation for circle .. can someone help me to spot the mistake .. by the way this is my first coding about calling function and I just started learning coding c last month .. T-T
With C you use == to evaluate (e.g. if (x == 1)). "=" is assignment, so you'll always hit the first block.
Also, you're accepting parameters which you're then modifying, which is not good practice. Consider declaring your variables at usage time also, the "everything at the top of the block" paradigm is very dated.
This question is not about functional programming, this is an example of imperative programming.
Also, your input being poured directly into an integer is not bounds checked, consider a switch/case so you can add a default of "invalid input" and extend to different shapes in the future.
Yes bro just make if(a==1) and else if(a==1).
You've used the assignment = operator instead of the comparison == operator.
A statement like
if(a=1)
will assign a value of 1 to a and check then check for the non-zero value of a [which always evaluates to TRUE].
Instead, what you want is
if (a == 1)
which evaluates to TRUE if a contains 1. Same for other comparison(s) also.
Note: In your int Circle (int b) case you're storing the result to an int, which will truncate the result of a double/float multiplication. To get the exact value, make the area as float or double and use %f/ %lf format specifier.
Next, as per the logical part, you don't need to pass b, c, d as parameters to the called functions. Simply a local variable in the functions would do the job.
Related
Thank you to anyone reading this , I have a problem with a part of my code , I'm learning to do functions, and functions that are named enter and get_random work fine.
Now i want to add function addsum, but for some reason when i run the code with it, the debugger stops me when the for loop of checking the column finishes and the for loop that loops row should start .
Could anyone tell me what I am doing wrong? i only know the bare essentials of pointers, maybe that is the solution to my problems? thanks in advance.
This is the message from the debugger
passing argument 4 of ‘addsum’ makes pointer from integer without a cast [-Wint-conversion]
#include<math.h>
#include<stdio.h>
#include<stdlib.h> // libraries added from example
#include<time.h>
//(*) For a square matrix calculate the sum of elements under the main diagonal excluding it.
#define A -10
#define B 10
int main(){
void enter(int *x,int *y);
int get_random(int lbound,int ubound);
int addsum(int ro, int co, int s, int arr[ro][co]);
int r;
int c;
int row,col,sum=0;
enter(&r,&c);
srand48(time(NULL)); //Call srand48 with current time reported by `time` casted to a long integer.
// srand48 is used to reinitialize the most recent 48-bit value in this storage
int array[r][c]; // we decided its gonna be r rows and c columns
for (row=0;row<r;++row) // we cycle numeration of rows of matrix
{
for(col=0;col<c;col++) // we cycle numeration of columns of matrix
{
array[row][col]=get_random(B,A);// filling array with random numbers, taken from example
printf("%d ",array[row][col]);
addsum(row, col, sum, array[row][col]);
}
printf("\n"); // this is to break line after row 1,2 col 3, so it looks nicer
}
printf("\n");
printf("sum of array: %d\n", sum);
return 0;
}
void enter(int *x,int *y){ // we have to use pointers if we want more then one return from a function
printf("How man rows in array? ");
scanf("%d", x); // we use x instead of &x because we need the adress of the number not the value
printf("How man columns in array? ");
scanf("%d", y); // we use y instead of &y because we need the adress of the number not the value
}
int get_random(int lbound,int ubound)
{
return rand()%(ubound-lbound+1)+lbound; // function for generating random numbers
}
int addsum(int ro, int co, int s, int arr[ro][co])
{
if (ro>co){ //since we want the sum numbers below the diagonal row>col must be true
s=s+arr[ro][co];// if row>col than we add the number to our sum
return s;
}
}
I have tried to rewrite the function in several different ways, but i dont think its my syntax thats the problem.
Why is this code not running after printing of array if I take value of n>=9?
#include <stdio.h>
#include <math.h>
float mean_function(float array[],int n);
int main() {
int i,n;
float array[n],mean,sum=0,s2,summation,deno,C[i],elements;
printf("Enter No of Elements\n");
scanf("%d",&n);
printf("Enter Elements\n");
for(i=0;i<n;i++){
scanf("%f",&array[i]);
printf("%f",array[i]);
}
printf("sample variance(s2) : (sum((x-mean)*(x-mean)))/(n-1) /n");
printf("population variance(sigma2) : (sum((x-u)*(x-u))/n");
mean_function(array,n);
for(i=0;i<n;i++) {
deno=((array[i]-mean)*(array[i]-mean));
C[i]=deno;
summation=summation+C[i];
}
s2=((summation)/(n-1));
printf("s2=%f \n",s2);
}
float mean_function(float array[],int n) {
int i;
float sum=0,mean;
for(i=0;i<n;i++){ sum=sum+array[i]; }
mean=(sum/n);
return mean;
}
Why is this code not running after printing of array if I take value
of n>=9?
Some thoughts about your code (and about building programs in steps):
Arrays in C don't change in size once defined. VLAs are out for a variety of reasons. malloc() is in.
Use double, unless there is a specific reason to use floats.
Define and initialize one variable per line. Uninit vars can only result in an error as mentioned by #Jens.
Function declarations at the top (which you have done)
During development, there is no need to complicate things with a scanf (at least initially). It only adds an unwarranted layer of complexity. If you are testing statistical functions (mean, variance), put numbers in a pre-defined static array and verify functionality first.
C[i] as been declared with uninitialized i.
For this initial phase of building this program, I include a basic program.
I am not a fan of zero space between tokens (but ignore that)
Consider calling your array something other than 'array'.
Calculating the size of the samples array allows you to change the number of elements without changing anything else in code; which adds another layer of complexity to an already difficult phase.
#include <stdio.h>
#include <math.h>
double sample_mean(double* p, int n);
int main()
{
double samples[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 16.5, 2.3};
double mean = 0.0;
int size_samples = sizeof samples/sizeof(double);
printf("size_samples = %d\n", size_samples);
mean = sample_mean(samples, size_samples);
printf("Mean = %.2lf", mean);
}
// -------------------------------
double sample_mean(double* p, int n)
{
double mean = 0.0;
double total = 0.0;
for(int i = 0; i < n; i++)
total += *p++;
mean = total/n;
return mean;
}
Once this functionality is present (saved), you can start working on other stat functions. This way you can work step by step to get closer to the desired outcome.
Next up you can define sample_variance(double* p, int n) and work on that knowing that additional(new errors) are not coming from your code written so far.
Output:
size_samples = 8
Mean = 5.24
I hope it helps.
The code is likely not running because array[n] is declared with an uninitialized n. At the time you read n with scanf(), the array does not automatically "grow into the right size". You should either declare array big enough, or if you really want it to be user-defined, use malloc to allocate it (read the comp.lang.c FAQ) and all Stackoverflow questions tagged array...)
In addition, the scanf at some point fails. Note that when you enter numbers, you also have the "Enter" as a newline ('\n') in the input stream. You never read the newline so the next scanf fails.
This becomes obvious when you actually check the return value from scanf with code like this:
if (scanf("%f", &array[i]) == 1) {
/* successfully converted 1 item */
}
else {
/* scanf failed */
}
Usually what you want is to skip whitespace in the input. You do this by placing a space in the scanf format. Note that a single space tells scanf to skip any amount of white-space.
if (scanf(" %f", &array[i]) == 1) {
Here is the code from my program that has a issue:
#include "stdio.h"
int main(void)
{
int funcnum;
printf("Welcome \n");
printf("Please enter a number\n");
scanf("%i",&funcnum);
switch(funcnum) //funcnum is the variable you are checking for a match
{ //Open curly!
case 1: // is funcnum==1?
printf("You entered 1. This is now the Turkey Time function.\n"); // if funcnum==1, this will happen.
{
//DECLARE the "cookTime" function.(Above, outside the MAIN function)
//It will return a float, and is expecting two floats.
float cookTime (float);
//Below is a "global" variable -meaning available to all functions. These are declared outside of any function.
float cTim;
float weight;
printf("Welcome to the turkey timer...\n");
printf("Please enter a turkey weight \n");
scanf("%f",&weight);
cookTime (weight); //Calling (jumping to) the cookTime function and sending it "weight" variable.
printf("Cooking time is %.1f minutes.\n\n",cTim); //printing the returned value cTim.
printf("\tThank you for choosing the MaiCorp Timing System, don't forget the gravy! \n");
//DEFINE the function. Note -no semicolon. (just like in main's definition above!)
float cookTime (float w)
{
cTim = w*15;
return cTim; //We are sending cTim back to where we left Main.
}
}
break; //break makes the statement end and jump out of the curlies.
case 2: // is funcnum==2?
printf("You entered 2. This is now the Area function.\n");
{
//DECLARE the "area" function.(Above, outside the MAIN function)
//Looking at the declaration we can see that this function will return an int, and is expecting two int's.
int area (int, int);
//Here we declare a global variable. Meaning a variable that is available to all functions. These are declared outside of any function.
int ans;
int len,wid;
printf("Welcome to the rectangle area calculator...\n");
printf("Please enter a length\n");
scanf("%i",&len);
printf("Please enter a width\n");
scanf("%i",&wid);
area (len,wid); //Calling the "area" function, sending it the len and wid integers..
printf("Area is %i.\n",ans); //printing the returned value "ans"
//DEFINE the area function. Note -no semicolon. (just like in main's definition above!)
int area (int L, int W)
{
ans = L*W;
return ans;
}
}
break;
default: //default catches all non matches.
printf("You did not enter 1 or 2, meaning that you are not running a function this time.\n");
break;
} //close curly!
return 0;
}
When I run this program, the gcc version 4.6.3 compiler gives this:
main.c: In function 'main':
main.c:35:21: error: static declaration of 'cookTime' follows non-
static declaration
float cookTime (float w)
^~~~~~~~
main.c:17:21: note: previous declaration of 'cookTime' was here
float cookTime (float);
^~~~~~~~
main.c:67:19: error: static declaration of 'area' follows non-static
declaration
int area (int L, int W)
^~~~
main.c:47:19: note: previous declaration of 'area' was here
int area (int, int);
^~~~
exit status 1
This program is written in C in case anyone needs to know the programming language that the program is written in.
I have tried to fix the program by putting in "{}"'s and other code but it came to be of no use (meaning that the error did not resolve).
It would be great if a reputable programmer can assist me with this issue.
It looks like you are declaring a function within the main...? That is not only bad practice, but judging by the code there it looks like it's illegal. Unless you put static in front of it.
If you want to use the function, do NOT put it's return type before using the function. Instead of:
int area( int L, int W);
use
area(int L, int W);
Really weird to define a function within the main. Like I said, I don't think it's allowed, but if you REALLY want to do it, I would suggest putting static in front of the function.
Better yet, make a Name_goes_here.h file and put the functions in there. Then,
#include "Name_goes_here.h"
and use the functions like I told you. (except instead of int L, int W, replace it with pre-declared variables L and W without int in front of it.)
the following proposed code:
cleanly compiles.
properly prototypes the sub functions.
properly declares the sub functions.
eliminates most commentary that is just a repeat of the code.
Uses appropriate vertical spacing (between code blocks, between functions, between code activities).
fails to check the returned value from system functions (I.E. scanf()).
Follows the axiom: only one statement per line and (at most) one variable declaration per statement.
respects the right boundary of a printed output of the listing.
properly writes a 'float' literal
and now the proposed code:
#include "stdio.h"
// prototypes
int area (int, int);
float cookTime (float);
int main(void)
{
int funcnum;
printf("Welcome \n");
printf("Please enter a number\n");
scanf("%i",&funcnum);
switch(funcnum)
{
case 1:
printf("You entered 1."
" This is now the Turkey Time function.\n");
float weight;
printf("Welcome to the turkey timer...\n");
printf("Please enter a turkey weight \n");
scanf("%f",&weight);
float cTim = cookTime (weight);
printf("Cooking time is %.1f minutes.\n\n",cTim);
printf("\tThank you for choosing the MaiCorp Timing System, don't forget the gravy! \n");
break;
case 2:
printf("You entered 2."
" This is now the Area function.\n");
int len;
int wid;
printf("Welcome to the rectangle area calculator...\n");
printf("Please enter a length\n");
scanf("%i",&len);
printf("Please enter a width\n");
scanf("%i",&wid);
int ans = area (len,wid);
printf("Area is %i.\n",ans);
break;
default:
printf("You did not enter 1 or 2,"
" meaning that you are not running"
" a function this time.\n");
break;
}
return 0;
} // end function: main
int area (int L, int W)
{
int ans = L*W;
return ans;
} // end function: area
float cookTime (float w)
{
float cTim = w*15.0f; // << note the proper 'float' literal
return cTim;
} // end function: cookTime
I'm new to programming. So, details are appreciated.
#include<stdio.h>
#include<math.h>
int main()
{
float x, f(x);
printf("Enter x=");
scanf("%f", &x);
f(x)= 3*pow(x, 5)- 5*sqrt(x)-6*sin(x); /*in this line compiler shows error*/
printf("f(x)= %f", f(x));
return 0;
}
Excuse me for assuming that you are a C beginner looking for the way to write a function in C. There are many C tutorials out there, I recommend finding one for further learning.
Here is an example of using an actual C function for what you are doing.
#include<stdio.h>
#include<math.h>
/* first define the function */
float f(float x) /* function head */
{ /* start of function body */
return 3*pow(x, 5) - 5*sqrt(x)-6*sin(x);
} /* end of function body and definition */
int main(void)
{
float x; /* definition of function has already happened, so no f(x) here */
printf("Enter x=");
scanf("%f", &x);
printf("f(x)= %f", f(x) /* call the function */);
/* Note that some coding styles do not like calling a function
from within a more complex statement. Using a variable to
take the result of the function is preferred.
I chose this way to stay more similar to your own code.
*/
return 0;
}
The following could work.
#include <stdio.h>
#include <math.h>
int main()
{
float x, f;
printf("Enter x=");
scanf("%f", &x);
f = 3 * pow(x, 5) - 5 * sqrt(x) - 6 * sin(x);
printf("f(x)= %f", f);
return 0;
}
In your code, f(x) is a valid identifier, but not a variable. It's a very poorly written (and now invalid, as per the latest C standard) function prototype. You cannot assign to it, it's not a modifiable lvalue.
That is why in case of
f(x)= 3*pow(x, 5)- 5*sqrt(x)-6*sin(x);
compiler screams.
On why your code did not throw an error for the invalid format, it's the legacy support in compiler. In your case
float x, f(x);
is treated the same as
float x, float f ( int x ) ; //missing data type is treated as 'int',
// DON'T rely on this "feature"
I want to add numbers to an array using scanf
What did i do wrong? it says expected an expression on the first bracket { in front of i inside the scanf...
void addScores(int a[],int *counter){
int i=0;
printf("please enter your score..");
scanf_s("%i", a[*c] = {i});
}//end add scores
I suggest:
void addScores(int *a, int count){
int i;
for(i = 0; i < count; i++) {
printf("please enter your score..");
scanf("%d", a+i);
}
}
Usage:
int main() {
int scores[6];
addScores(scores, 6);
}
a+i is not friendly to newcomer.
I suggest
scanf("%d", &a[i]);
Your code suggests that you expect that your array will be dynamically resized; but that's not what happens in C. You have to create an array of the right size upfront. Assuming that you allocated enough memory in your array for all the scores you might want to collect, the following would work:
#include <stdio.h>
int addScores(int *a, int *count) {
return scanf("%d", &a[(*count)++]);
}
int main(void) {
int scores[100];
int sCount = 0;
int sumScore = 0;
printf("enter scores followed by <return>. To finish, type Q\n");
while(addScores(scores, &sCount)>0 && sCount < 100);
printf("total number of scores entered: %d\n", --sCount);
while(sCount >= 0) sumScore += scores[sCount--];
printf("The total score is %d\n", sumScore);
}
A few things to note:
The function addScores doesn't keep track of the total count: that variable is kept in the main program
A simple mechanism for end-of-input: if a letter is entered, scanf will not find a number and return a value of 0
Simple prompts to tell the user what to do are always an essential part of any program - even a simple five-liner.
There are more compact ways of writing certain expressions in the above - but in my experience, clarity ALWAYS trumps cleverness - and the compiler will typically optimize out any apparent redundancy. Thus - don't be afraid of extra parentheses to make sure you will get what you intended.
If you do need to dynamically increase the size of your array, look at realloc. It can be used in conjunction with malloc to create arrays of variable size. But it won't work if your initial array is declared as in the above code snippet.
Testing for a return value (of addScores, and thus effectively of scanf) >0 rather than !=0 catches the case where someone types ctrl-D ("EOF") to terminate input. Thanks #chux for the suggestion!