Variable Buffer? - c

I have this code which calculates the exponential power of a value, both of which is entered by the user, example, user enters 2^3 = 8, its suppose to work like this but somethings wrong, the end result is 608, when I debug in the pwra function in the counter, even before the counter initiates the result value is set, from where I dont know because I did not set it so the end result is 608. I feel like its a buffer issue but I have tried fflush both in and out, it doesnt work. So when I copy this code to a new window, it works for sometime, then same again, earlier it was showing 624 as the end result.
#include <stdio.h>
int pwra (int, int);
int main()
{
int number, power, xx;
printf("Enter Number: ");
scanf("%i", &number);
printf("Enter Number: ");
scanf("%i", &power);
xx=pwra (number,power);
printf("Result: %i", xx);
return 0;
}
int pwra (int num, int pwr)
{
int count, result;
for(count=1;count<=pwr;count++)
{
result = result*num;
}
return result;
}
Another thing, how can I calculate the exponential value from a float, because when I change all the int to float the end result is always 0.00000 even with %lf.

You're hitting undefined behavior for the below line
result = result*num;
as you've not initialized result. The initial value for an uninitialized automatic local variable is indeterminate. Using that invokes UB.
Always initialize your local variables, like
int count = 0 , result = 0 ; //0 is for illustration, use any value, but do use
Then coming to the case, where you want to change all ints to float, only changing the data type of the variable is not sufficient. You need to change the corresponding format specifiers, too.

Related

Basic question about how this C code is working

#include <stdio.h>
#include <cs50.h>
int get_pos_int(void);
int main(void) {
int i = get_pos_int();
printf("You entered the positive Integer of %i\n", i);
}
int get_pos_int(void) {
int n;
do {
n = get_int("Insert a positive Integer: ");
}
while(n < 1);
return n;
}
So of course this is just a simple program to test for if a number entered is a number above 0. Out of interest I decided to make this small change to see if it was semantically still correct.
int main(void) {
get_pos_int();
printf("You entered the positive Integer of %i\n", get_pos_int());
}
When running the program with this change, if I input the number '1' it returns me back to the prompt to type an integer, then if I type 1 again it returns 'You entered the positive Integer of 1'
I was just wondering if you could explain what the behaviour is causing this, I like to know why things are working the way they are and it interested me how removing the function being stored in a variable made it behave this way.
Based on your description of what happens, I'm assuming you meant get_pos_int() in your printf.
int i = get_pos_int() stores the return value of the function, not the function itself. So when you made your change, you call the function but discard the value it returns. The function then gets called again in your printf statement. The function being called twice is why you have to enter 1 twice.

calculating x to power y using for loop

I've tried to use the for loop for calculating x to power y. The program is running but giving errors.
To my knowledge, the error must be in "z" statements but I cannot figure it out.
Help me if you encounter my mistakes.
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,i;
long int z=x;
printf("Enter the values of x and y: ");
scanf("%d %d",&x,&y);
for(i=2;i<=y;i++)
z*=x; ```
/*e.g- Let x=2, y=3, then as per intialization z=x=2
since,from the for condition, (i=2)<=3, which is true
z= z*x =>2*2 => 4 now z=4
now i++ => i=3
(i=3)<=3,which is true
z= z*x =>4*2 => 8
therefore, 2 to power 3 is 8 */
printf("%d to power %d is %ld",x,y,z);
getch();
}
You are assigning z to x before x is assigned a value. z then has an indeterminate value, which messes up calculation of the power.
You have to wait until x is assigned from user input before using its value to initialize z.
Also, when reading input from scanf, it's a best practice to check its return value to ensure that all intended values were read successfully:
if(scanf("%d %d", &x, &y) != 2)
{
// x and y were not properly read - handle error
}
z = x;
EDIT: #chux - Reinstate Monica pointed out in the comments that if y == 0 the code still has a problem. Anything to the power of zero (except zero itself, since xy is not continuous at the origin) is 1. You have to handle that special case as well.
You are initializing your z variable (to be equal to x) before you have assigned a value to x! To fix this, move the declaration/initialization of z to after your scanf call:
//..
int x,y,i;
// long int z=x; // Means nothing: as "x" is here undefined, so "z" will also be!
printf("Enter the values of x and y: ");
scanf("%d %d",&x,&y);
long int z = x; // Here, we have (probably) a value for "x" so we can copy it to "z"
//..
EDIT: Maybe I'm drifting a bit 'off-topic' here, but you may have a background in programming languages that use reference variables (C++ or C#)? In such languages, what you are trying to do may work! For example, in C++, you could have int& z = x; (where you have your current declaration), and that could work in some circumstances (although, in your code, it actually won't, as pointed out in the comments). However, in "plain old C," code is executed where you put it, and there's no such thing as a "reference variable."
First you might want to initialize those variables
long int x = 0, y = 0;
long int z = 0;
Here you should check if scanf was successful
printf("Enter the values of x and y: ");
scanf("%ld %ld",&x,&y);
About scanf return value. From cppreference
Return value 1-3) Number of receiving arguments successfully assigned
(which may be zero in case a matching failure occurred before the
first receiving argument was assigned), or EOF if input failure occurs
before the first receiving argument was assigned. 4-6) Same as (1-3),
except that EOF is also returned if there is a runtime constraint
violation.
Now the problem is you're assigning z the value of x before either is initialized properly. So that is an undefined behavior.
This is what you want
long int x = 0, y = 0;
long int z = 0;
printf("Enter the values of x and y: ");
scanf("%ld %ld",&x,&y);
z = x;
Also you can define a new int variable inside the loop. I personally find this method better.
for(int i = 2; i <= y; i++)
z *= x;
For the print statement, you might want to use %ld format for long int
printf("%ld to power %ld is %ld",x,y,z);

There is an C function with pointers and a char return, what only returns the char value and 0 to the pointers

The objective here is to print the student's average grade as a letter (A for Aprooved, R for Reprooved, or F for Miss, or Falta, in Portuguese), with the average grade value itself, and the student's total presence in classes, using pointers to avg and misses. But after compilation, only the char return value is printed, with 0 on the others.
I tried to print the stored values in the pointers *avg and *presence, but the program takes the student grade values and present values before crashing.
#include <stdio.h>
char situation(float n1,float n2,float n3,int misses, int classes, float
*avg, float *presence);
int main()
{
float *avg, *presence, vet[3];
int f, a, x;
printf("Write the value of your notes \n");
for(x=0;x<=2;x++)
{
printf("Note %d:",x+1);
scanf("%f",&vet[x]);
}
printf("Misses: ");
scanf("%d",&f);
printf("Given: ");
scanf("%d",&a);
char outcome=situation(vet[0], vet[1], vet[2], f, a, &avg, &presence);
printf("With an average of %f and presence of %f percent, your situation is %c",avg,presence,outcome);
return 0;
}
char situation(float n1,float n2,float n3,int misses, int classes, float
*avg, float *presence)
{
char result;
*presence=((classes-misses)/classes)*100;
*avg=(n1+n2+n3)/3;
if(*presence>=0 && *presence<75)
{
result='F';
}
if(*presence>=75 && *presence <=100)
{
if(*avg>=0 && *avg<6);
{
result='R';
}
if(*avg>=6 && *avg<=10)
{
result='A';
}
if(*avg<0 || *avg>10)
{
result='x';
}
}
if(*presence<0 || *presence>100)
{
result='x';
}
return result;
}
I expected the student's total presence and the average grade as a value and letter (A, R, or F), printed on the terminal to the user, but it only returned the char result value.
Your code has one main problem:
float *avg,*presence,
When you a calling
char outcome=situation(vet[0],vet[1],vet[2],f,a,&avg,&presence);
You are passing the address to the pointer you just declared. By changing the value in the function outcome, you are changing the address that avg and presence are pointing to, not the value of the variable.
Try changing to
float avg,presence
This way, when you change the value (using the * operator) you will change the actual variable value.
You may find this that presence still be showing as 0 on the printf. This is because how C works with types in arithmetics operations. Your division has only ints on it, so the result will be a int. Given the result will always be >= 1, the result will be rounded to the int value, which is 0.
To fix that just put a float value in the division and the result will be a float.
Something like:
*presence=((classes-misses)/(classes*1.0))*100;
avg is a float pointer, you are sending it by pointer (&avg) so your function needs to be (int n1,....,float **avg,...)
Try to send avg without the &.
Give him a value before (it is better)
The compiler warning pointed you directly to the problem. You should examine the warning and come to understand what it means and why it was issued.
Your error is here:
float *avg,*presence
These should be declared as float, not float *.

How to assign value to a variable only if value meets a condition?

I am a first year college student working on a project for my beginner programming class. I am trying to ask the user for a value, which represents the starting amount, which must be greater than or equal to zero. As I am debugging my program, I noticed that when I input a negative value, the program asks me to re-enter a value that is greater than or equal to zero (like it should), however the initial negative value gets assigned to the variable to do the computations, resulting in an incorrect output. I was wondering if anyone had any ideas as to how I could assign the positive value to the variable.
I have a function that asks the user to input a value, stores this value in a variable, and then returns the variable to the main function. In my main function, I have a variable set equal to the function call. After this initialization, I have tried using while loops and if statements to check whether or not the value is less than zero, and if it is, tell the user that the input should be greater than or equal to zero, and call the function again.
int main(){
int initialSize = getInitialSize();
if (initialSize < 0) {
printf("Initial size must be greater than or equal to 0");
getInitialSize();
}
}
int getInitialSize() {
int startingAmount;
printf("Enter initial size: ");
scanf("%d", &startingAmount);
return startingAmount;
}
I have also tried putting the if statement within the function getInitialSize itself, but that also was not a solution.
I recommend also adding a test to be sure that the user actually entered a valid number at all, because if they entered garbage, then the startingAmount variable won't have a reasonable value at all.
int getInitialSize() {
int startingAmount;
do
{
printf("Enter initial size: ");
} while (scanf("%d", &startingAmount) < 1 || startingAmount < 0);
return startingAmount;
}
Now it loops asking the user for input either if they didn't type a valid number or the number they entered is not to your satisfaction.
So, on first inspection, you have initialized the variable initialSize, but when you want to recompute it, you are missing an assignment. Since you want to repeat the query for the value until it is non-negative, you should use a loop.
int initialSize = getInitialSize();
while (initialSize < 0) {
printf("Initial size must be greater than or equal to 0");
initialSize = getInitialSize();
}
#include <stdio.h>
int getInitialSize();
int main(){
int initialSize = getInitialSize();
if (initialSize < 0) {
printf("Iinitial size must be greater than or equal to 0");
getInitialSize();
}
return 0;
}
int getInitialSize() {
int startingAmount;
printf("Enter initial size: ");
do{
scanf("%d", &startingAmount);
}while(startingAmount<0);
return startingAmount;
}
Here use loop like that. Ofc with this you don't need to check it in main.

An Address is Printed Instead of the Expected Value

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

Resources