Incorrect 'for' loop results C++

Viewed 118

I am a beginner at using C++ so I was wondering if someone would be able to help me out as I'm currently trying to print a 'for' loop. The 'alfa' loop is printing correctly but when that information is called upon by the 'sina' loop, only zeros are being printed in the console.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <new>
#include <ctime>
#include <string>
#include <sstream>
#include <vector>

const double convToRad = pi/180.0;

int main(){

    int INDEX = 91;
    double alfa[INDEX] {0};
    double sina[INDEX] {0};

for (int p = 90; p >= 0; p--){
     alfa[INDEX] = p*convToRad;
     //std::cout << alfa[INDEX] << std::endl;
 }

for (int e = 0; e <= 90; e++){
    sina[INDEX] = sin(alfa[INDEX]);
    std::cout << sina[INDEX] << std::endl;        //only prints 0's
 }

   return 0;

}
2 Answers

Your are accessing wrong memory location. INDEX=91; You had typed INDEX instead of p and e in both the loops. So accessing a single wrong location which may gives a junk value or crash the program.

A few notes:

  • Don't use magical numbers, use constants.

  • Don't use the numbers in the array which are constant as you did.

Try a simple fix:

for (int p = 0; p < INDEX; p++) {
    // storing 90* stuff in first index, 89* in second and so on...
    alfa[p] = (90 - p) * convToRad;
    // std::cout << alfa[p] << std::endl;
}

for (int e = 0; e < INDEX; e++) {
    sina[e] = sin(alfa[e]);
    std::cout << sina[e] << std::endl;
}
Related