Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main()
{
int a,query,in,n,b[n],sum[a];
sum[1]=0;
scanf("%d",&query);
for(a=1;a<=query;a++)
{
scanf("%d",&in);
for(n=1;n<=in;n++)
{
b[n]=1+7*(n-1)+6*(n-1)*(n-2)+(n-1)*(n-2)*(n-3);
sum[a]=sum[a]+b[n];
}
}
for(a=1;a<=query;a++)
{
printf("%d\n",sum[a]);
}
return 0;
}
I have made this code which is running in terminal .
But in hacker rank it is showing
Input (stdin)
2
2
5
Your Output (stdout)
~ no response on stdout ~
Expected Output
9
225
Compiler Message
Segmentation Fault
Now what should I do to solve the problem .
Your variables are uninitialized. As a result your program invokes Undefined Behavior.
For example you do not initialize n, but you then declare int b[n]. What is the size of array b? Nobody really knows, since n has a garbage value.
Start by figuring out what the values of your variables should be, and then start coding.
Array indexing starts from 0, thus your for loops are not looking good.
Change this:
for(a=1;a<=query;a++)
to this:
for (a = 0; a < query; a++)
int main()
{
int a, query, in, n, *b, *sum;
scanf("%d",&query);
sum = malloc(query * sizeof(int));
/* do some checks if the malloc was successful */
for(a = 0; a < query; a++)
{
scanf("%d",&in) ; /* you should check if scan has returned 1 */
b = malloc(in * sizeof(int)); /* and again check against any allocation errors */
for(n = 0; n < in; n++)
{
b[n] = 1+7*(n)+6*(n)*(n-1)+(n)*(n-1)*(n-2);
sum[a] = sum[a] + b[n];
}
free(b);
}
/* the rest */
In int a,query,in,n,b[n],sum[a];, the value of a is not initialised and is having garbage value which could be anything. This value is used as the size of the variable length array sum. So the size of the array could be anything which is probably not what you want.
a could be 0 in which case sum is an array of size 0 which will in turn make sum[1] incorrect (it would be undefined behavior).
The same applies to n and b[n].
In the nested for loop, with sum[a]=sum[a]+b[n]; you are using sum[a] which has not been initialised. It has garbage value and the result is indeterminate.
If you wanted all elements of sum to be initialised with 0, you can do
int sum[20]={0};
at the time of declaring it.
The same goes for b[n]=1+7*(n-1)+6*(n-1)*(n-2)+(n-1)*(n-2)*(n-3); as well.
And array indexing starts at 0.
Perhaps you could use the loops like
for (a = 0; a < query; a++) {
instead of
for (a = 1; a <= query; a++)
If you choose the starting index as 0, the inner nested loop should be like
for(n=0;n<in;n++)
{
//b[n]=1+7*(n-1)+6*(n-1)*(n-2)+(n-1)*(n-2)*(n-3);
b[n]=1+7*(n)+6*(n)*(n-1)+(n)*(n-1)*(n-2);
sum[a]=sum[a]+b[n];
}
See demo.
Your problem is in this line:
int a,query,in,n,b[n],sum[a];
What is the meaning of b[n]? And of sum[a]? Assuming that you would like to have a language with magically growing arrays, C is a bad choice.
In C language arrays are a structure with size known at compile time. Anyway, let's assume that your compiler supports the horrible hack of variable-length arrays. You can do this:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(void) {
int a, query, in , n;
scanf("%d", &query);
int sum[query+1];
for (a = 1; a <= query; a++) {
sum[a] = 0;
scanf("%d", &in);
int b[in+1];
for (n = 1; n <= in ; n++) {
b[n] = 1 + 7 * (n - 1) + 6 * (n - 1) * (n - 2) + (n - 1) * (n - 2) * (n - 3);
sum[a] = sum[a] + b[n];
}
}
for (a = 1; a <= query; a++) {
printf("%d\n", sum[a]);
}
return 0;
}
Note the changes: first you need to know the size of the array, then you can allocate it. Moreover, I increased the size of the array in order to support your choice of starting from 1. Lastly I also zeroed the initial value for sum array.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
When I'm running the program, the 2nd and the 3rd values being printed are garbage values, and I don't know why. I think it should be the numbers I've entered.
The code:
int main()
{
int a = 0, b = 0;
int * students = NULL;
int * size = &a;
int * studentscount = &b;
func1(students, size, studentscount);
return 0;
}
#include "Source.h"
int checkAllocation(void * ptr)
{
if (ptr == NULL)
return 1;
return 0;
}
int * doubleArr(int *arr, int size)
{
int * newArr = (int*)malloc(size * sizeof(int));
checkAllocation(newArr);
for (int i = 0; i < size; i++)
newArr[i] = arr[i];
size *= 2;
newArr = (int*)realloc(newArr, size);
checkAllocation(newArr);
free(arr);
return (newArr);
}
void func1(int *students, int *size, int *studentscount)
{
int num;
students = (int *)malloc(sizeof(int) * 2);
checkAllocation(students);
*(studentscount) = 0;
*(size) = 2;
printf("Enter students, to end enter a negative number.\n");
do
{
printf("Enter student number %d: ", *(studentscount)+1);
scanf("%d", &num);
if (num >= 0)
{
*(students + *(studentscount)) = num;
*(studentscount) += 1;
}
if (*(studentscount) == (*size))
{
students = doubleArr(students, *(size));
*(size) *= 2;
}
} while (num >= 0);
printf("******************\nArray size: %d\nNumber of students: %d\n******************\n", *(size), *(studentscount));
for (int i = 0; i < *(studentscount); i++)
printf("student #%d: %d\n", i + 1, *(students + i));
free(students);
}
Any suggestions to make the code print the values I entered and not the garbage values?
There are some issues you should probably work on, but the reason for garbage is very likely statement realloc(newArr, size), which considers only the count but not the size of datatype int. Hence, instead of doubling the array size, you are actually decreasing it; Consequently, realloc might give you back a different memory block where only portions of the previous one has been taken over; or some parts of the memory you have written values to have gone invalid. Anyway, you have a good chance here to loose your entered values. So - as pointed out by bluepixy, statement realloc(newArr, size*sizeof(int)) should solve the main problem.
Note further that statement realloc, when allocating memory at a different place, takes over the content of the former memory block and (in this case) frees the former block (cf. cppreference of realloc). So there is no need to transfer the data manually, there is particularly no need to first malloc and then realloc, and there is consequently no need for a separate free at the end. So the code of doubleArr could actually look like the following.
int * doubleArr(int *arr, int size) {
return realloc(arr,size*2*sizeof(int));
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
#include <stdio.h>
int main()
{
int i, n, c, p;
printf("enter\n");
scanf("%d", n);
c = find(n);
if (c == 1)
{
printf("no. is not prime");
}
else
{
printf("no. is prime");
}
}
find(int n)
{
int i = 2, p;
while (i < n)
{
p = n % i;
printf("value of p%d", p);
if (p == 0)
{
return 1;
}
i = i + 1;
}
return 2;
}
....................................
Above program giving me 'not a prime number' output for all inputs...also the value of p is always zero and this shouldn't be the case...
Please help...badly stuck...
Your scanf() call must take the address of n. Furthermore you primality test fails for numbers smaller than 2. It is also better to return non-zero for true, zero otherwise, so that the value can directly be tested with if. And you should find a better name than find.
Try something like this:
#define TRUE 1
#define FALSE 0
int is_prime (int n)
{
int i;
if (n < 2)
return FALSE;
for (i = 2; i < n; i++) {
if (n % i == 0) {
return FALSE;
}
}
return TRUE;
}
int main()
{
int n;
printf ("enter number: ");
scanf ("%d", &n);
if (is_prime (n)) {
printf ("number is prime.\n");
}
else {
printf("number is not prime.\n");
}
return 0;
}
Various improvements are possible but I wanted to stay as close to your code as possible.
This looks like a student exercise so let me start by suggesting that the debugger is your friend. :)
Having said that, you may want to review the Sieve of Eratosthenes and leverage Wikipedia for a source of some good test content.
As already suggested, there are loads of potential improvements... I'd modify your "find" function to be more clear as follows:
bool IsPrime(unsigned int n)
{
unsigned int nCounter = 2;
while (n % nCounter++);
return (nCounter > n);
}
Prime's can't be negative and since you're asking a "TRUE/FALSE" question, the name and return type should enforce that contract.
Several issues:
scanf("%d", n); should be scanf("%d", &n); - you need to pass the address of n so scanf can update it (note that you risk a runtime error,
since the value of n most likely isn't a valid address value);
Implicit typing of functions such as find(int n) {...} is no longer supported as of the C99 standard, and it was never good practice to begin with. You should (and for C99 and later, must) provide a type specifier along with the function name in both function declarations and function definitions - int find( int n ) {...};
Similar to 2, a function declaration must be visible before a function is called; the simplest way to accomplish this is to move the function definition above the definition for main. If you don't want to do that, then you need to add the declaration int find(int n); somewhere before find is called.
Note that you can speed up the primality test in a couple of ways. First, you can skip testing against even factors; if a number is divisible by a multiple of 2, then it's divisible by 2, and you would have already checked for that. Secondly, you don't need to test all factors up to n - 1; you only need to test factors up to the square root of n. You can put that all together like so:
if ( n < 2 )
return 0; // zero indicates false
if ( n == 2 )
return 1; // non-zero indicates true
int result = n % 2;
for ( int i = 3; result && i * i <= n; i += 2 ) // loops as long as result
result = n % i; // is non-zero, only tests
// against odd numbers up to
return result; // sqrt(n)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i'm a beginner c programmer studying computer science and i'm trying to create a sorting program to sort an array of integers although i keep getting wrong results, this is what i got so far:
#include <stdio.h>
#include <string.h>
#define TAM 9
int sort_array(int num1[],int num2[]);
int main(){
int i=0;
int num1[TAM] = {5,6,2,4,7,1,3,0};
int num2[TAM] = {0};
int * ptr_num2 = num2;
sort_array(num1,num2);
while(*ptr_num2 != '\0'){
printf("%c",*ptr_num2+48);
ptr_num2++;
}
putchar('\n');
return 0;
}
int sort_array(int num1[],int num2[]){
int min=256,max=0,i,j;
int * ptr_num1 = num1;
int * ptr_max = num1;
int * ptr_num2 = num2;
/* check for max */
while(*ptr_max != '\0'){
if(*ptr_max > max) max = *ptr_max;
ptr_max++;
}
for(i=0;i<TAM-1;i++){
/* check for min */
for(j=0;j<TAM-1;j++){
if(*ptr_num1 < min) min = *ptr_num1;
ptr_num1++;
num1[i] = max;
}
*ptr_num2 = min;
ptr_num2++;
}
return 0;
}
I've been banging my head for several hours on this already.
EDIT: Forgot to mention that some of these things might not make sense since i'm just experimenting with a few things.
I understand you do not know about the typical array sorts... Well, let me to introduce you to one of the more simple ones. Allthough it's usually not the most efficient one, it's the easiest one to understand, and considering the fact you are messing with little arrays and not databases, it will be just fine.
I am talking about good old Chum, our Bubble sort.
Bubble sort is a well known simple array sorting algorithm -
The logic is simple. You go over the whole array on pairs of two - I.e, Array[0] with Array[1], Array[1] with Array[2], etc...
Whenever you find that things are not the way they are supposed to be - in your case, The larger index number is bigger than the lower index number - you swap between them, until you reach an iteration where you passed through the whole array and didnt swap at all.
In case you didn't understand well, here's Pseudo code from wikipedia (OMG who the heck uses wikipedia i'm such a n00b):
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure
And here's some C code:
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
Here again, btw, the credit is not for me:
http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort
Hope this helped you, and good luck :)
Program Design, our first homework assignment was to take 4 integer values, add the 2 highest together and subtract the lowest two and square that result. Finally, compare the 2 values together to see if they are equal or not.
For example, if you were to enter: 20 10 60 40
You'd get
60 + 40 = 100
and
20 - 10 = 10 --> 10^2 = 100
So, 100 == 100
I wrote my program and tested it for various values which all returned correct results. My professor told me my program failed for all 10 test inputs and he sent me the results he got. The results he got aren't the same as mine, and I don't know what's going on. I emailed him, and he told me one of my for loops has incorrect bounds. He's right, but I still get the right results, so...?
Here's the code, any help would be appreciated!
/*
// Author: Jesse W
// Assignment 1
// Desciption:
// This program inputs four integer numbers a, b, c and d and
// determines if the sum of the two largest numbers is the same
// as the squared difference of the two smallest numbers
*/
#include <stdio.h>
/* Complete the code for this program below */
int main()
{
int a, b, c, d, f, k, swap;
int array_size = 4;
int return_val;
int sum, difference, square;
int small_1, small_2, large_1, large_2;
int array[array_size];
//Gather input
//printf("Enter integer values for a, b, c and d.\n");
return_val = scanf("%d %d %d %d", &a, &b, &c, &d);
//Validate input
if (return_val != 4)
{
printf("INVALID INPUT\n");
}
else
{
//Assign values to array
array[0] = a;
array[1] = b;
array[2] = c;
array[3] = d;
//Sort array
for (k = 0 ; k < ( array_size - 1 ); k++)
{
for (f = 0 ; f < array_size ; f++)
{
if (array[f] > array[f+1]) /* For decreasing order use < */
{
swap = array[f];
array[f] = array[f+1];
array[f+1] = swap;
}
}
}
//Assign sorted values to new variables
small_1 = array[0];
small_2 = array[1];
large_1 = array[2];
large_2 = array[3];
//Compute math
sum = large_1 + large_2;
difference = small_1 - small_2;
square = difference * difference;
//Compute logic
if(sum == square)
{
printf("%d equals %d.\n", sum, square);
}
else
{
printf("%d does not equal %d.\n", sum, square);
}
return 0;
}
}
f ranges up to array_size - 1
for (f = 0 ; f < array_size ; f++)
but in that case you access array[ f + 1 ] which is array[ array_size ]
array[f] = array[f+1];
array[f+1] = swap;
This results in undefined behavior. Since the value one past the end is effectively sorted as part of the array, whether the program works or not depends whether the uninitialized value is larger than all the input values.
The problem is indeed the upper bound on your inner for loop; it's causing you to read past the end of your array, which causes undefined behaviour.
It's entirely possible that the resulting program still prints the correct results on your machine, but there is no guarantee that it will work on anyone else's. Hence undefined.
Your inner loop will end up accessing array[4], which triggers undefined behavior. As soon as you trigger undefined behavior, you can't guarantee anything about the program after that point.
What's likely actually happening, though, is that on your computer, array[4] just happens to be larger than array[3] and you keep those in the same order. On your professor's computer, you swap them (probably corrupting some other variable), making array[3] be that undefined value.
Since your program's output depends totally on the value of array[4], where array is an array of length 4, its behavior is completely unpredictable: there's no way, from the source, to guess what value will happen to be in memory at location array + 4.
(In fact, it's even worse than that — your program invokes undefined behavior, which means that it's allowed to do absolutely anything at all, up to including sending your professor a vulgar and insulting e-mail that looks like it's from you. But in practice, it's likely to print one of its expected outputs, there's just really no way to guess which one.)
Change your sort loop to this
for (k = 0 ; k < array_size ; k++)
{
for (f = 0 ; f < (array_size -1) ; f++)
{
if (array[f] > array[f+1]) /* For decreasing order use < */
{
swap = array[f];
array[f] = array[f+1];
array[f+1] = swap;
}
}
}
I have a simple test program in C to scramble an array of values on the heap. Sidenote: I know the random logic here has a flaw that will not allow the "displaced" value to exceed RAND_MAX, but that is not the point of this post.
The point is that when I run the code with N = 10000, every once in a while it will crash with very little information (screenshots posted below). I'm using MinGW compiler. I can't seem to reproduce the crash for lower or higher N values (1000 or 100000 for example).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int N = 10000;
int main() {
int i, rand1, rand2, temp, *values;
/* allocate values on heap and initialize */
values = malloc(N * sizeof(int));
for (i = 0; i < N; i++) {
values[i] = i + 1;
}
/* scramble */
srand(time(NULL));
for (i = 0; i < N/10; i++) {
rand1 = (int)(N*((double)rand()/(double)RAND_MAX));
rand2 = (int)(N*((double)rand()/(double)RAND_MAX));
temp = values[rand1];
values[rand1] = values[rand2];
values[rand2] = temp;
}
int displaced = 0;
for (i = 0; i < N; i++) {
if (values[i] != (i+1)) {
displaced++;
}
}
printf("%d numbers out of order\n", displaced);
free(values);
return 0;
}
it may be because rand() generates a random number from 0 to RAND_MAX inclusive so (int)(N*((double)rand()/(double)RAND_MAX)) can be N, which exceeds the array boundary. however, i don't see why that would vary with array size (it does explain why it only crashes sometimes, though).
try /(1+(double)RAND_MAX) (note that addition is to the double, to avoid overflow, depending on the value of RAND_MAX) (although i'm not convinced that will always work, depending on the types involved. it would be safer to test for N and try again).
also, learn to use a tool from Is there a good Valgrind substitute for Windows? - they make this kind of thing easy to fix (they tell you exactly what went wrong when you run your program).