0

So the question is: Write a program in C such that it contains a function which calculates the third power of a given integer. It should calculate the third power of numbers between 1 and 10 using your function and the results should be saved in an array.

This is what I have (below). I keep getting an error from CCS on the line output=powerOfThree(int i+1);. The error says 'expected an expression'. I'm not sure what I'm doing wrong.

#include<msp430.h>     

long int powerOfThree(int a);
long int arrayOfTen[10];
int powers = 3;
int output;
int i;
int temp;

int main(void) {
    WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer

    for (i = 0; i <= 10; i++)
    {
        output = powerOfThree(int i+1);
        arrayOfTen[i] = output;

        return output;
    }
}

long int powerOfThree(int a)
{
    int result = a*a*a;
    return result;
}

2 Answers2

2

Above code having following errors:

  • In line output = powerOfThree(int i+1); there is syntax/semantics error. You should change it to output = powerOfThree(i+1);
  • Conditional part in for loop should be changed from i<=10 to i<10
  • Return return output; statement should not be inside the loop.
  • If you wish that function powerOfThree(int a) should return long int then function prototype should be long int powerOfThree(long int a) or typecast a to long int to prevent data error.

Following is the corrected code:

Note: Some changes have been made for optimization i.e. removal of unnecessary variables.

#include<msp430.h>     

long int powerOfThree(long int a);
long int arrayOfTen[10];
int i;

int main(void) {
    WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer

    for (i = 0; i < 10; i++)
    {
        arrayOfTen[i] = powerOfThree(i+1);
    }
    return 0;
}

long int powerOfThree(long int a)
{
    long int result = a*a*a;
    return result;
}
cse
  • 4,066
  • 2
  • 20
  • 37
0

the following proposed code:

  1. cleanly compiles
  2. is modified to run on linux
  3. declares everything as long int to avoid conversion/overflow problems.
  4. performs the desired function.

and now the code

//#include <msp430.h>
#include <stdio.h>

#define MAX_NUM 10

long int powerOfThree(long a);

int main(void)
{
    long int arrayOfTen[ MAX_NUM ];
    //WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer

    for ( long i = 0; i < MAX_NUM; i++)
    {
        arrayOfTen[i] = powerOfThree(i+1);
        printf( "%ld to the third power is %ld\n", i+1, arrayOfTen[i] );
    }
}

long int powerOfThree(long a)
{
    long result = (long)a*a*a;
    return result;
}

The output of the proposed code is:

1 to the third power is 1
2 to the third power is 8
3 to the third power is 27
4 to the third power is 64
5 to the third power is 125
6 to the third power is 216
7 to the third power is 343
8 to the third power is 512
9 to the third power is 729
10 to the third power is 1000
user3629249
  • 16,402
  • 1
  • 16
  • 17