Runtime Error - SIGSEGV - c

I am supposed to write a program for adding array elements and remove the elements from the sum if the previous element is 0,but i'm getting Run Time error as SIGSEGV.How can i solve this error.
#include <stdio.h>
int main()
{
int i,arr[10],n,sum=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d\n",&arr[i]);
}
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
for(i=0;i<n;i++)
{
if(arr[i]==0)
{
sum=sum-arr[i-1];
}
}
printf("%d",sum);
return 0;
}

In this statement
sum=sum-arr[i-1];
when i is equal to 0 you are trying to access memory beyond the array.
Remove the new line character from the call of scanf
scanf("%d\n",&arr[i]);
^^
And if you ask the user to enter the number of elements of the array then you should check that the entered number is less than or equal to 10.
I think that it does not make sense to ask the user to enter the number of elements of the array. Otherwise it is better to use a Variable Length array if the compiler supports them.
The program can look the following way
#include <stdio.h>
#define N 10
int main( void )
{
int a[N];
printf( "Enter %d elements: ", N );
int n = 0;
while ( n < N && scanf( "%d", &a[n] ) == 1 ) n++;
long long sum = 0;
for ( int i = 0; i < n; i++ )
{
if ( i + 1 == n || a[i+1] != 0 ) sum += a[i];
}
printf( "\nsum = %lld\n", sum );
return 0;
}
If for example to enter the following sequence of numbers
1 2 0 3 4 0 5 6 0 7
then the output can look like
Enter 10 elements: 1 2 0 3 4 0 5 6 0 7
sum = 16

The Problem Here is size of the Array.
You declared array for size 10 and if the user enters the size as 100 then this kind of Run time error will appear.
To avoid this exception simply declare the array after user enters thee size i.e
scanf("%d",&n);
int arr[n];

Related

Need to write a program that asks the user to fill in a 2D array then checks how many times a digit between 0 and 9 was entered in those two rows

**This was a deleted question but I remade it so it easier for this community to understand what I'm asking
Here is my code:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int row;
int col;
int x;
int y;
int i = 9;
int count[i];
printf("Enter the size of your array: ");
scanf("%d %d", &row, &col);
int arr[row][col];
//This will read the rows
for (int x = 0; x < row; ++x) {
for (int y = 0; y < col; ++y) {
printf("Enter row %d: ", x);
scanf("%d", &arr[x][y]);
}
}
//This will create a count for the rows
for (x = 0; x < row; ++x) {
for (y = 0; y < col; ++y) {
++count[arr[x][y]];
}
}
//This will count if digits repeat in the rows and print it
printf("\nTotal count for each digit:\n");
for (int j = 0; j < 10; ++j) {
printf("Digit %d occurs %d time%s\n", j, count[j], count[j] > 1 ? "s" : "");
}
return 0;
}
Notes on the code
I made i = 9 because the max number the user should enter is 9
On the "This will read the rows" there should be two printf's
"Enter Row 0"
"Enter Row 1"
How would I go and make it so the user would enter a set of numbers for the user to enter in both the rows. When I compile it just keeps saying "enter row 0: enter row 0: enter row 0". The program should find out how many times a number between 0 and 9 was entered. The final result should look like this
Enter the size of your array: 2 6
Enter row 0: 0 1 2 3 4 5
Enter row 1: 0 1 6 7 8 9
Total count for each digit:
Digit 0 occurs 2 times
Digit 1 occurs 2 times
Digit 2 occurs 1 time
Digit 3 occurs 1 time
ect. This would keep going until it the program hits "Digit 9 occurs however many times.
When I compile without the printf it runs through 3 rows when it should be 2 and most of the numbers that the compiler gives out are wack except for 2 digits
Ex The Digit 1 occurs 3 times
Digit 2 occurs -343589435 times
Thanks for any help!
There are ten digits 0-9. So the array count should have ten elements. Also the array need to be initialized.
Either use an array with the size specified by a constant expression and initialize it in a declaration like
#define N 10
//...
int count[N] = { 0 };
Or use a variable length array and initialize it using the function memset declared in the header <string.h>
For example
#include <string.h>
//...
int i = 10;
int count[i];
memset( count, 0, i * sizeof( int ) );
Otherwise if the array is not initialized it will have indeterminate values.

How to fix program printing a 0 after the print statement executes in C?

This program tests Goldbach's Conjecture, printing a given even integer as the sum of two primes. After printing the first one, the given integer is to iterate by 2 , then find the sum of two primes for that integer. And so on until the program is interrupted by the user.
This problem is that the program prints a '0' after every executed print statement.
The code:
#include <stdio.h>
#include <math.h>
int GC(int goldsum); //function prototype
int main()
{
int goldsum;
printf("Enter an even integer greater than 5: ");
scanf("%d", &goldsum);
printf("%d\n", GC(goldsum));
goldsum = goldsum + 2;
printf("%d\n", GC(goldsum));
}
int GC(int goldsum) //function definition
{
int i, j; //prime addends
int div1, div2; //divisors
char prime1, prime2;
for (i=2 ;i<goldsum ;i++) //when number is less than goldsum, run this loop iterating by 1
{
prime1 = 1;
for (div1=2 ;div1<i ;div1++) //this loop determines if "i" is prime.
if (i % div1 == 0) //if yes, the prime number is stored in "i"
prime1 = 0;
if (prime1)
{
for (j=3; j<goldsum; j+=2) //when number is less than goldsum, run this loop iterating by 2
{
prime1 = 1;
for (div2=2; div2<j; div2++) //this loop determines if "j" is prime.
if(j % div2 == 0) //if yes, the prime number is stored in "j"
prime1 = 0;
if (prime1)
if (i + j == goldsum) //If i + j = goldsum, it prints the result.
{
printf("%d + %d = %d\n",i ,j , goldsum);
return 0;
}
}
}
}
return 0;
}
The output:
Enter an even integer greater than 5: 10
3 + 7 = 10
0
5 + 7 = 12
0
What I want it to look like:
Enter an even integer greater than 5: 10
3 + 7 = 10
5 + 7 = 12
use just GC(goldsum);
instead of printf("%d\n", GC(goldsum));
Maybe you misunderstood the return 0; we put in main(). Every function has to return the value we desire. In the case of main we want 0 because that means everything was OK. In the case of your function the return value should be what YOU want from it.
Edit: re-read the question and adding this: Since you don't want a return value from you function you should declare it as void and not have it in a printf() because all the printing you want is in your function.
Void functions do not return a value, so that is what you want.

How to find whether the given array is sorted in descending order in c programming

I need to find out whether the given array is sorted in descending order or not...
I got the output but in portal it shows as Wrong Answer.
This is my code.
#include<stdio.h>
int main()
{
int n,a[15],i,k=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
{ scanf("%d",&a[i]);}
for(i=1;i<=n;i++)
{
if(a[i]<a[i+1])
k++;
}
if(k==0)
printf("yes");
else
printf("no");
return 0;
}
Help me to figure it out...
Arrays are indexed from 0 to size - 1 . So if you have
int array[15];
the elements are a[0] to a[14] . But in your code, you are starting from a[1] to a[15] and might try to access a[15], which is unsafe memory and will cause problems.
So you should first change your for loop.
You should change it to
for( i = 0 ; i < n ; i++ )
{
scanf("%d",&a[i]);
}
for( i = 0 ; i < n - 1 ; i++ )
{
if( a[i] < a[i+1] )
{
k++;
break;
}
}
In the second for loop, you should loop till i < n - 1 because otherwise, in
if(a[i]<a[i+1])
when i = n, you will try to access the n + 1th with element with a[i+1] , which might be out of bounds.
You can also just exit from the loop once you find out that the array is not in descending order to save time.
You must also be certain that a[15] is enough to store all the values ( that is, the number of values given as input should not exceed 15, check the problem statement to ensure this )
you should start array index from 0 in both for loop.
Use this
for(i=0;i<n;i++)
in second for loop you should use
for(i=0;i<n-1;i++) // you need to compare up to second last element with last, so run loop upto `i<n-1`
for example if you enter n = 5 loop will work for 0 to 4
It is good to use break; if value of k increases
for(i=1;i<=n;i++)
{
if(a[i]<a[i+1]){
k++;
break; // if k increments break the loop.
}
}
Here you are.:)
#include <stdio.h>
#define N 15
int main(void)
{
int a[N];
int i, n;
printf( "Enter number of elements in the array (not greater than %d: ", N );
scanf( "%d", &n );
if ( N < n ) n = N;
printf( "Enter %d elements of the array: ", n );
for ( i = 0; i < n; i++ ) scanf( "%d", &a[i] );
i = 0;
while ( i++ < n && !( a[i-1] < a[i] ) );
if ( i == n ) puts( "The array is sorted in the descending order" );
else puts( "The array is not sorted in the descending order" );
return 0;
}
The program output might look like
Enter number of elements in the array (not greater than 15: 15
Enter 15 elements of the array: 10 10 9 9 9 8 7 6 5 5 4 3 2 1 0
The array is sorted in the descending order
As for you code then this loop
for(i=1;i<=n;i++)
{
if(a[i]<a[i+1])
k++;
}
is unsafe because using index i+1 in expression a[i+1] you can access memory beyond the array.
Also you have to check whether the entered value of n is less than 15 that is the size of the array because you use the range of indices [0, n].
And in the first loop the index has to start from 0. Otherwise the first element of the array will not be initialized.
First, you define array a[15]:
int n,a[15],i,k=0;
and you use variable n to control its size
scanf("%d",&n);
for(i=1;i<=n;i++)
{ scanf("%d",&a[i]);}
then you need to keep n <= 15.
p.s., array starts with '1' in Matlab but '0' in C.
I can't agree less about what others have said regarding array indexing, the problem in not knowing whether a[i+1] exists or not, and using of break. I would add though when all the numbers in this input array are equal it will still pass as decreasing in your code. If that is a problem you can add another if statement checking whether at all it decreases anywhere and use another variable say change for checking whether it gets satisfied.
int change = 0;
for(i=0;i<n;i++)
{
if(a[i]<a[i+1])
k++;
if(a[i]>a[i+1])
change++;
}
if(k==0 && change > 1)
printf("yes");
else
printf("no");
Check with the problem statement whether it allows such cases as descending. If it doesn't go with this otherwise its fine.

Prints out the first eight autmorphic numbers

Create a program that prints out the first eight[8] automorphic numbers. Output must be done
in the main() function.
Here's the code I worked on:
#include <stdio.h>
#include <conio.h>
main() {
int automorphic[8];
int n;
printf("\t\t\tAUTOMORPHIC\n\n\n");
for(n=1; n<8; n++ ){
if (n*n%10==n || n*n%100==n || n*n%1000==n);
}
printf("\t%d\n\n", automorphic [n]);
getch();
return 0;
}
I don't get why it only prints out 0? Is there something missing on my code? Or am I not doing the right thing at all?
Because:
You are examining only numbers 1 to 7 (only numbers 1, 5 and 6 in this range are automorphic).
You are not storing the number in the array.
You are printing only element 7 of the array (which is always 0).
You need to expect numbers bigger than that.
Additionally, automorphic numbers start at 0, not 1.
int main() {
long automorphic [8];
long i;
int n;
printf("\t\t\tAUTOMORPHIC\n\n\n");
i= 0 ;
n= 0 ;
while( n < 8 ) {
if( i*i%10==i || i*i%100==i || i*i%1000==i || i*i%10000==i || i*i%100000==i ) {
automorphic[n]= i ;
n++;
}
i++;
}
for(n= 0 ; n < 8 ; n++ ) {
printf("\t%d\n\n", automorphic[n] );
}
getch();
return 0;
}
Result should be:
0
1
5
6
25
76
376
625
You're close, but not quite there.
You are only testing the integers from 1 through 8 for the automorphic property. The question asks for the first 8 automorphic numbers, not which numbers less than 8 are automorphic.
Your if statement doesn't do anything if the condition is true.
You are printing the value of automorphic[n] but do not set any values in the automorphic array. Also, at the point the printf executes, n will be 8 because the for loop has already finished.

Reading an array of integers and printing them out

I'm learning C on my own and doing a few exercises. The following code reads in an
array of integers from the user. The integers are printed out when the user types in a "0" or when the array is filled. Now the problem is the output. When I type in "0" after I have typed in 3 digits e.g. 1 2 3 the output is the following: 1 2 3 -858993460 -858993460. I am not sure why I get the value "-858993460" but I have already found a solution to avoid it. Now my question is what the values mean and if there is a smarter solution than mine which is presented below as comments.
#include <stdio.h>
#include <string.h>
#define arraylength 5
int main ()
{
//const int arraylength = 21; //alternative possibility to declare a constant
int input [arraylength] ;
int temp = 0;
//int imax = 0;
printf("Please type in a your digits: ");
for (int i = 0; i < arraylength; i++)
{
scanf("%d", &temp);
if ( temp !=0)
{
input[i]= temp;
//imax= i;
}
else
{
//imax= i;
break;
}
if (i < arraylength-1)
printf("Next: ");
}
for (int i =0; i < arraylength; i++ ) // switch arraylength with imax
{
printf("%d", input[i]);
}
getchar();
getchar();
getchar();
}
This happens because irrespective of when the 0 input is given you print all 5 numbers:
for (int i =0; i < arraylength; i++ )
To fix this you can print only the number(s) user entered before entering a 0 by running a loop from 0 to i:
for (int j =0; j < i; j++ )
Those 2 numbers are the garbage that was left in the memory locations for the last 2 parts of your array. You never initialise those when you only input 3 numbers, so when you go through and print all 5 elements in the array, it prints whatever garbage was in the memory.
You print all integers in array which is size of arraylength = 5. So you get 5 integers in output. As you didn't initialize array, you get uninitilized values as 4th and 5th elements of array. You can use memset(&input, 0, arraylength*sizeof(int)); to set initials values in array to 0.

Resources