calculating x to power y using for loop - c

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

Related

Why different values inside called function and inside calling function?

The values which are output from inside the called function and from inside the calling function are not identical.
Why are values of y and value of m not the same?
screenshot of code and output, showing "Value of m 6" and "value of y 13"
#include<stdio.h>
int pass(a);
int main()
{
int x,y;
printf("Hello world\n");
printf("Enter the x ");
scanf("%d",&x);
y = pass(x);
printf("value of y %d",y);
return 9;
}
pass(m)
{
m = m + 5;
printf("Value of m %d\n",m);
// return 5;
}
Output:
Hello World
Enter the x 1
Value of m 6
value of y 13
Strictly, this should not even attempted to be explained, because of undefined behaviour, compare Reaching end of function without return statement
but ...
Assuming that my guess on the pattern of returned values (a constant plus the number of digits in "input + 5") is correct:
By chance, the default assumptions of the compiler when seeing the incomplete prototype int pass(a); (should be int pass(int a);), allow it to associate the later provided implementation of pass(m) (should be int pass(int m);, or more consistently int pass(int a)).
So when you call y = pass(x);, y gets the value returned by that implementation.
The implementation then lacks a clean return statement (it has one, but inactive by being a comment).
So at the end of executing that function, the most recently determined result is returned, another default of compilers which you should better not rely on for clarity and readability of code.
The most recent result is the return value of the call to printf().
That return value is the number of successfully printed characters.
You might want to read up on printf() and its return value in its specification, and about the concept of return values, prototypes and data types of parameters and return values in general.
For the output you show in your picture of text,
Value of m 6\n (thanks for making me type that...) that is, let me count
^ ^ ^ ^
1 5 10 13,
13, including the newline at the end of the output from inside the function.
Obviously, this is completely unrelated to the value of the local variable m, which is seen in the picture of text.
For more details on how to achieve what you might try to do see the comment David C. Rankin.

Variable Buffer?

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.

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.

Structure with formulas

My problem is that the correct value that is suppose to be stored in the data[i].Px isn't stored and the same with the data[i].Py.
My formula in the do-while is faulty or must be.
The formula should calculate the 'position' of a projectile.
Vx and Vy is the initial velocities/values and Px and Py is the positions (in the x and y directions)
typedef struct
{
float t, Vx, Vy, Px, Py;
}datapoint;
steps = 100
data[0].Vx = (20*(cos(30))); //in my program 30 is in radians
data[0].Vy = (20*(sin(30));
data[0].Px = 0;
data[0].Py = 0;
do
{
i=1;
printf("Time: %.2f\t",i*q5);
//X
data[i].Vx = data[i-1].Vx;
data[i].Px = ((data[i-1].Px) + ((data[i].Vx) * i));
printf("X = %.2f\t",data[i].Px);
//Y
data[i].Vy= data[i-1].Vy - (9.81)*i;
data[i].Py= data[i-1].Py + (data[i].Vy * i);
printf("Y = %.2f\t", data[i].Py);
printf("\n");
i++;
}while(**(data[i].Py >0)** && (i<=steps));
In the while condition of the do while loop, do you want to have
while((data[i].Py > 0) && (i <= steps));
Oh just saw a flaw. Why are you initializing i=1 inside the loop! Its value will never go beyond 2.
(I just skimmed through your question, so if this doesn't work I will check it thoroughly).
Judging from the notation used (since the declaration is not shown), data is an array of datapoint. Then data->Px is equivalent to data[0].Px.
You don't show how data[0] is initialized.
i never gets beyond 2. Unless steps is 2, the loop won't terminate because of the i <= steps condition. Since the value in data[0].Py (aka data->Py) is not modified in the loop, you have an infinite loop unless data[0].Py is negative or zero on entry to the loop.
You should look askance at a do { ... } while (...); loop. They aren't automatically wrong; but they are used far less often than while or for loops.
Generally, you will get better answers on StackOverflow if you produce a minimal compilable and runnable program (or a minimal non-compilable program that illustrates the syntax error if you are having problems making the program compilable). And 'minimal' means that nothing can be removed without altering the behaviour.

Is my looping solution cheat for this puzzle?

This programming problem is #85 from a page of Microsoft interview questions. The complete problem description and my solution are posted below, but I wanted to ask my question first.
The rules say that you can loop for a fixed number of times. That is, if 'x' is a variable, you can loop over a block of code based on the value of 'x' at the time that you enter the loop. If 'x' changes during the loop, that won't change how many times you loop. Also, that is the only way to loop. You can't, for instance, loop until some condition is met.
In my solution to the problem, I have a loop which will be set to execute zero or more times. The problem is, in reality, it only ever executes 0 times or 1 time because the only statement in my loop is a return statement. So if we enter the loop, it only has a chance to run once. I am using this tactic instead of using an if-else block, because logical comparisons and if statements are not allowed. The rules don't explicitly say that you can't do this, but I am wondering if you would consider my solution invalid. I couldn't really figure out another way to do it.
So here are my questions:
Do you think my solution is invalid?
If so, did you think of another way to solve the problem?
Problem description:
85) You have an abstract computer, so just forget everything you know
about computers, this one only does what I'm about to tell you it
does. You can use as many variables as you need, there are no negative
numbers, all numbers are integers. You do not know the size of the
integers, they could be infinitely large, so you can't count on
truncating at any point. There are NO comparisons allowed, no if
statements or anything like that. There are only four operations you
can do on a variable.
You can set a variable to 0.
You can set a variable = another variable.
You can increment a variable (only by 1), and it's a post increment.
You can loop. So, if you were to say loop(v1) and v1 = 10, your loop would execute 10 times, but the value in v1 wouldn't change so
the first line in the loop can change value of v1 without changing the
number of times you loop.
You need to do 3 things.
Write a function that decrements by 1.
Write a function that subtracts one variable from another.
Write a function that divides one variable by another.
See if you can implement all 3 using at most 4 variables. Meaning, you're not making function calls now, you're making macros. And at
most you can have 4 variables. The restriction really only applies to
divide, the other 2 are easy to do with 4 vars or less. Division on
the other hand is dependent on the other 2 functions, so, if subtract
requires 3 variables, then divide only has 1 variable left unchanged
after a call to subtract. Basically, just make your function calls to
decrement and subtract so you pass your vars in by reference, and you
can't declare any new variables in a function, what you pass in is all
it gets.
My psuedocode solution (loop(x) means loop through this block of code x times):
// returns number - 1
int decrement(int number)
{
int previous = 0;
int i = 0;
loop(number)
{
previous = i;
i++;
}
return previous;
}
// returns number1 - number2
int subtract(int number1, int number2)
{
loop(number2)
{
number1= decrement(number1);
}
return number1;
}
//returns numerator/denominator
divide(int numerator, int denominator)
{
loop(subtract(numerator+1, denominator))
{
return (1 + divide(subtract(numerator, denominator), denominator));
}
return 0;
}
Here are C# methods that you can build and run. I had to make an artificial way for me to
satisfy the looping rules.
public int decrement(int num)
{
int previous = 0;
int LOOP = 0;
while (LOOP < num)
{
previous = LOOP;
LOOP++;
}
return previous;
}
public int subtract(int number1, int number2)
{
int LOOP = 0;
while (LOOP < number2)
{
number1 = decrement(number1);
LOOP++;
}
return number1;
}
public int divide(int numerator, int denominator)
{
int LOOP = 0;
while (LOOP < subtract(numerator+1, denominator))
{
return (1 + divide(subtract(numerator, denominator), denominator));
}
return 0;
}
Ok so the reason I think your answer might be invalid is because of how you use return. In fact I think just using the return is too much of an assumption. in a few places you use the return value of a function call as an extra variable. Now if the return statement is ok, then your answer is valid. The reason i think its not valid is because the problem hints at the fact that you need to think of these as macros, not function calls. Everything should be done by reference, you should change the variables and the return values are how you left those variables. Here is my solution:
int x, y, v, z;
//This function leaves x decremented by one and v equal to x
def decrement(x,v):
v=0;
loop(x):
x=v;
v++;
//this function leaves x decremented by y (x-y) and v equal to x
def subtract(x,y,v):
loop(y):
decrement(x,v);
//this function leaves x and z as the result of x divided by y, leaves y as is, and v as 0
//input of v and z dont matter, x should be greater than or equal to y or be 0, y should be greater than 0.
def divide(x,y,v,z):
z=0;
loop(x):
//these loops give us z+1 if x is >0 or leave z alone otherwise
loop(x):
z++;
decrement(x,v);
loop(x):
decrement(z,v)
//restore x
x++;
//reduce x by y until, when x is zero z will no longer increment
subtract(x,y,v);
//leave x as z so x is the result
x=z;

Resources