Search code examples
cif-statementnested-loopsmodulussqrt

C Code For loop with nested If; modulus and sqrt issue


So, I am trying to get this C code to work. It compiles, but produces incorrect outputs. It should list all pefect square numbers between 1 and a chosen value. It is doing something wrong, and after alot of trial and error i think the issue is with the modulus operation...like its truncating early or doing some other strange thing.

// C Code


/*This program will identify all square numbers between one and a chosen integer*/

#include <stdio.h>
#include <math.h>

int main(){

int i, upper, square_int;
float square;
printf("This program will identify all square numbers between one and a chosen integer");

printf("Please enter the upper limit integer:");
scanf("%d", &upper);

upper = 13; /*scanf is the primary integer input method; this is here just to test it on codepad*/

for (i = 1; i<= upper; ++i) /*i want to run through all integers between 1 and the value of upper*/
{ 
    square = sqrt(i);  /* calc square root for each value of i */
    square_int = square;  /* change the root from float to int type*/

    if (i % (int)square_int == 0) /*check if i divided by root leaves no remainder*/
        printf("%d\n", i);  /*print 'em*/
}
printf("This completes the list of perfect squares between 1 and %d",upper);

return 0; /*End program*/
}

The output on codepad is:

This program will identify all square numbers between one and a chosen integerPlease enter the upper limit integer:1
2
3
4
6
8
9
12
This completes the list of perfect squares between 1 and 13

Which is of course wrong. I expect to get 1, 2, 4 and 9 back. Can anyone point out my screw up here?


Solution

  • Here is a simpler algorithm

    int i = 1;
    while (i*i < upper)
    {
        printf("%d\n", i*i);
        ++i;
    }
    

    Another method is computing the square root, convert it to int, and compare the numbers.

    for (i = 1; i <= upper; ++i)
    {
        square = sqrt(i);
        square_int = square;
        if (square == (float)square_int)
            printf("%d\n", i );
    }