Homework help for a beginner in C programming - c

I have to separate a program I created into 1 main function and 3 user defined functions.
The instructions for my work is as follows:
// gets an integer from the user and returns it // make 3 calls to
this function: // get the length of the rectangle from the user and
return it to main // get the width of the rectangle from the user and
return it to main // get the radius of the circle from the user and
return it to main int GetNum(void);
// takes two arguments, the length and width of the rectangle and
returns the area int CalculateAreaR(int length, int width);
// takes one argument, the radius of the circle and returns the area
double CalculateAreaC(int radius);
I am pretty stuck though. I've written the functions but can't correctly call them to the main function. I know it may be simple but there is just something im not seeing right. the code I have written is as follows:
#include <stdio.h>
#include <math.h>
#define PI 3.14
int GetNum(void)
{
int length;
int width;
int radius;
printf( " Please enter the length of a rectangle \n");
scanf(" %d", &length);
printf(" Please enter the width of a rectangle \n");
scanf(" %d", &width);
printf(" Please enter the radius of a circle \n");
scanf(" %d", &radius);
return length, width, radius;
}
int CalculateAreaR(int length, int width)
{
return length*width;
}
double CalculateAreaC(int radius)
{
return PI*radius*radius;
}
int main(void)
{
int length;
int width;
int radius;
int areaR;
double areaC;
GetNum();
printf("\nThe area of the rectangle is %d\n", CalculateAreaR);
printf("\nThe length is %d, the width is, %d and thus the area of the rectangle is %d\n\n", length, width, areaR);
areaC = CalculateAreaC();
printf("\nThe area of the circle is %.3f\n", CalculateAreaC);
printf("\n\n The radius of the circle is %d and the area of the circle is %.3f\n\n", radius, areaC);
return 0;
}
Can anyone please help me? I'd be very thankful. Im trying my best to learn.

In C, a function can only return a single value via the return statement.
For a simple program, you could make your GetNum() function modify global variables.
// variables placed outside any function have global scope
int length;
int width;
int radius;
int GetNum(void)
{
printf( " Please enter the length of a rectangle \n");
scanf(" %d", &length);
printf(" Please enter the width of a rectangle \n");
scanf(" %d", &width);
printf(" Please enter the radius of a circle \n");
scanf(" %d", &radius);
return 0;
}
This shows declaring the variables at global scope, then using them in the function.
A more advanced, but usually better, way to return multiple values is for the caller to pass a pointer to a variable, and the function to use the pointer to set the variable. #bash0r showed this technique in his/her answer.
Now, to call a function, you must always put parentheses after the function name. Always always always. If you put the name without the parentheses, you are not calling the function; you are just referring to the function (you are referencing the address of the function). You have a couple of places where you wanted to call functions but you didn't put the parentheses.
Some functions take arguments. When you call a function that takes arguments, you need to pass the arguments in. Here is an example of a function that multiplies a number by a factor and then adds a term.
float adjust_num(float x, float factor, float term)
{
return x * factor + term;
}
// example of calling the above:
float adjusted;
adjusted = adjust_num(input_value, scale_factor, 0.0f);
In the example, we pass in input_value and scale_factor. We don't have a constant or variable with a term to add, so we just pass in a literal 0.0 value. So for this example, we are passing all the required arguments. Then the function returns a value, and we collect that output value in the variable adjusted.
If you do try the global variables as I suggested, you will need to delete the lines that declare the variables inside the main() function. Otherwise you will declare two sets of variables, the ones private inside of main() and the other, global ones. The ones in main() will sort of hide the global ones; we call that "shadowing", as in "the local variables inside of main() are shadowing the global variables."
Good luck.

int GetNum(void)
{
...
return length, width, radius;
}
You can't do that, C functions can only return 1 return value. You can basically follow three approaches to solve this problem:
store length, width, radius in variables that are outside of the function (ie, global)
package the elements to be returned in a struct ure
pass pointers to variables containing length, width, radius to that function
Working with global variables is the easiest of these three, and probably sufficient in this case, but in real programs we tend to avoid global variables.
printf("\nThe area of the rectangle is %d\n", CalculateAreaR);
You can call a function inside a call to another function (in this case printf) you have to call the function, what you're doing here is giving a pointer to the function to printf. Also, if you declare a function as taking parameters, you have to give these parameters to the function, like this:
printf("\nThe area of the rectangle is %d\n", CalculateAreaR(length,width));
A comparable issue can be found here:
areaC = CalculateAreaC();
printf("\nThe area of the circle is %.3f\n", CalculateAreaC);
Same remarks as above (parameters should be given), however here you already store the result in areaC so you can just say
printf("\nThe area of the circle is %.3f\n", areaC);

You can't return 3 values at the same time. If you need more than 1 return value you must do it like this:
int x = 0, y = 0, z = 0;
myFunction( &x, &y, &z );
Where myFunction must be declared like this:
void myFunction( int *x, int *y, int *z ) { }
You can read from/write to x, y and y via the * operator. You can use it like this:
*x = 10; // write 10 to the variable behind x.
*y = *x; // write to variable behind y and read from variable behind x.
int *x is called a pointer variable/parameter. It stores an address instead of a value. With pointers you can 'point' to another variable and modify it's value from somewhere else (for example in a function which you call). The size of a pointer depends on the operating system (32-bit systems have 4 byte addresses and 64-bit systems have 8 byte adresses).

Inside of the main function, you should receive the input from your input function: getNum();
I usually like to encapsulate input data into separate functions so I specifically know that this function only does one thing. The whole point of declaring length, width, and radius inside the main is to actually be able use those values when I need them. The simplest approach can be done like so:
Function:
int get_length()
{
int length = 0;
printf("Enter length of rectangle: ");
scanf("%d", &length);
return length;
}
Main Function:
int main()
{
int length = 0;
length = get_length();
// collect additional input...
return 0;
}

Related

function declaration and call and definition in c

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) {

Bubblesort a 2-D Array - C

I am trying to use Bubblesort for a 2-D array, using a custom sized 2D Array with the max limit of [100][2]. I am a beginner at this, so i am not great at formatting code properly so shedding light would be great.
my input
How many items of data do you wish to enter? 4
Please enter in the X coordinate: 4
Please enter in the Y coordinate: 4
Please enter in the X coordinate: 3
Please enter in the Y coordinate: 3
Please enter in the X coordinate: 2
Please enter in the Y coordinate: 2
Please enter in the X coordinate: 1
Please enter in the Y coordinate: 1
So that prints out how many numbers you wish to enter from a custom array input.
output(Meant to compare each array and switch to ascending order).
Printing in Ascending Order:
[4][3]
[3][3]
[3][3]
It prints 3 arrays not 4, and doesn't print out any of the numbers i entered.
so
But could anybody shed some light on this? It is specifically the Bubblesort function.
int main()
{
int arrayHeight, array[100][2];
printf ("***** Bubble Sort ***** \n");
InputArray(array, arrayHeight);
}
int InputArray(int array[100][2], int arrayHeight, int swap)
{
int i, xCoord, yCoord;
printf("\n How many items of data do you wish to enter? ");
scanf("%d",&arrayHeight);
for(i=0; i<arrayHeight; i++)
{
printf("Please enter in the X coordinate: ");
scanf("%d", &xCoord);
printf("Please enter in the Y coordinate: ");
scanf("%d", &yCoord);
array[i][0] = xCoord;/* Name of XCoordinate and position within Array*/
array[i][1] = yCoord;/*Name of YCoordinate and position within Array*/
}
DisplayArray(array, arrayHeight);
}
int DisplayArray(int array[100][2], int arrayHeight, int swap)
{
int i, j;
printf("\n The 2-D Array contains : \n");
for(i=0; i<arrayHeight; i++)
{
printf("[%d][%d]\n\r", array[i][1], array[i][0]);
}
BubbleSort(array, arrayHeight);
}
int BubbleSort(int array[100][2], int arrayHeight)
{
int swap, i, j, k;
printf("\n Printing in Asending Order: ");
for (i = 0; i <arrayHeight-1; i++)
{
if (array[i][0] > array[i][1 + 1])
{
array[1][i] = array[1][0+1];
swap = array[1][i];
array[i][1 + 1];
printf("\n [%d][%d] ", array[i][0], array[1][i]);
}
}
}
There's a fair amount of things going on here.
Your Question
Your program is printing out strange parts of your array because of the way you're calling printf from within BubbleSort. While BubbleSort is still running, your array isn't fully sorted. However, the function calls printf after each attempt at swapping array elements. If you'd like to print your whole array after sorting, it would be better to allow the sorting function to run to completion, then print out the array in full afterwards.
Other Stuff
There are a lot of points tangential to your question that I'd like to raise to help you out from a style and correctness perspective. Also, some of these are rather interesting.
#include Statements
When compiling this, you should be getting several warnings. If you're using gcc, one of those warnings will be something like:
main.c: warning: incompatible implicit declaration of built-in function ‘printf’
printf ("***** Bubble Sort ***** \n");
This states that the function printf has been implicitly declared when it was called. That is, the compiler inferred that a function printf exists because you called a function named printf. The problem is that it knows nothing about this function other than that it probably exists. This means the complier doesn't know what the function is supposed to return or what arguments it is supposed to accept, so it cannot help you if you use it inappropriately. To avoid this problem, you should include the standard C Input/Output headers in your program like so:
#include <stdio.h>
The stdio.h header file includes many functions besides just printf. Check out man 3 stdio for more information on it.
Define or Declare Functions Before Calling Them
One of the less-modern aspects of C is that it runs through your program from top to bottom. Many modern languages allow you to put your function declarations anywhere in your code and then it works things out on its own. Javascript's variable and function hoisting is an example of this.
Because C does not do this, you should define or declare your functions before you call them. If you call them without a declaration or definiton, the compiler will fall back to the default function signature extern int <function_name>(); That is, if you do not supply a declaration or definition for your function, C will assume that function is defined elsewhere, returns an int, and takes an unspecified number of arguments.
In this program, the function DisplayArray is defined with three arguments:
int DisplayArray(int array[100][2], int arrayHeight, int swap);
However, it is called with only two arguments:
DisplayArray(array, arrayHeight);
This can only happen because when the function is first called, it hasn't yet been defined, so the compiler, without knowing any better, assumes the call is made correctly.
When this is corrected (the definition is put above the first call), the compiler will throw an error stating that the function DisplayArray takes three arguments, but it was called with only two.
Calling Functions / Program Structure
The most oft-cited benefit of creating functions in your code is modularity. This is the idea that you can freely re-use code at different points in your program while knowing what that code is going to do. This program sacrifices this benefit by creating a sort of function-chain, where each function calls the other. InputArray calls DisplayArray, and DisplayArray calls BubbleSort.
This means any time you'd like to print an array, you must be okay with it being bubble-sorted as well. This is considered bad practice because it reduces the amount of times calling the function is useful. A more useful function would be one that displays the array but does not call BubbleSort or modify the array in any way.
Bubble Sorting
Your question doesn't specify exactly how you'd like to bubble sort, but the function here doesn't implement the BubbleSort algorithm. Generally, it's best to make sure you understand the algorithm before applying it to strange cases like 2-D arrays. I've included a working example below, which I hope helps get you on the right track.
Briefly, note that there two loops in a bubble sort:
* an inner loop that runs through the array and swaps neighboring elements
* an outer loop that runs the inner loop until the entire array is sorted
Minor Things
C programs generally prefer snake_case to CamelCase, but more generally, you should do what works best for you. If you're on a team, use a style consistent with that team.
All of the functions in this program return int, yet none of them actually use a return statement or return a useful value. If you have a function does not return a useful value, return void instead (e.g. - void DisplayArray(int array[100][2], int arrayHeight)).
Your displayArray function swaps the position of x and y. printf will display parameters in the order you specify unless directed otherwise. Check out man 3 printf for more on that function.
Working Example
#include <stdio.h>
void DisplayArray(int array[100][2], int arrayHeight)
{
int i, j;
printf("\n The 2-D Array contains : \n");
for(i=0; i<arrayHeight; i++)
{
printf("[%d][%d]\n\r", array[i][0], array[i][1]);
}
}
void BubbleSort(int array[100][2], int arrayHeight)
{
int i;
int swap[2];
int swapHappened = 1;
// the outer loop runs until no swaps need to be made
// no swapping implies the array is fully sorted
while (swapHappened) {
swapHappened = 0;
// the inner loop swaps neighboring elements
// this is what 'bubbles' elements to the ends of the array
for (i = 0; i < arrayHeight-1; i++)
{
if ((array[i][0] > array[i+1][0]) ||
(array[i][0] == array[i+1][0]) && (array[i][1] > array[i+1][1]))
{
// if a swap happens, the array isn't sorted yet, set this variable
// so the `while` loop continues sorting
swapHappened = 1;
// save the higher-value row to a swap variable
swap[0] = array[i][0];
swap[1] = array[i][1];
// push the lower-valued row down one row
array[i][0] = array[i+1][0];
array[i][1] = array[i+1][1];
// put the saved, higher-value row where the lower-valued one was
array[i+1][0] = swap[0];
array[i+1][1] = swap[1];
}
}
DisplayArray(array, arrayHeight);
}
}
int main()
{
int arrayHeight, array[100][2];
printf ("***** Bubble Sort ***** \n");
int i, xCoord, yCoord;
printf("\n How many items of data do you wish to enter? ");
scanf("%d",&arrayHeight);
for(i=0; i<arrayHeight; i++)
{
printf("Please enter in the X coordinate: ");
scanf("%d", &xCoord);
printf("Please enter in the Y coordinate: ");
scanf("%d", &yCoord);
array[i][0] = xCoord;/* Name of XCoordinate and position within Array*/
array[i][1] = yCoord;/*Name of YCoordinate and position within Array*/
}
DisplayArray(array, arrayHeight);
BubbleSort(array, arrayHeight);
DisplayArray(array, arrayHeight);
return 0;
}
I don't get what you are trying to do with your BubbleSort function.
But just to get a few things right :
if (array[i][0] > array[i][1 + 1])
this shouldn't work, your array was initialized as "int array [100][2]". Conventionally the highest number that should be in the second square bracket is 1. (1+1 =2, by the way)
array[1][i] = array[1][0+1];
swap = array[1][i];
C executes code in a sequential basis, so the array[1][i] is overwritten with array[1][0+1] even before the original value is saved in the 'swap' variable.
array[i][1 + 1];
This line of code does not seem do anything.
If you could tell whether you are trying to sort 'by element' or by 'line' (ie by each array in the 2D array), maybe we could help you approach the problem correctly.

C program that results in a static and non-static declaration error

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

Programming C calling function area of circle and rectangle

#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.

Pointers as arguments to a function that calls scanf

I am having some trouble with pointers.
The gist of it is, I am trying to define pointers in one function and call that function in my main to use those pointers.
The exact instructions for my assignment are as follows:
Write two functions, one that reads three numbers from the keyboard
and one that prints some information about these three numbers.
Input Function
Write a function that has three integer pointer parameters, and that
asks the user to enter three whole numbers. The values entered at the
keyboard should be read into the addresses stored in the pointer
parameters.
Note: recall that scanf requires the address of a variable and that
pointers store addresses.
Printing Values
Write a second function called a2question2, with no return value and
no parameters. The function should declare three integer variables
and then use your input function to read values into these variables.
The function should then print the sum, the average, the product, and
the smallest and largest of these numbers.
Here is what I have so far:
int pntloc (int *x, int *y, int *z){
int a = 0;
int b = 0;
int c = 0;
printf("Please enter integer #1: ");
scanf ("%d", & a);
printf ("Please enter integer #2: ");
scanf ("%d", & b);
printf("Please enter integer #3: ");
scanf ("%d", & c);
*x = &a;
*y = &b;
*z = &c;
return *x, *y, *z;
}
// Fourth function
main (){
int x, y, z;
pntloc(x, y, z);
int sum = 0;
int average = 0;
int product = 0;
int smallest = 0;
int largest = 0;
printf ("%d", x);
}
However, after the program asks me for the three integers, it crashes without doing anything.
The first function works fine by its self (tested it by making it the main function without parameters and printed the pointer values) ie:
printf ("%d", *x);
So I guess the values are just not passing from one function to the next. I've tried various ways of writing the first and second function but nothing seems to work.
The best I got was getting the program not to crash but the printed value was nowhere to what I inputted before.
Any ideas how to do this?
Your program is probably crashing because of two errors:
1) You are returning the local address of the variables a, b and c:
*x = &a; // This line says follow the 'x' pointer, and set the value there to
// the address of 'a'
Since a is defined locally (i.e. inside the function), that address is invalid once the function returns.
What you probably meant is:
*x = a; // Follow the 'x' pointer, and set the value there to the value of 'a'
2) You're not passing pointers to pntloc() (your compiler should be warning you about this one)
int x, y, z;
pntloc(x, y, z); // The passes the VALUES of x, y and z
You probably meant:
pntloc(&x, &y, &z); // Pass the ADDRESSES of x, y and z
Some other improvements that aren't causing your crash:
You can massively shorten pntloc() by not using the local variables:
void pntloc (int *x, int *y, int *z){
printf("Please enter integer #1: ");
scanf ("%d", x);
printf ("Please enter integer #2: ");
scanf ("%d", y);
printf("Please enter integer #3: ");
scanf ("%d", z);
}
Note that the & has been removed inside the scanf() call. You asked about it in comments, so here's a bit more explanation: &x says "the address of x", but when you have a pointer, you already have an address. A quick example:
int a; // 'a' is an integer variable
int *b = &a; // 'b' is a pointer to the integer variable 'a'
scanf("%d",&a); // This statement reads an integer into 'a'.
// We pass it the address of 'a', which is written &a
scanf("%d",b); // This statement also reads an integer into 'a'.
// We pass it the address of 'a', which is stored
// in the pointer 'b'.
Since we have pointers passed in to the function:
void pntloc (int *x, int *y, int *z){ // Three pointers to ints
we can pass them straight in to scanf(), and don't need to (and shouldn't) use & when we do.
Note that I also removed the return statement:
return *x, *y, *z;
I don't think this return statement is doing what you think it is. Remember that C only allows one return value from a function.
But why does it compile, you ask? Well, here's what's happening - but feel free to ignore this bit if it is confusing: The comma operator evaluates left to right, discarding the left hand result as it goes. So, your return statement is equivalent to:
*x;
*y;
return *z;
The comma operator is useful when the left hand statement has a side effect, and you want to write everything on one line. In my opinion, it makes code much harder to read, but there are one or two situations where it makes things cleaner. For a beginner, I recommend the following rule: Only use commas inside the round brackets of functions.
Since you weren't using the return value from the function when you called it:
pntloc(&x,&y,&z);
I removed the return entirely, and set the return type to void.
*x = &a;
*y = &b;
*z = &c;
Will cause mayhem and death! a b and c are local variables, so you are setting the contents of x y and z to addresses that will be invalid once you return from the function where a b and c are defined.
Perhaps you mean:
*x = a;
*y = b;
*z = c;
in main(),
pntloc(&x, &y, &z);
and
*x = a;
...
printf ("%d", x);
while you pass the *x as a parameter in pntloc(), you can't change *x 's value after calling the function.
and pntloc() don't need to return them, returning 0 or 1 is enough.

Resources