Go Back  Xtreme Visual Basic Talk > Other Languages > Miscellaneous Languages > Exponentiation using For Loop in C#


Reply
 
Thread Tools Display Modes
  #1  
Old 01-12-2010, 02:59 AM
CarlMartin10 CarlMartin10 is offline
Regular
 
Join Date: Dec 2009
Posts: 54
Exclamation Exponentiation using For Loop in C#


I am not used to C#, I am very new to it. I am trying to learn how to use the For Loop. I want to create a program that calculates an answer based on user input.

The user inputs a base number, and an exponent. The calculator then needs to calculate the exponentiation.

Example: 3^3 = 27

I am having 3 real problems.

1) I do not know how to get the value calculated by the loop to be returned within the method, using a "return" line.

2) For some reason, the calculation is incorrect, so I do not know what I am doing wrong in the actual loop to get the wrong answer.

3) I am not sure I am calling the method correctly.

If you can help, I thank you.

Code:
{
    public partial class frmExpCalc : Form
    {
        
        public frmExpCalc()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnCalc_Click(object sender, EventArgs e)
        {
            {
                // Exception handling to make sure user enters a numerical value into text box
                try
                {
                    // Declare variables
                    int baseNum = int.Parse(tbxBase.Text);
                    int power = int.Parse(tbxPower.Text);
                    

                    // Declare variable to hold value from method, and cal method
                    int result = calculatePower(power);
                    

                    // Send results to appropriate label
                    lblResults.Text = result.ToString();
                    
                    }
                catch
                {
                    // Display message if nothing, or non-numerical values entered by user
                    MessageBox.Show("Please enter numerical values ONLY.", "Error");
                }
            }
        }
     
            // Create method to perform exponentiation calculation

            private int calculatePower(int total)        
                
            {
                // Declare variables
                int baseNum = int.Parse(tbxBase.Text);
                int power = int.Parse(tbxPower.Text);

                // Use Loop to perform exponentiation
                for (; power != 0; power--) baseNum *= power;

                // Return results of calculation
                return;
                

            }
            
            }
        }
Reply With Quote
  #2  
Old 01-12-2010, 09:31 AM
AtmaWeapon's Avatar
AtmaWeapon AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,505
Default

Just to get an idea of how much needs to be explained, could you write this program in VB .NET? If so, how about you try that first, get it working, then try to apply that to C#? In short, I'm fishing for the answer to "Do you need me to explain for loops in general, or just what's wrong with your algorithm?"

I'll assume you're familiar with for loops and only explain that if asked.

Think about how you raise a number to a power. Let's use 2^5 as an example. To get the result, you multiply 2 * 2 * 2 * 2 * 2 to get 32. So ideally, for inputs "2" and "5" you'd want your algorithm to do the same thing as 2 * 2 * 2 * 2 * 2. Right now, your algorithm is multiplying by power each time, which happens to be the loop variable and will change each time. So for "2" and "5", your loop will produce 2 * 5 * 4 * 3 * 2 * 1. Instead of multiplying by power, you should multiply by the original number each time.

You're not using the "return" keyword correctly, and you don't need or use the total parameter at all. Do you understand how functions work? Let's say I had a function called ReturnsTwo():
Code:
int ReturnsTwo()
{
    return 2;
}
You put the value you want to return after the return keyword. The type of the return value must match the type of the function; in this case the function is supposed to return int and I'm returning an integer. You would use this function where you'd use any other expression that generates a value:
Code:
int two = 2;
int alsoTwo = ReturnsTwo();
Also note that most C# developers really, really, *really* frown upon cramming an entire loop onto one line. Here's a hint as to what your final implementation would look like using more idiomatic C#:
Code:
private int CalculatePower(int base, int exponent)
{
    int total = 1;
    for (int i = exponent; i > 0; i--)
    {
        total *= ???;
    }
    
    return total;
}
This may or may not be off by one on the exponentiation; I'd test it but I usually just use Math.Pow() instead.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #3  
Old 01-12-2010, 11:41 AM
CarlMartin10 CarlMartin10 is offline
Regular
 
Join Date: Dec 2009
Posts: 54
Default

Here is what I have come up with, but I am still confused on syntax. I am getting a build error stating that the loac variable "power" can not be declared in the scope because it is already used in a different scope. It is referring to this code, specifically the variable "power":

Code:
 // Declare variables
            int baseNum = int.Parse(tbxBase.Text);
            int power = int.Parse(tbxPower.Text);
Here is the total code I have, which should work *fingers crossed* if I can get the syntax and build errors fixed. Anyone have any ideas?

Code:
 public frmExpCalc()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnCalc_Click(object sender, EventArgs e)
        {
            {
                // Exception handling to make sure user enters a numerical value into text box
                try
                {
                    // Declare variables
                    int baseNum = int.Parse(tbxBase.Text);
                    int power = int.Parse(tbxPower.Text);
                    

                    // Declare variable to hold value from method, and cal method
                    int result = calculatePower(power);
                    

                    // Send results to appropriate label
                    lblResults.Text = result.ToString();
                    
                    }
                catch
                {
                    // Display message if nothing, or non-numerical values entered by user
                    MessageBox.Show("Please enter numerical values ONLY.", "Error");
                }
            }
        }
     
            // Create method to perform exponentiation calculation

            private int calculatePower(int power)
        {
            // Declare variables
            int baseNum = int.Parse(tbxBase.Text);
            int power = int.Parse(tbxPower.Text);

            // Use Loop to perform exponentiation
            int result = baseNum;

     for(int i = 0; i < power; i++)
     {
           result *= baseNum;
     }


        }
            
            }
        }
Reply With Quote
  #4  
Old 01-12-2010, 02:18 PM
AtmaWeapon's Avatar
AtmaWeapon AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,505
Default

The syntax oddities towards the end suggest you just pasted my code in. Spend some time thinking. The compiler doesn't spit out error messages in order to anger you; it always has a reason for giving you an error message. When it tells you there's already another variable in scope, then you need to find that variable and decide what to do.

You have two local variables named power in your code:
Code:
private int calculatePower(int power)
{
    int baseNum = ...;
    int power = ...;
One or the other has to go. In my opinion, it's more natural to use a parameter than control values, but you might decide against it. Otherwise everything looks fine.
Reply With Quote
  #5  
Old 01-12-2010, 02:58 PM
Iceplug's Avatar
Iceplug Iceplug is offline
MetaCenturion

Retired Moderator
* Guru *
 
Join Date: Aug 2001
Location: California, USA
Posts: 16,583
Default

Also, your function doesn't return result. You should receive a warning that the function doesn't return value on all code paths (or, in this case, any).

A slightly less ambiguous suggestion to the code that you are posting:
Consider the fact that, if I 'unrolled' the function into the subroutine that called the function, I'd get something that looks like this (ignoring the try block):
[code]
// Declare variables
int baseNum = int.Parse(tbxBase.Text);
int power = int.Parse(tbxPower.Text);
// Declare variable to hold value from method, and cal method
// Underlined code represents what's in your function.

// Declare variables
int baseNum = int.Parse(tbxBase.Text);
int power = int.Parse(tbxPower.Text);

Now, you have two variables that contain the value of baseNum: the one in the function, and the one in btncalcclick, the subroutine that called the function.
You only *use* the one in the function, so the one in btnCalc_Click is therefore, useless.
Something similar occurs with power: the one in btnCalc_Click is passed to the function, but the calculatepower function never uses the power variable that is passed to the calculatepower function... instead, declaring its own version of power and calculating power again, when it has already been calculated. So, in fact, the basenum and power are both useless.
(However, if you merely highlight and delete both, your calculatepower function will still be expecting an input for its power variable despite the fact that the input value for power will never be used)
A more fitting solution would be to remove the power that is recalculated in the subroutine. This would serve two purposes: power calculated in btnCalc_Click is no longer useless and the input to calculatepower is no longer useless.
__________________

Iceplug, USN
Quadrill 1 Quadrill 2 (full) Quadrill 3 JumpCross .NET Website is ALIVE! - DL Platform Tour for VB.NET! Posting Guidelines Hint: Specify your location in your user cp profile if you want compassion!
Reply With Quote
  #6  
Old 01-13-2010, 10:37 AM
CarlMartin10 CarlMartin10 is offline
Regular
 
Join Date: Dec 2009
Posts: 54
Default

Here is what I have now after looking at this again. Everything is in order, with the exception of the variable "total" within the method. I am getting the error "use of unassigned local variable" related to this line of code:

return total;

I still can not work out how to get this last and final error handled.

Here is the current code:

Code:
public frmExpCalc()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnCalc_Click(object sender, EventArgs e)
        {
            {
                // Exception handling to make sure user enters a numerical value into text box
                try
                {
                    // Declare variables
                    int baseNum = int.Parse(tbxBase.Text);
                    int power = int.Parse(tbxPower.Text);

                    // Declare variable to hold value from method, and cal method
                    int result = CalculatePower(baseNum, power);

                    // Send results to the results label
                    lblResults.Text = result.ToString();
                    
                    
                    }
                catch
                {
                    // Display message if nothing, or non-numerical values entered by user
                    MessageBox.Show("Please enter numerical values ONLY.", "Error");
                }
            }
        }
     
            // Create method to perform exponentiation calculation

           private int CalculatePower(int baseNum, int power)
        {


            // Use Loop to perform exponentiation            
            int total;
            for (int i = 1; i < power; i++)
                total = baseNum * baseNum;
            {
                
                return total;
            }
        }
            
            }
        }
Reply With Quote
  #7  
Old 01-13-2010, 12:30 PM
Iceplug's Avatar
Iceplug Iceplug is offline
MetaCenturion

Retired Moderator
* Guru *
 
Join Date: Aug 2001
Location: California, USA
Posts: 16,583
Default

Well, initializing the value of total to 1 in the event that power is a number that is less than 1 (for example: 0) should satisfy that requirement.

However, if you look at the code in the for loop, you are simply setting total = basenum * basenum.
If basenum is equal to 3 and power is equal to 7.
No matter how many times you write
total = basenum * basenum
total will be equal to 3 * 3, which is 9.
Calculating 3 * 3 for seven times will still give you 9.

Also, you return total in a rogue block of code:
The for block ended at the semicolon on the line:
total = baseNum * baseNum;
The { and } afterward are not connected to any kind of block keyword such as if, for, while, etc.
__________________

Iceplug, USN
Quadrill 1 Quadrill 2 (full) Quadrill 3 JumpCross .NET Website is ALIVE! - DL Platform Tour for VB.NET! Posting Guidelines Hint: Specify your location in your user cp profile if you want compassion!
Reply With Quote
  #8  
Old 01-13-2010, 02:16 PM
CarlMartin10 CarlMartin10 is offline
Regular
 
Join Date: Dec 2009
Posts: 54
Default

Thanks everyone, I go *** to work.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
 
 
-->