Program using scanf in a loop prints incorrect output - c

I don't know what's happening with this code.
#include<stdio.h>
int main()
{
int ii[5], i;
for (i=1; i<=5; i++)
{
scanf("%d", &ii[i]);
}
printf("----------------------\n");
for(i=1; i<=5; i++)
printf("%d\n", ii[i]);
return 0;
}
After compiling when I provide input as
1 2 3 4 5
then it prints as it is,
but when I provide input in reverse order:
5 4 3 2 1
it keeps on asking up to some more digits and after that it prints out some random digits from given set of input.
How can I fix this?

c uses 0 indexing that means that array indexes start at 0 not 1. A for loop over an array should look like this:
int array[ARRAY_LENGTH], i;
for (i = 0; i < ARRAY_LENGTH; ++i) {
This will ensure that i will go from 0 to ARRAY_LENGTH - 1 and will not go outside the bounds of your array.
These lines:
for(i=1; i<=5; i++)
printf("%d\n", ii[i]);
will Access element 5 of ii where the maximum index is 4. This will cause Undefined Behavior which is likely why you are seeing random numbers appear.

Related

Segmentation fault: 11 in Counting Sort algorithm in C

I have written this code in C that implements the counting sort algorithm. I create an array of 10 elements and then I apply the counting sort. The code is this:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
int my_array[] = {10,10,9,9,6,5,4,3,2,1};
int i;
int N = 10;
//print the array
for (i=0; i<10; i++){
printf("%d\n", my_array[i]);
}
//define the minimum and the maximum as the first element of the array
int min_array=my_array[0];
int max_array=my_array[0];
printf("--------------\n");
//find the minimum and the maximum of the array
for(i=0; i<N; i++){
if(my_array[i]<min_array){
min_array=my_array[i];
}
else if(my_array[i]>max_array){
max_array=my_array[i];
}
}
//check if it worked
printf("max_array %d\n", max_array);
printf("min_array %d\n", min_array);
//
int range_array;
range_array = max_array - min_array +1;
int count_array[range_array+1];
for(i=0; i<range_array;i++)
count_array[i]=0;
int j=0;
for(int i=0; i<10; i++){
count_array[my_array[i]-min_array]=count_array[my_array[i]-min_array]+1;
}
int z = 0;
for(i=min_array; i<max_array; i++){
for(j=0; j<count_array[i-min_array];j++)
z=z+1;
my_array[z]=i;
}
for(i=0; i<N; i++){
printf("%d\n", my_array[i]);
}
}
When I execute it, I have Segmentation fault: 11
I do not know why, but I think it is related to some allocation problem, and in particular I think that the error comes from one of the last for loops before printing the ordered array. Indeed if I put some print check where it stops, the segmentation fault error comes at the end.
EDIT: I fixed count_array[range_array] into count_array[i] in the for loop. But now it seems not working properly:
The output is this:
10 10 9 9 6 5 4 3 2 1
--------------
max_array 10
min_array 1
--------------
1 2 3 4 5 6 9 9 2 1

Copy an array to another while sorting it simultaneously

I have already done the sorting part and the copy but I am really struggling to put it together.
Here is only the sorting part because i am not so familiar with it. My main problem is when I start copying the array it only copies the first 2 number then stops and I think its a small problem in the for loop somewhere but i cant find it.
int main ()
{
int number[30];
int number2[30];
int i, j, a, n;
printf("Enter the value of N\n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The array is copied and sorted like:\n");
for (i = 0; i < n; ++i)
{
printf("%d\n", number[i]);
}
system("Pause");
}
I compiled (MinGW) and ran this exact code and got the following output:
Enter the value of N
10
Enter the numbers
9
1
0
2
8
3
7
5
4
6
The array is copied and sorted like:
9
8
7
6
5
4
3
2
1
0
Press any key to continue . . .
It looks like it is correctly reverse-sorting the input values. Note that this is a fairly common sorting algorithm (https://www.geeksforgeeks.org/bubble-sort/).
Based on this I would argue that the for loop works as is, assuming that you are looking for a reverse sort.
I am not sure what exactly is meant by "copying the array". Array number2 is unused and there are no operations that appear to copy the array number, just operations for loading it, sorting it and printing it.

How do I fix the problem with the incorrect array value in for loop using C language? [duplicate]

This question already has answers here:
How dangerous is it to access an array out of bounds?
(12 answers)
Closed 2 years ago.
I am trying to understand how array boundaries work in C, so tried the following code:
#include <stdio.h>
int main(){
{
int i, s[4], t[4], u=0;
// fisrt loop
for (i=0; i<=4; i++)
{
s[i] =i;
t[i] =i;
printf("s = %d\n", s[i]);
printf("t = %d\n", t[i]);
}
// second loop
printf("s:t\n");
for (i=0; i<=4; i++)
printf("%d:%d\n", s[i], t[i]);
printf("u = %d\n", u);
}
return 0;
}
The output is as follows :
fisrt loop
s = 0
t = 0
s = 1
t = 1
s = 2
t = 2
s = 3
t = 3
s = 4
t = 4
second loop
s:t
4:0
1:1
2:2
3:3
4:4
u = 0
I am expecting both loops to print 5 elements from 0 to 4. As you can see, the first for loop's output looks ok, but in the second loop the value of s[0]
is wrong and for some reason turned to 4.
I am assuming that this is happening because of some problem in the array boundary, but I am not sure, please correct me if I am wrong. Is there any way to fix this, and make s[0] correct value? Cheers.
for (i=0; i <4; i++)
in your code you access 5 elements of the array and your array has only 4 elements. It ans Undefined Behaviour.
Second loop the same error.
There is a problem with the size of the array, you need to modify your code of that line to given code:
int i, s[4], t[4], u=0;
to
int i, s[5], t[5], u=0;
Delete the equals in the for loops:
for (i = 0; i < 4; i++)
The length of the arrays is 4. From 0 to 4 (included) there are 5 positions.
When you declare int s[4]; you create an arrays of lenght 4: s[0], s[1], s[2], s[3]. You can't access s[4].
This is because the position starts to 0.
If you want to have 5 elements for both arrays:
Change the declarations of s and t to s[5] and t[5]. Only at the declaration the 5 means 5 elements. Only at indexing and addressing a certain element, counting starts at 0, not 1.
If you want to have the arrays to be consisted of 4 elements:
for (i = 0; i <= 4; i++)
i <= 4 - With this condition and the initialization i = 0 you access memory beyond the bounds of the array at the last iteration, which invokes undefined behavior.
When i == 4, s[i] and t[i] is an out of bounds access as s and t are both arrays of 4 int, not 5.
It needs to be i < 4 or i <= 3 for the arrays of 4 int or (if you want to) or change the initialization to i = 1.

How to append values to array in C language

given a set of 10 digit number i need to find how many times the index appears in the give number e.g
given 2 2 0 0 0 3 0 0 1 0 as an array element the array index from 0-9 so i have something like
0 1 2 3 4 5 6 7 8 9
2 2 0 0 0 3 0 0 1 0 ---> input
00115558 -----> output
the first index 0 appear twice, the second index 1 appear twice, the third index 0 appear 0 times so it's ignore and so on so the outcome is 00115558 and now i need to rearrange the output such that 0 must not start so i need something like 10015558
i was able to get the initial output like 00115558, but i need to save it into an array so i can loop through the array and check for value greater than 0 and swap the position.
int main() {
int i,j,len;
int array[10],output[10];
printf("Enter 10 digit number separated by space: \n");
for (i = 0; i < 10; i++)
scanf("%d", &array[i]);
len = sizeof(array)/sizeof(array[0]);
for(i=0; i<len; i++)
{
if(array[i] != 0)
{
for(j=0; j<array[i]; j++)
//output[j] = i;
printf("%d ", i);
}
}
I tried to save the output into another array and i printed the array outside the loop to see the content but the result wasn't what i wanted. How can i save my value into the output[] array. thanks for any help
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,len;
int array[10],output[10];
printf("Enter 10 digit number separated by space: \n");
for (i = 0; i < 10; i++)
scanf("%d", &array[i]);
len = sizeof(array)/sizeof(array[0]);
for(i=0; i<len; i++)
{
if(array[i] != 0)
{
for(j=0; j<array[i]; j++)
//output[j] = i;
printf("%d ", i);
}
}
}
Sir, i tried you exact code as above in "Dev c++". I get answer is 00115558. I think your Code is absolute Right. change your IDE software or Update that.

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