I am trying to compute the average after reading in the data from a text file of int type.The program compiles fine. clang -std=gnu11 -Weverything -g3 -pedantic -g3 -O3 -lm average_weight_of_elephant_seals.c -o average_weight_of_elephant_seals
Suppose I want to compute the average weight of 2000 seals,the expected output is 6838.848152 but I get 1710.566467.I have no idea how to make sense of GDB yet.
Could someone please point out where have I have gone wrong?
/* The following program demonstrates the usage of fscan to read in a set of integer data into a file and then computes the sum followed by the average.
* The computation shall be encapsulated in a function and then be called in the main routine
*/
#include <stdio.h>
#define MAXSIZE 5000 /* Macro definition to pre-define the size of the array */
double average_weight(int count, int weights_array[]);
int main(void)
{
int number_of_seals;
int weights_array[MAXSIZE];
printf("Enter the number of seals: \n");
scanf("%i", &number_of_seals);
printf("Their average weight is %lf\n", average_weight(number_of_seals, &weights_array[number_of_seals]));
return 0;
}
double average_weight(int count, int weights_array[])
{
/* Variable declaration and initialization
* Note the use of the FILE data type */
int weight;
int sum = 0;
FILE *elephant_seal_data = fopen("elephant_seal_data.txt", "r");
if (elephant_seal_data == NULL)
{
return -1;
}
/* FEOF function to determine if EOF has been reached or not */
while (!feof(elephant_seal_data))
{
fscanf(elephant_seal_data, "%i", &weight);
weights_array[count++] = weight;
sum += weight;
count++;
}
double average_weight = (double)sum / (double)count;
fclose(elephant_seal_data);
return average_weight;
}
printf("Their average weight is %lf\n", average_weight(number_of_seals, &weights_array[number_of_seals]));
The code passes a pointer to a position into the array for no apparent reason, and does not check if number_of_seals * 2 is less than MAXSIZE so may overflow the array. But the array isn't needed for this calculation anyway.
weights_array[count++] = weight;
sum += weight;
count++;
The code is writing to the array not reading it. The array is not needed for this calculation.
The code increments count twice, so the average will be out by a factor of two, and alternate locations in the array will have undefined values in them.
There are 2 stupid mistakes in your code, a nastier one, and a risk.
First the stupid ones:
You pass count to the function and increment that value twice per each value in the file. If the initialy given value was correct, you end with a count 3 times too big. You should not pass count to the function but compute it there.
You use a wrong syntax to pass an array: you are expected to pass a pointer to its first element.
Now the nasty one: while Why is “while ( !feof (file) )” always wrong? is indeed a FAQ, is is still a common thing in beginners code...
feof only returns true after a read operation returned an error. Let us examine what happens for the last value. It is read and correctly processed once. feof still returns false (no error so far) so your code re-enters the loop. scanf reaches the end of file and returns 0 (what your code ignores) but does not change the values => the last value will be processed twice. Never ever use while (!feof(...
And finally the risk.
You are summing value into an integer. Even if the average will easily fit there, if you had larger value and a very high number of them, you could get an integer overflow. The recommended way it to sum into a larger type (double?) and if possible use a guess to limit the cumulative error: average(qty-guess) + guess is indeed average(quantity), but the computed sum can be much lower, limiting the cumulative error when using floating point values or preventing overflow when using integer ones. From the number of seals and the expected average there should be no problem here so a guess is useless, but remember that for a different use case...
Last but not least, main is expected to be declared as int main() if you do not care for additional parameters but never int main(void)
Code could become:
/* The following program demonstrates the usage of fscan to read in a set of integer data into a file and then computes the sum followed by the average.
* The computation shall be encapsulated in a function and then be called in the main routine
*/
#include <stdio.h>
#define MAXSIZE 5000 /* Macro definition to pre-define the size of the array */
double average_weight(int* count, int weights_array[]);
int main()
{
int number_of_seals;
int weights_array[MAXSIZE];
double weight = average_weight(&number_of_seals, weights_array);
printf("Their number is %d and their average weight is %lf\n", number_of_seals, weight);
return 0;
}
double average_weight(int* count, int weights_array[])
{
/* Variable declaration and initialization
* Note the use of the FILE data type */
int weight;
int sum = 0;
FILE* elephant_seal_data = fopen("elephant_seal_data.txt", "r");
if (elephant_seal_data == NULL)
{
return -1;
}
*count = 0;
/* FEOF function to determine if EOF has been reached or not */
for(int i=0; i<MAXSIZE; i++) // never process more than the array size
{
if (1 != fscanf(elephant_seal_data, "%i", &weight)) {
break; // immediately stop at end of file
}
weights_array[(* count)++] = weight;
sum += weight;
}
double average_weight = (double)sum / (double)*count;
fclose(elephant_seal_data);
return average_weight;
}
I have kept your general program structure unchanged, but IMHO, you are expected to first read the data into an array, and then pass that populated array along with its count to an average function. Just split your current function into 2 steps.
You have sent the number of counts to use in the array which is great, since the function does not know the length of the weights_array. But you are not using it properly.
I'd suggest you to:
Use count to limit the number of loops based on how many data you want.
Do not change/reassign the value of count. Since this number is crucial to calculate the average. Create some other variable to do the task.
So here is how I slightly modified your code to bring those changes. I assumed the format of elephant_seal_data.txt as space separated integer values.
#include <stdio.h>
#define MAXSIZE 5000 /* Macro definition to pre-define the size of the array */
double average_weight(int count, int weights_array[]);
int main(void)
{
int number_of_seals;
int weights_array[MAXSIZE];
printf("Enter the number of seals: \n");
scanf("%i", &number_of_seals);
printf("Their average weight is %lf\n", average_weight(number_of_seals, &weights_array[number_of_seals]));
return 0;
}
double average_weight(int count, int weights_array[])
{
/* Variable declaration and initialization
* Note the use of the FILE data type */
int weight;
int sum = 0;
int i = 0;
FILE *elephant_seal_data = fopen("elephant_seal_data.txt", "r");
if (elephant_seal_data == NULL)
{
return -1;
}
/* FEOF function to determine if EOF has been reached or not */
while (i<count)
{
fscanf(elephant_seal_data, "%d", &weight);
weights_array[i++] = weight;
if (feof(elephant_seal_data)) break;
sum += weight;
}
double average_weight = (double)sum / (double)count;
fclose(elephant_seal_data);
return average_weight;
}
Edit:
I have used the elephant_seals_data.txt to simulate these in Google Colab for you. Try running the first cell there.
Google Colab Link
Related
I am writing a code to find the factor of the user given number. And then I want to store all the factors in an array. I created two functions, factors and insert_element. factors will find the factor and insert_element will store the factor in array as loop continues. When i call insert_element function form factors it shows me an error like warning: passing argument 1 of ‘insert_element’ from incompatible pointer type [-Wincompatible-pointer-types]. I have no idea what this means and how it occurred as I am new at C language. I would like to know how a bit about how compiler works with array along with how this error occurred
I am extremely SORRY if the question title and the question body seems to be misleading..
Here's my code below:
// PROGRAME TO FIND FACTORS OF GIVEN NUMBER"
#include <stdio.h>
void insert_element(int *factor_array[], int *base_divisor, int *index_of_array_elements)
//I heve used * because i want to ruturn more then one thing
{
*factor_array[*index_of_array_elements] = *base_divisor;
*index_of_array_elements++;
}
void factors(int number)
// I dont know if I want to return something or not so i kept it of type void
{
int base_divisor = 2, factor_array[50], index_of_array_elements = 0;
// base_divisor starts dividing given number from 2
while (number != 1)
{
if (number % base_divisor==0) //If remainder is zero then only devide number by base_divisor
{
number = number / base_divisor;
}
else //If remainder is not zero then base_divisor will be increase by 1.
{
base_divisor++;
}
// calling the function to insert element in array
insert_element(&factor_array[50], &base_divisor, &index_of_array_elements);
}
//i dont know why i did this but error is not caused by this.
printf("%ls", factor_array);
}
int main()
{
int number;
printf("\nPROGRAME TO FIND FACTORS OF GIVEN NUMBER\n\n");
printf("Enter the number to find factor: ");
scanf("%d", &number);
factors(number);
}
As written, the code in your post is outputting values that are not always factors. Only during the final iteration of the loop is the value for factor_array (if stored correctly) a quotient and a factor, which of course should also mean it is prime.
The following example, for simplification removes one function, and modifies the prototype of the remaining function to take a struct array argument. The struct itself contains values for quotient, factor, base. The code is also commented to explain some of the modification. In particular I hope this will help you to understand how to pass an array as a function argument, and how to use a loop to output the values in an array.
typedef struct {
long long factor;
long long quotient;
long long base;
}elements_s;
elements_s factor_array[50] = {{0}};
//REMOVED as all the work done here is moved to it's calling function
// void insert_element(size_t arr_size int *factor_array[], int *base_divisor, int *index_of_array_elements)
////I heve used * because i want to ruturn more then one thing
//{
//
// *factor_array[*index_of_array_elements] = *base_divisor;
// *index_of_array_elements++;
//
//
//}
void factors(long long number, size_t size, elements_s arr[size])//changed to pass container for results.
// I dont know if I want to return something or not so i kept it of type void
{
long long base_divisor = 2, /**factor_array[50],*/ index_of_array_elements = 0;//factor_array replaced by struct array
arr[index_of_array_elements].factor = 1;//fill array here, no need to send via function
arr[index_of_array_elements].quotient = number;
arr[index_of_array_elements].base = base_divisor;
int i=0;
// base_divisor starts dividing given number from 2
while (number != 1 && base_divisor < LLONG_MAX )
{
if (number % base_divisor==0) //If remainder is zero then only devide number by base_divisor
{
index_of_array_elements++;//index array index
number = number / base_divisor;
arr[index_of_array_elements].factor = base_divisor;//fill array here, no need to send via function
arr[index_of_array_elements].quotient = number;//fill array here, no need to send via function
arr[index_of_array_elements].base = base_divisor;//fill array here, no need to send via function
}
else //If remainder is not zero then base_divisor will be increase by 1.
{
base_divisor++;
}
//REMOVED for simplification of example (Not needed)
// calling the function to insert element in array
//insert_element(&factor_array[50], &base_divisor, &index_of_array_elements);
//insert_element(&factor_array, &base_divisor, &index_of_array_elements);
}
//i dont know why i did this but error is not caused by this.
for(i = 0;i < index_of_array_elements-1; i++)//putting into loop so all populated element of array are output
{
printf("quotient:%lld\nfactor:%lld\n", factor_array[i].quotient,factor_array[i].factor);//using %d for int
}
printf("base divisor:%lld\nfactor and quotient:%lld\nfactor:%lld\n", factor_array[i].base, factor_array[i].quotient,factor_array[i].factor);//using %d for int
}
int main(void)//this is a minumum signature for main. Anything less is not portable.
{
long long number = 0; //allows larger values up to 9223372036854775807 (LLONG_MAX)
//int factor_array[50] = {0};
size_t size = sizeof factor_array/sizeof *factor_array;
printf("\nPROGRAME TO FIND [prime] FACTORS OF GIVEN NUMBER\n\n");
printf("Enter the number to find factor...\n");
scanf("%lld", &number);//format specifier changed to accomodate larger type
factors(number, size, factor_array);//factor_array contains all the results here,
// so prinf could be used here if index were
// also passed as argument
return 0;//int main(void) requires this statement
}
Example run for value: 1234567890: (multiply all factors to test for input)
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) {
I need to learn how to use the function for the calculation and then a simple call in main. When I tried it didn't work. I have no idea what to do. It works but when I take out the code from main it gets funky.
this is simple simple scenario and code for that.
Write a function that takes an array of ints, and the size of the array - another int.
It also returns a double. Call this one 'average.' Return a double that is the average
of the values in the array. Demonstrate that it works by finding the average of an array
with these values {78, 90, 56, 99, 88, 68, 92}
#include <stdio.h>
#include <stdlib.h>
// Outside of main, a function will be declared that takes an array of ints.
double Function(int Array[7])
{
// int Array[7] = {78, 90, 56, 99, 88, 68, 92};
int sum = 0;
int i;
double average;
// This for loop allows us to use all 7 elements in the array.
for(i=0; i<7; i++)
{
// This takes all the array's elements and sums them up.
sum += Array[i];
}
// This prints the sum
printf("Sum = %d\n", sum);
// The double average is found by taking the sum found and dividing it by 7.
average = sum/7;
// This prints the average in a double.
printf("The resulting average is %lf \n", average);
return average;
} // Ends Function
// There will also be the size of the array(which is another int)
// The function will return a double called average. It is the average of the values in the array.
int main()
{
//int i; // Allows us to use the for loop and print each element in the corresponding array.
// int array numbers are declared and initialized.
int Array[7] = {78, 90, 56, 99, 88, 68, 92};
int sum = 0;
int i;
double average;
// This for loop allows us to use all 7 elements in the array.
for(i=0; i<7; i++)
{
// This takes all the array's elements and sums them up.
sum += Array[i];
}
// This prints the sum
printf("Sum = %d\n", sum);
// The double average is found by taking the sum found and dividing it by 7.
average = sum/7;
// This prints the average in a double.
printf("The resulting average is %lf \n", average);
Function(Array);
system("pause");
return 0;
}
Can any one give me a tips!
If you want to follow the instruction you were given, your function declaration should be
double average(int *array, int array_size)
Also, your solution should be general, not only for array with length of 7.
In general in C language - when you want to pass an array which its length is unknown, you pass the address of the array (here *array) and its size (here array_size). Then your function will iterate over the array from the given address, with jumps of the type (here jumps of sizeof(int) because it's an array of ints).
In C Program execution always starts from main.
So the stack will be like
main()-->Function()
You are almost right just you called the function which returns the average so to keep that average or to accept that average in main you need variable so just remove all the code shown below
for(i=0; i<7; i++)
{
// This takes all the array's elements and sums them up.
sum += Array[i];
}
// This prints the sum
printf("Sum = %d\n", sum);
// The double average is found by taking the sum found and dividing it by 7.
average = sum/7;
// This prints the average in a double.
printf("The resulting average is %lf \n", average);
Now take the results returned by the Function() in average variable shown below.
average=Function(Array);
Now print that value if you want to print or use in main if you need.
the posted code contains several misconceptions
no need to '#include' header files those contents are not needed.
only write code that is part of the solving of the problem. Other code that is added for 'debug' purposes should be eliminated from the final executable. Usually be surrounding the debug code with: #ifndef NDEBUG .... #endif Suggest learning how to work with NDEBUG
The problem only needs to solved once, not both in 'main()' and in 'Function()' BTW: function is a terrible function name suggest: calculateAverage(). Function names should indicate what they will perform, usually by starting the function with some active verb, like calculate
for ease of readability and understanding, consistently indent the code. Indent after every opening brace '{'. unindent before every closing brace '}'. Suggest each indent level be 4 spaces as that is wide enough to be visible even with variable width fonts. Remember, the compiler (in general) doesn't care about the 'style' of the code formatting. However, any human cares a lot, because the human wants to be able to read the code.
it is (almost always) a bad idea to hard code any values other than 0 and 1. Instead give them meaningful names via a enum statement or #define statements, then use those meaningful names throughout the code.
Please pay attention to these 3 details in the code:
how the size of the array is calculated
how the parameters are passed to the 'Function()'
how the average is calculated.
Note: when all the variables in a divide operation are integers, then a integer divide is performed. This can produce some surprising results.
For instance, 5/3 results in 1, not 1.66.
by wanting to keep the fraction, cast one of the elements (not the whole expression) to double or float
and now the code
#include <stdio.h> // printf()
//#include <stdlib.h>
double Function(int *pArray, int numElements );
int main( void )
{
// int array numbers are declared and initialized.
// note: usually best to let the compiler calculate array size
// rather than hardcoding the size
int Array[] = {78, 90, 56, 99, 88, 68, 92};
// number of elements in array
int sizeofArray = sizeof(Array)/sizeof(int);
// call Function to calculate and return as double,
// the average of the array elements
double average = Function( Array, sizeofArray );
// This prints the average as a 'double'.
printf("The resulting average is %lf \n", average);
//system("pause"); // not portable, suggest:
int ch;
while( (ch = getchar()) != EOF && '\n' != ch );
getchar();
//return 0; // <-- in modern C, if main to return 0 then this line not needed
} // end function: main
double Function(int *pArray, int numInts )
{
int sum = 0;
double average;
for(int i=0; i<numInts; i++)
{
sum += pArray[i];
}
// cast one of the values as a double so an integer divide is NOT performed
average = (double)sum / numInts;
return average;
} // end function: Function
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 am trying to sum an array of numbers. The array has a length determined by an input and then the user gives the array. There were no compilation errors and I am able to run other programs. On the immediate start of running the program I am given a message that program has stopped working and that windows is searching for solution.
#include <stdio.h>
int main()
{
int sum, length, count;
int array[length];
sum=0;
scanf("%d",&length);
scanf("%d",&sum);
for(count=0; count<length-1; count++)
{
sum = sum + array[count];
}
printf("%d", sum);
return 0;
}
When you declare your array it depends on length but you ask the user for length after.
A solution could be to ask the user for length (scanf("%d",&length);) before declaring your actual array (int array[length];).
you should move int array[length] to after scanf("%d", &length). But it is not allowed in C to declare variables after the first non-declaration (it is however possible if you compile this program as C++).
In fact, in standard C you can't have a non-const length definition for an array variable. gcc on the other hand for example allows this nevertheless.
In your case, the problem is that length has an undefined value at the declaration of int array[length];. If you are lucky, your data segment has been initialized to zero (there is no guarantee for that) but otherwise, it may be any value, including a value which leads the program to exceed your physical memory.
A more standard way of doing this is:
int *array = NULL;
scanf("%d",&length);
...
array = (int*) malloc(sizeof(int) * length);
...
free(array);
By the way, even after fixing that, you will most likely get random numbers because you never actually assign the contents of the elements of array.
Local variable are initialized to 0. Hence value of length is 0. So you array is of length. You are then reading length, say 10, from stdin and expect the array to be of length 10. This can't be. Since this is a stack variable, the size is determined in time of pre-processing and not in run time. If you want to define the array length in run time then use malloc.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int sum, length, count;
int *array;
sum=0;
scanf("%d", &length);
scanf("%d",&sum);
array = (int *)malloc(sizeof(int) * length);
if (array == NULL) return 0;
memset(array, length, 0);
for(count=0; count<length-1; count++)
{
sum = sum + array[count];
}
printf("%d", sum);
return 0;
}
Thanks.
first problem:
the length variable is being used to set the number of entries in the array[], before the variable length is set. Therefore, length will contain what ever trash happens to be on the stack when the program starts so the number of entries defined in array[] is an unknown.
This results in undefined behaviour and could lead to a seg fault event, depending on what was on the stack and what the user entered for length.
second problem:
The array array[] is never initialized so will contain what ever trash is on the stack at program startup. This means the value being printed could be anything. And the 'sum' could overflow, depending on the trash values in array[]
OP program lacks the part of data input, it's asking for sum instead of the values to sum, which is weird. The only inputs requested are also never checked (the return value of scanf must always be checked).
In C (at least C99 and optionally C11) Variable Length Arrays, like the one defined by int array[length], can be used, but the variable length here is used uninitialized and before it is even asked to the user.
Moreover, the loop where the sum is calculated stops before the last element of the array (not really a big deal in this case, considering that all those variables are uninitialized...).
A better way to perform this task could be this:
#include <stdio.h>
// helper function to read an integer from stdin
int read_int( int *value ) {
int ret = 0;
while ( (ret = scanf("%d", value)) != 1 ) {
if ( ret == EOF ) {
printf("Error: Unexpected end of input.\n");
break;
}
scanf("%*[^\n]"); // ignore the rest of the line
printf("Please, enter a number!\n");
}
return ret;
}
int main(void) {
int sum = 0,
length = 0,
count,
i;
printf("Please, enter the number of values you want to add: ");
if ( read_int(&length) == EOF )
return -1;
// Use a VLA to store the numbers
int array[length];
// input the values
for ( count = 0; count < length; ++count ) {
// please, note ^^^^^^^^ the range check
printf("Value n° %2d: ", count + 1);
if ( read_int(&array[count]) == EOF ) {
printf("Warning: You entered only %d values out of %d.\n",
count, length);
break;
}
// you can sum the values right here, without using an array...
}
// sum the values in the array
for ( i = 0; i < count; ++i ) {
// ^^^^^^^^^ sum only the inputted values
sum += array[i];
}
printf("The sum of the values is:\n%d\n", sum);
return 0;
}
I am writing a program that calculates the square of two values (I must use a function.) I am sure that there are many mistakes but, I just can't seem to pick them out:
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
int integer1, integer2, total = 0;
int squared(int integer1, int integer2);
int main(void)
{
printf("Enter two numbers to be Squared\n");
scanf("%d%d",&integer1,&integer2);
printf("Square of entered numbers = %d\n", squared(integer1,integer2));
return 0;
}
int squared(int integer1, int integer2)
{
int total;
total = integer1 + integer2;
return total *= total;
}
Header file:
#ifndef HEADER_H
#define HEADER_H
#define squared
int squared(int integer1, int integer2);
#endif
While you don't really need to specify the type int for the arguments that the function squared takes, because int is assumed whenever type is not specified, it is never bad to just put them down, as in:
int squared(int integer1, int integer2, int total);
// instead of
// int squared(integer1, integer2, total);
// both at the prototype and the definition of the function
Then again, you may just leave that out.
There are real problems in your function squared's definition. You aren't using semicolons ;, and you have written a return for the first statement, where I think you don't really want to return anything yet. You probably just wanted:
int squared(int integer1, int integer2, int total)
{
total = integer1 + integer2;
return total *= total;
}
One another important thing is, you are giving 2 less arguments to the squared function call from your main function. squared awaits for 3, you give it just 1. You probably wanted to call it as following:
...
printf("Square of entered numbers = %d\n", squared(integer1, integer2, total));
...
Lastly, you shouldn't be using variables that you haven't given a value to. integer1 hopefully will have a value assigned, integer2 also, hopefully. But total won't be assigned a value by the time you call the squared from main. You can just initialize it with a 0 or something, like this:
...
int integer1, integer2, total = 0;
...
Actually, you don't even need to have a total inside main, your squared function doesn't need a 3rd argument that holds total, as soon as you just declare an int total inside squared. But I won't get to that...
The main issue throughout is that you don't specify the type of each function parameter. You need to tell the compiler that integer1 is an int, for example. Also, see haccks' answer.
Two return statements one after the other are useless. The second return statement is unreachable. And you missed semicolons at the end of both the lines. May be this is the function you wanted:
int squared(int integer1,int integer2,int total)
{
total = integer2+integer2;
return total*total;
}
This calculates the sum of the two values and returns the square of the sum.
in addition to the function definition you need to change even the function call,
printf("Square of entered numbers = %d\n",squared(total));
to
printf("Square of entered numbers = %d\n",squared(integer1,integer2,total));
so that function call gets the value to add. read some basic c programs to know the format and syntax.
With all above answers, you seem to have missed ; in the return statement of your function.