last index of array give wrong output in c - arrays

I created a program that search the specific number in array and give it position.
here's the code.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[10], srch, i;
clrscr();
printf("Enter elements of array.\n");
for(i=0;i<10;i++){
scanf("%d", &arr[i]);
}
printf("Enter element to search\n");
scanf("%d", &srch);
for(i=0;i<10;i++){
if(arr[i]==srch){
printf("%d is at position %d", srch, i+1);
break;
}
}
//Below statement run when no such number found in array.
if(srch!=arr[i])
printf("%d", arr[i]);
getch();
}
Well, I can't understand why am i getting this output.
whenever i run this program and entered a value that is in the current array it found its position and give correct answer.
But I have doubt that when i print this array with last value of index which was 10 it give the value of 'srch variable' i don't know why it is giving this as array 10 index.
For example when i enter 11 as value to search which will not be in array
print("%d", arr[i]) // It print value of srch

After coming out the second loop in your code the value of i will be equal to 10. And when the if(srch!=arr[i]) gets read by the compiler, it searches for the arr[10] which has not been allocated by you. So theres a garbage value there at that position. That is being printed by printf("%d", arr[i]);

It's garbage value. You are reaching an index which is not created. Out of bonds. So you get a garbage value. It can be anything.

After the loop i is one past the last element, thus you can't access the array at this index.
You need to handle the fact that the value has been found or not, possibly this way:
int found = 0; // value not found
for (i=0; i<10; i++) {
if (arr[i]==srch) {
printf("%d is at position %d", srch, i+1);
found = 1; // value found
break;
}
}
if (!found) {
//Below statements run when no such number found in array.
}

When No element found then from second for loop value of i will be 10. which is out of the bound of the array. since array will have 0,1,2.....9 index and you are trying to access 10th index, It will have garbage value.
to prevent this issue, you can replace i with i-1
if(srch!=arr[i-1])
printf("%d", arr[i-1]);

Related

Printing arrays elements in reverse order using pointer

I am trying to input an array and then print it in reverse order using for loop. Firstly, I tried to print out the array elements in original order as follows:
#include <stdio.h>
int main()
{
int a[100];
int n,i;
int *p=a;
printf("Enter size of array:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++){
printf("Enter array element [%d]:",i);
scanf("%d",p+i);
}
printf("Array elements in reverse order: ");
for (i=0;i<n;i++){
printf("%d\n",*(p+i));
}
The above code worked and desired output was achieved. And then I tried to output array elements in reverse order using following changes in the last for loop:
for (i=n;i>0;i--){
printf("%d\n",*(p+i));
But doing this the output appears as below:
while the desired output is:
3
2
1
What am I missing?
In your first attempt, the indices range from 0 to n-1 which is correct. In your second attempt the indices range from n to 1, so you read and write one element past the end of the array.
The proper initialization and condition is:
for (i=n-1;i>=0;i--){
You iterate from p+3 (array[3]), while max index is 2 -> undefined behavior, garbage printed
You iterate until p+0, excluded, you exclude array[0].
for (i = n - 1; i >= 0; i--) {
//...
}

Error: Stack around the variable "m" is corrupted

Im trying to make a program which says how many times a specific digit appears on a 100 numbers sequence.
Meanwhile I got this error and I can´t understand what is the solution to this. I´d appreciate if you could get me some tip or the solution.
#include <stdio.h>
int main() {
int i, m, digit, val[99], count=0;
printf("Enter a number:");
scanf("%d", &val[0]);
while (val[0] < 0) {
printf("Enter a number:");
scanf("%d", &val[0]);
}
for (i=1;i<101;i++) {
val[i]=val[0]++;
printf("%d\n", val[i]);
}
printf("Enter a digit:");
scanf("%d", &m);
while (m<0||m>9) {
printf("Enter a digit:");
scanf("%d", &m);
}
do {
digit=val[i]%10;
val[i]=val[i]/10;
if (digit==m) {
count++;
}
}while (val[i]>0);
printf("The digit %d is printed %d times in this sequence.", m, count);
}
In the for loop you step outside of the array val of which the last index is 98. Instead of hard-coding the length of the array in several places it is more convenient to use a length macro, like this:
#define LEN(anArray) (sizeof (anArray) / sizeof (anArray)[0])
...
for (i = 1; i < LEN(val); i++) {
...
Also, in the do-while loop the index i is outside of the array bounds of val. You also need to check the return value of scanf to make sure the input is valid. The last printf statement also needs a trailing newline.
Edit: Note that LEN only handles "real" arrays; arrays passed to functions are received as pointers.
You allocated only int /* ... */ val[99] (only val[0] to val[98] are available) and accessed upto val[100] because the loop condition is i<101.
This will lead to dangerous out-of-range write (undefined behaior).
Allocate enough elements like int /* ... */ val[101] or fix the loop condition not to cause out-of-range access.
Also you didn't set value of i after the for (i=1;i<101;i++) loop, so value of uninitialized element will be used in the do ... while loop. Values of uninitialized elements of non-static local variables are indeterminate and using the value invokes undefned behavior.
Set i to proper value before the loop or change the indice i to proper thing.

How to add the first number and last number of a series of number in C?

I am a beginner to C language and also computer programming. I have been trying to solve small problems to build up my skills. Recently, I am trying to solve a problem that says to take input that will decide the number of series it will have, and add the first and last number of a series. My code is not working and I have tried for hours. Can anyone help me solve it?
Here is what I have tried so far.
#include<stdio.h>
int main()
{
int a[4];
int x, y, z, num;
scanf("%d", &num);
for (x = 1; x <= num; x++) {
scanf("%d", &a[x]);
int add = a[0] + a[4];
printf("%d\n", a[x]);
}
return 0;
}
From from your description it seems clear that you should not care for the numbers in between the first and the last.
Since you want to only add the first and the last you should start by saving the first once you get it from input and then wait for the last number. This means that you don't need an array to save the rest of the numbers since you are not going to use them anyway.
We can make this work even without knowing the length of the series but since it is provided we are going to use it.
#include<stdio.h>
int main()
{
int first, last, num, x = 0;
scanf("%d", &num);
scanf("%d", &first);
last = first; //for the case of num=1
for (x = 1; x < num; x++) {
scanf("%d", &last);
}
int add = first + last;
printf("%d\n", add);
return 0;
}
What happens here is that after we read the value from num we immediately scan for the first number. Afterwards, we scan from the remaining num-1 numbers (notice how the for loop runs from 1 to num-1).
In each iteration we overwrite the "last" number we read and when the for loop finishes that last one in the series will actually be the last we read.
So with this input:
4 1 5 5 1
we get output:
2
Some notes: Notice how I have added a last = first after reading the first number. This is because in the case that num is 1 the for loop will never iterate (and even if it did there wouldn't be anything to read). For this reason, in the case that num is 1 it is reasonably assumed that the first number is also the last.
Also, I noticed some misconceptions on your code:
Remember that arrays in C start at 0 and not 1. So an array declared a[4] has positions a[0], a[1], a[2] and a[3]. Accessing a[4], if it works, will result in undefined behavior (eg. adding a number not in the input).
Worth noting (as pointed in a comment), is the fact that you declare your array for size 4 from the start, so you'll end up pretending the input is 4 numbers regardless of what it actually is. This would make sense only if you already knew the input size would be 4. Since you don't, you should declare it after you read the size.
Moreover, some you tried to add the result inside the for loop. That means you tried to add a[0]+a[3] to your result 4 times, 3 before you read a[3] and one after you read it. The correct way here is of course to try the addition after completing the input for loop (as has been pointed out in the comments).
I kinda get what you mean, and here is my atttempt at doing the task, according to the requirement. Hope this helps:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first, last, num, x=0;
int add=0;
printf("What is the num value?\n");//num value asked (basically the
index value)
scanf("%d", &num);//value for num is stored
printf("What is the first number?\n");
scanf("%d", &first);
if (num==1)
{
last=first;
}
else
{
for (x=1;x<num;x++)
{
printf("Enter number %d in the sequence:\n", x);
scanf("%d", &last);
}
add=(first+last);
printf("Sum of numbers equals:%d\n", add);
}
return 0;
}

return statement in c ??? why this function always returning 20?

int akki(int arr[],int m,int n){
int i;
for(i=0;i<m;i++){
if(arr[i]==n)
return i;
}
return 20;
}
void main(){
int i,m,n,arr[10],a;
printf("Enter size of array:");
scanf("%d",&m);
printf("Enter %d elements of array:",m);
for(i=0;i<m;i++){
scanf("%d",arr[i]);
}
printf("Enter element to be searched:");
scanf("%d",&n);
a=akki(arr,m,n);
if(a!=20)
printf("Element found at %d position",a+1);
else
printf("Element not found");
}
IT is Returning 20 or some garbage value..even if condition matches... it is returning value of i.It is linear search function where m is size of array arr and n is element to be searched...
please explain in detail..i am new in c language
thankzzz in advance
You have a problem in your code. Change
scanf("%d",arr[i]);
To
scanf("%d",&arr[i]);
This is done because scanf expects an argument of type int* but you provide argument arr[i] which is of type int. Also add a check that ends the program if user inputs a number which is greater than 10 for the first scanf.
There can be two reasons.
Case 1 [Much likely for _always_]
Simple. Because your if(arr[i]==n) condition is not met, and i<m became false. It came out of for() loop and hence, return 20.
case 2 [Less likely for _always_]
By chance, the value of n is present at the 21st location [index 20] in the input array.
Apart from the coding aspect, did you understand what's the logical purpose of this function? If not, begin with that. It searches for a specific value in an array of given length, and if no element of the array matches that value, it returns 20.
Now analyze your case, based on your input.
EDIT:
After seeing the complete code, as Mr. CoolGuy has pointed out, use
scanf("%d",&arr[i]);
Just for more reference, you can look at Chapter 7.19.6.2, paragraph 12 , %d format specifier, which goes like
... The corresponding argument shall be a pointer to signed integer.
In your code, arr[i] is of type int. What you need is a int *, i.e., &arr[i].

deleting doubles in a sorted array and then puttting X in the end

Here's the problem I've been trying to tackle for a few days.
I need to write a program that gets a sorted array. The program will put 999 where two adjacent blocks have the same value, and then put all the 999 in the end of the array. I need to do this without using another array and the program must be O(n).
example input:
50,60,60,72,81,81,81,81,93,93
desired output:
50,60,72,81,93,999,999,999,999,999
another example:
1,1,2,3,4,4,5,6,6
desired output:
1,2,3,4,5,6,999,999,999
my code. It's not working. For the first example the output is alright. for the second example i get 1,2,3,4,5,4,5,6,-14568127 (out of array bounds)
my algorithm is i walk through the array with two indexes, i and j, if a[i]!=a[i+1] then i advance i. if they are equal, j looks for the next unique value, and puts it in a[i+1].
I'd love to hear better ideas or a code to do this. in C.
while((j!=size-1)&&(a[size-1]!=a[i]))
{
if(a[i]!=a[i+1])
{
i++;
j=i;
}
if(a[i]==a[i+1])
{
j=i;
while(a[i]==a[j])
j++;
a[i+1]=a[j];
i++;
if(j!=size-1)
j=i;
}
}
i++
for(;i<size;i++)
a[i]=999;
I've edited the code, now I do it as chen suggested. First i iterate through the array putting 999 where the doubles are, problem arises when I want to switch though. here's the code I wrote for re-sorting the array:
each time i put a 999 somewhere, count++.
It's working for the two examples I gave perfectly. Thanks everyone.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
int *a;
int i=0,j=0,size,count=0;
printf("Enter the size of the array\n");
scanf("%d", &size);
a=(int *)calloc(size,sizeof(int));
printf("Enter %d numbers\n",size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
printf("The array recieved is :\n");
for(i=0;i<size;i++)
printf(" %d ", a[i]);
i=0;
printf("\n");
for(i=0;i<size;i++)
{
if(a[i]==a[i+1])
{
j=i+1;
while(a[i]==a[j])
{
a[j]=999;
j++;
}
count++;
}
}
while(count!=0)
{
for(i=0;i<size-1;i++)
{
j=i;
if(a[j]==999)
{
a[j]=a[j+1];
a[j+1]=999;
}
}
count--;
}
printf("The new array is: \n");
for(i=0;i<size;i++)
printf(" %d ",a[i]);
free(a);
getch();
}
Here's a general approach that runs in O(n):
Assumption: The input array does not contain 999 (It's fine if it does, you just have to use a different sentinel value):
Iterate through the array once:
For each element, look ahead to the next one
If it's a duplicate to the current element, change it to 999
Keep looking ahead and marking duplicates as 999 until you hit a different element.
You want all the 999's at the end, so now, keep 2 separate pointers:
An index X to keep track of where the first 999 is in the array
Another index num to keep track of where we are in the swapping process
Iterate through the array again, swap all the valid numbers with 999 using these two pointers.
This might sound confusing, so here's a pseudo animation using one of your examples:
(Using W as the sentinel in place of '999` for readability)
1,1,2,3,4,4,5,6,6,
1,W,2,3,4,4,5,6,6,
1,W,2,3,4,W,5,6,6,
1,W,2,3,4,W,5,6,W,
1,2,W,3,4,W,5,6,W,
1,2,3,W,4,W,5,6,W,
1,2,3,4,W,W,5,6,W,
1,2,3,4,5,W,W,6,W,
1,2,3,4,5,6,W,W,W,
And again, but labeling the W with numerical suffix this time so you can see which swaps are happening:
1,1,2,3,4,4,5,6,6,
1,W1,2,3,4,4,5,6,6,
1,W1,2,3,4,W2,5,6,6,
1,W1,2,3,4,W2,5,6,W3,
1,2,W1,3,4,W2,5,6,W3,
1,2,3,W1,4,W2,5,6,W3,
1,2,3,4,W1,W2,5,6,W3,
1,2,3,4,5,W2,W1,6,W3,
1,2,3,4,5,6,W1,W2,W3,
Assuming this is for a school exercise, and you are not working for Google and need to remove duplicates of locations in a world map, your algorithm sounds about right.
For VERY large number of potential dublicates, and also assuming the list is sorted, you could use a method based on a search for the nearest larger elemnt, and then by measuring the distance between two elements, you may find that more effecient.
Easiest way to do this is to remove duplicates first, then fill the rest of the array with 999.
Removing duplicates is O(n), and filling an array is O(n).

Categories

Resources