Sanyam Jain
Sanyam Jain

Reputation: 23

what can be the cause of segsigv error in my program?

I am quite new to coding and I was trying to solve a problem in which we would be given a number of test cases (say n) and an integer (say k). So for each test case, a new integer(say a) will be given for which we have to find how many numbers (say sum) is divisible by k.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n,k,sum;
    scanf("%d",n);
    scanf("%d",k);
    while(n>0)
    {
        int a;
        scanf("%d",a);
        if(a%k==0)
        {
            sum++;
        }
        n--
    }
    printf("%d",sum);
    return 0;
}

Upvotes: 1

Views: 96

Answers (1)

Jarvis
Jarvis

Reputation: 8564

First, you provide the address of the variable when scanning with scanf:

scanf("%d", &n);
scanf("%d", &k);
scanf("%d", &a);

Also, initialise sum:

sum = 0;

Second, this is C++, so use cin and cout instead:

std::cin >> n >> k;
std::cin >> a;

std::cout << sum;

Upvotes: 2

Related Questions