M. Boyes M. Boyes - 2 months ago 15
C Question

C Program crashes at For Loop

I'm new to C programming (I have some very basic experience with programming via vb.NET), and I'm attempting to write a program for the Project Euler Problem #1.
https://projecteuler.net/problem=1

Algorithm



The challenge requires the programmer to find the sum of all multiples of 3 or 5 (inclusive) below 1000 (I used intInput to allow the user to enter an integer in place of 1000).

My current solution takes the input, and decrements it by 1 until (intInput - n) % 3 = 0, that is, until the next nearest multiple of 3 under the input integer is found.

The program then cycles through all integers from 1 to ((intInput - n) / 3), adding each integer to the sum of the previous integers, so long as the current integer is not a multiple of 5, in which case, it is skipped.

The resultant sum is then stored in intThreeMultiplier.

The above process is then repeated, using 5 in place of 3 to find the highest multiple of 5 under intInput, and then cycles through integers 1 to ((intInput - n) / 5), not skipping multiples of 3 this time, and stores the sum in intFiveMultiplier.

The output sum is then calculated via sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier).

The Problem



Whenever I compile and run my code, the user is allowed to input an integer, and then the program crashes. I have determined that the cause has something to do with the first For loop, but I can't figure out what it is.

I have commented out everything following the offending code fragment.

Source Code:



#include <stdio.h>
#include <stdlib.h>

void main()
{
int intInput = 0; /*Holds the target number (1000 in the challenge statement.)*/
int n = 0;
int count = 0;
int intThreeMultiplier = 1;
int intFiveMultiplier = 1;

printf("Please enter a positive integer.\n");
scanf("%d",intInput);

for( ; (((intInput - n) % 3) != 0) ; n++)
{}

/*for(; count <= ((intInput - n) / 3); count++)
{
if ((count % 5) != 0)
{
intThreeMultiplier += count;
}
}

count = 0;
for(n = 0 ; ((intInput - n) % 5) != 0 ; n++)
{}

for(; count <= ((intInput - n) / 5) ; count++)
{
intFiveMultiplier += count;
}

int sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier);
printf("The sume of all multiples of 3 or 5 (inclusively) under %d is %d.",intInput, sum);*/
}


This is my first time posting on StackOverflow, so I apologize in advance if I have broken any of the rules for asking questions, and would appreciate any feedback with respect to this.

In addition, I am extremely open to any suggestions regarding coding practices, or any rookie mistakes I've made with C.

Thanks!

Answer
scanf("%d",intInput);

might be

scanf("%d", &intInput);  // note the ampersand

scanf need the address the variable where the content is to be stored. Why scanf must take the address of operator

For debugging only, print the input to verify that the input is accepted correctly, something like

printf("intInput = %d\n", intInput);
Comments