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.
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.
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
im facing an problem in this program, may anyone tell me, what im doing wrong, the program won't display anything after i give it input.
(Code is about sum of digits enter #example 12345 = 15)
#include<stdio.h>
int sum(int num);
int sum(int num){
int total=0;
if(sum==0){
return total;
}
else{
total+=num%10;
num/=10;
return sum(num);
}
}
int main()
{
int num,k;
printf("Enter 5 positive number: ");
scanf("%d",&num);
printf("Sum is: %d",sum(num));
}
Here is a rule of thumb, whenever you have a non-stopping recursion program try to verify your base cases.
Here you are verifying sum the function instead of num the parameter. The C compiler let's you do that because functions in C are pointers, and pointers hold the addresses as numeric value.
You just need to change the condition from sum==0 to num==0. It will now print something. However, the logic of your program is still wrong. You can change your sum function to this.
int sum(int num){
if(num==0) {
return 0;
}
return num % 10 + sum(num/10);
}
And you can try learning more about recursion through stack since recursion is basically just stack.
In your code the total gets initialized to zero every time the function is called. and a variable named sum is not initialized. Just change sum==0 to num==0.I have also given the logic to sum the digits of a number.
I am trying to write a simple program. I am a begineer and i am not getting a value to total. When i am trying to print . I am getting a address as output . Can anyone explain me what is the mistake and correct my program .
#include<stdio.h>
void main()
{
int first,second,total;
printf("enter the value for the first");
scanf("%d",&first);
printf("enter the value for the second");
scanf("%d",&second);
total=power(first,second);
printf("The value for power is %d",power);
}
int power(int doom1,int doom2)
{
int temp=doom1;
int i;
for(i=1;i<=doom2;i++)
{
temp=temp*doom1;
}
return temp;
}
You are printing the wrong variable:
total=power(first,second); //here you are getting return value in variable total
printf("The value for power is %d",power); // power is the function name not variable
Replace this line with:
printf("The value for power is %d",total); // you need to print `total`
Also you have to declare your function prototype before main():
int power(int ,int);
and you should use int main():
int main()
{
// your code
return 0;
}
In addition to passing total to printf instead of power, as you are just starting, make a point to always give your variables an initial value (initialize them). This prevents an attempt to read from uninitialized space which is the bane of new C programmers. (it will save you a lot of headaches). Attempting to read from an uninitialized variable is Undefined Behavior. That can result in anything from slipping by unnoticed, to causing your program to crash. It is to be avoided.
Also, as I explained in the comment, in C, the function main() is type int and it returns a value to its caller (usually the shell, or another program). When using main without arguments, the proper form is:
int main (void)
When accepting arguments, the proper form is:
int main (int argc, char **argv)
In either case, it should return a positive value upon completion. A return 0; at the end is all that is required. exit (0); is another function you can use to return a value. You will also see the form of main with arguments written as:
int main (int argc, char *argv[])
The first and second forms are the practical equivalents of each other, the first recognizing that an array passed to a function in C will decay to a pointer. But for now, just understand that they are equivalent.
You also have an error in your my_power calculation. int temp = doom1; should be int temp = 1; Your calculation was returning a value twice the actual product.
Your style of syntax is up to you, but I would suggest that expanding your syntax a little by using discretionary spaces and lines will make your code much more readable and make finding errors a bit easier. Here is an example regarding all of these points:
#include <stdio.h>
int my_power (int doom1, int doom2);
int main (void)
{
int first = 0; /* Always initialize your variable to prevent */
int second = 0; /* an inadvertant read from an unitialized */
int total = 0; /* value which is Undefined Behavior (bad). */
printf ("\n enter the value for the first : ");
scanf ("%d",&first);
printf (" enter the value for the second: ");
scanf ("%d",&second);
total = my_power (first,second);
printf ("\n The value for my_power is: %d\n\n", total);
return 0;
}
int my_power (int doom1, int doom2)
{
int temp = 1;
int i = 0;
for (i = 1; i <= doom2; i++)
temp = doom1 * temp;
return temp;
}
Output
$ ./bin/simple_function
enter the value for the first : 2
enter the value for the second: 7
The value for my_power is: 128
you are trying to print "power" without parameter
printf("The value for power is %d",power);
you should do
printf("The value for power is %d",total);
or
printf("The value for power is %d",power(first,second));
I'm pretty new to C programming and I had a question as to why a sample code I was given runs the way it does. I'm learning about function prototypes. Can someone give me a run down on the order in which this compiles?
//TwoFunctions - All code split into two user-defined functions
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
//function prototypes
//Calculates and displays the total and avergae of two numbers
void CalcAvg(double tot);
double CalcTotal();
int main()
{
double totl;
totl = CalcTotal();
CalcAvg(totl);
printf("Your total is %.2f\n", totl);
return 0;
}
CalcTotal()
{
double val,
num,
total;
printf("Please enter a number: ");
scanf(" %lf", &num);
printf("Please enter another number: ");
scanf(" %lf", &val);
total = val + num;
return total;
}
void CalcAvg(double tot)
{
double avg;
avg = tot/2;
//printf("Your total is %.2f\n", tot);
printf("The average of the two numbers is %.2f\n", avg);
return;
}
If it makes any sense, for the most part I understand and can write a program like that, however I am a little unclear as to the the steps involved, the calls, and the order in which the compiler compiles the program. Can someone shed a little light on this for? Greatly appreciate it!
Suggested changes:
/*
* Calculates and displays the total and avergae of two numbers
*/
#include <stdio.h>
//function prototypes
double CalcAvg(double tot);
double CalcTotal();
int main (int argc, char *argv[])
{
double tot = CalcTotal();
printf("Your total is %.2f\n", totl);
printf("The average of the two numbers is %.2f\n", CalcAvg(totl));
return 0;
}
double
CalcTotal()
{
double val, num, total;
printf("Please enter a number: ");
scanf(" %lf", &num);
printf("Please enter another number: ");
scanf(" %lf", &val);
total = val + num;
return total;
}
double
CalcAvg(double tot)
{
return tot / 2.0;
}
Function declaration and function prototypes have their differences. A declaration simply means introducing the function (its name) to the compiler before it's usage, similar to a variable; just the function return type is specified. A prototype is where you specify every type the function is associated with i.e. argument type(s) and the return type.
Say you've an add that adds two ints and returns an int. This is a declaration
int add();
while this is a prototype
int add(int, int);
In C89 having a declaration isn't necessary at all. You may just use (call) add(3, 5) and the compiler should infer argument types from the function call and since no return type is known int is assumed. From C99 onwards declaration before usage was made mandatory. Still declaring a prototype isn't necessary. Thus the declaration would be
Note that the argument types isn't part of the declaration. C99 didn't allow the return type to be assumed implicitly as int, it has to be specified in the declaration. Still a function prototype isn't mandatory. Even today C11 doesn't expect a prototype but just a declaration.
Function prototypes were introduced in ANSI C (1989) where a function's declaration can have the argument and return types specified. Though it was never made mandatory for all functions. Only for variadic functions it's mandatory since C89 to declare a function with prototype.
As for your specific program, you declared two functions (one with prototype and one without [see Kerrek SB's comment]) and the used them in main; after main's definition, you've defined the two functions earlier declared.
your questions expects a lot of different topics to be discussed.
1)how compilation takes place? Check This Link For compilation Process
2) how are functions called ? Function Call
read these two links if still you have doubts be more specific on what you want.
Please follow the changes as suggsted by #FoggyDay.
The execution of any program is started from main. so compiler will first find out main and start execution from there.
int main()
{
double totl;
totl = CalcTotal(); /*As a function call to CalcTotal(); function is made here, the
execution is main is suspended and compiler tries to find
CalcTotal()'s definition and runs the whole function and return
value is store in "totl" variable. (Here the return value of
CalcTotal() is double as defined by function's return value.)*/
/*As soon as CalcTotal() function returns, the compiler again comes back to main()
where it suspended the execution and resumes the execution. saves return value of
CalcTotal() in "totl" and jumps to next statement.*/
CalcAvg(totl); /*Again in this statement, a function call to CalcAvg(totl) function
is made here so main()'s execution will be suspended and execution
jumps to CalcAvg(totl) function. The compiler continues to execute
this function until it returns*/
/*When CalcAvg(totl) returns, the execution of main() is again reumed from here*/
printf("Your total is %.2f\n", totl); //This line prints totl
return 0; //main returns and this defines end point of the program.
}
Generally, execution of a program starts from main and goes step by step until a function is called inside main. As soon as any function is called, execution is redirected to that function until that function returns.