Reversing array elements in C programming - c

I am new to C and I have a problem. I need to reverse the elements of arrays in the following program. Can I get a very simple explanation of what I am doing wrong and how I could go on about fixing it?
Here's the output I get:
Enter number 0: 0
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
Enter number 6: 6
Enter number 7: 7
Element 0 is: 7
Element 1 is: 6
Element 2 is: 5
Element 3 is: 4
Element 4 is: 4
Element 5 is: 5
Element 6 is: 6
Element 7 is: 7
My code:
#include <stdio.h>
void reverse(int a[], int i)
{
int j=7,b;
for (i=0; i<=7; i++)
{
b=a[i];
a[i]=a[j];
a[j]=b;
printf("Element %d is: %d\n", i,a[i]);
j--;
}
}
int main(void)
{
int a[8];
int i;
for(i=0;i<=7;i++)
{
printf("Enter number %d: ",i);
scanf("%d", &a[i]);
}
reverse(a, 8);
return 0;
}

To avoid being misled, write the output after the reversal, not during it:
#include <stdio.h>
void reverse(int a[], int i)
{
int j = 7, b;
for (i = 0; i <= 7; i++)
{
b = a[i];
a[i] = a[j];
a[j] = b;
j--;
}
}
int main(void)
{
int a[8];
int i;
for (i = 0; i <= 7; i++)
{
printf("Enter number %d: ",i);
scanf("%d", &a[i]);
}
reverse(a, 8);
for (i = 0; i <= 7; i++)
{
printf("Element %d is: %d\n", i, a[i]);
}
return 0;
}
Now you’ll notice the array isn’t changing at all. That’s because you’re swapping every element in the array twice: once to its reversed position, then back to its original position. To fix this, only loop over the first half the array, i.e. while i < 4.
It was probably also intended to make the second argument to reverse the length, so you should make use of that instead of hard-coding 7 or 4:
void reverse(int a[], int length)
{
int i, j = length - 1, b;
for (i = 0; i < length / 2; i++)
{
b = a[i];
a[i] = a[j];
a[j] = b;
j--;
}
}

You could also copy over the array in a new one:
#include <stdio.h>
void reverse(int a[], int i)
{
int b[i];
int j;
for(j=0; j<i; j++){
b[j] = a[i-1-j];
printf("Element %d is: %d\n", j, b[j]);
}
}
int main(void)
{
int a[8];
int i;
for(i=0;i<=7;i++)
{
printf("Enter number %d: ",i);
scanf("%d", &a[i]);
}
reverse(a, 8);
return 0;
}

What you want to do it move through only half of the length of your array else you're reversing the array twice.
void reverse(int a[], int len)
{
int i;
int j=len-1,b;
for(i=0;i<len/2;i++)
{
b=a[i];
a[i]=a[j];
a[j]=b;
j--;
}
for(i = 0; i < len; i++) {
printf("Element %d is: %d\n", i,a[i]);
}
}

The Principe is simple. just stand at the middle of the table and reverse the elements as follow. so pose n is lent of the table. then the last element is n-1.
so you ave to reverse position t[0] and t[n-2]
reverse t[1] and t[n-3] and so on...
stop when you rich the middle of the table. try to code your self is better than for me giving you the code.
hope it helped.

Related

Program to find prime numbers from the set of numbers of Fibonacci series in C

I want to find prime numbers from the Fibonacci series after printing them. First, I implemented the code for Fibonacci then added each element into an array. Then passed the array to a method to check for prime. Wanted to try it with an array. Displaying the series but not the prime numbers from the following code.
#include <stdio.h>
int fib()
{
int a=0,b=1, arr[20];
arr[0] = a;
arr[1] = b;
printf("%d, %d,",a, b );
int c=0;
for(int i=2; i<=20; i++)
{
c=a+b;
arr[i] = c;
printf("%d,",c);
a=b;
b=c;
}
checkPrime(arr);
}
void checkPrime(int a[])
{
int i, count;
for(i=0; i<sizeof(a); i++)
{
count=0;
for(int j=2; j<=a[i]/2 ; j++)
{
if(a[i]%2==0)
count++;
}
if(count>1)
printf("%d is a Prime", a[i]);
}
}
int main()
{
fib();
}
Output of the code
0, 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,
8 is a Prime
You have certain bugs in your implementation.
In fib function you iterate until i <= 20 but your arr have length 20 therefore your loop will go out of bounds of array. You should iterate until i < 20 or increase length of your array.
In checkPrime function you iterate until i < sizeof(a). But sizeof function doesn't return size of your array. It returns size of type of variable that you pass to it therefore it will return sizeof(int*) which = 8 (in case you 64 bit machine but I guess you have). To fix this bug you should pass length of your array in checkPrime function and use it.
You don't reset the count variable after j loop.
checkPrime function doesn't check if the number is prime. You have wrong expression in your nested loop. To check if number N is prime you should check if there any divisor of N that at least less than sqrt(N). Your expression is wrong.
Considering the adjustments above I suggest the next solution:
void checkPrime(int a[], size_t a_len) {
int i, count;
for (i = 1; i < a_len; i++) {
count = 0;
for (int j = 2; j <= sqrt((double)a[i]); j++) {
if (a[i] % j == 0) {
count++;
break;
}
}
if (count == 0) {
printf("%d is a Prime\n", a[i]);
} else {
count = 0;
}
}
}
int fib() {
size_t arr_size = 21;
int a = 0, b = 1, arr[arr_size];
arr[0] = a;
arr[1] = b;
printf("%d, %d, ", a, b);
int c = 0;
for (int i = 2; i < arr_size; i++) {
c = a + b;
arr[i] = c;
if (i == arr_size - 1)
printf("%d ", c);
else
printf("%d, ", c);
a = b;
b = c;
}
printf("\n");
checkPrime(arr, arr_size);
}

Couldn't get the reason for the fault in the code

This is a program to print the smallest value and its position in an array (defined by user).
#include <stdio.h>
int position_smallest(int a[],int n)
{
int smallest = a[0];
int i,k;
for(i=0; i<=n-1; i=i+1)
{
if(a[i]<a[0])
{
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main()
{
int n,j;
int a[n];
printf("Enter the size of the array: ");
scanf("%d", &n);
for(j=0; j<=n; j=j+1)
{
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
But upon running it, it shows following error:
Segmentation fault (core dumped)
What can be the possible reason(s) for it?
First error, as stated in one of the comments, is declaring an array of size n before even knowing how much n is.
Second mistake is for loop in your main function that goes from 0 to n, i.e. index of an array is out of bounds.
Try this:
int main() {
int n = 0, j = 0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
for (j = 0; j < n; j++) {
printf("a[%d] = ", j + 1);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
If this solved your problem, please mark it.
First of all:
int n, j;
both uninitialized. Initialize them otherwise you will get garbage values.
int n = 0, j = 0;
What happens if n by chance (very likely) is 0 in following line?
int a[n];
You allocate 0 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);
You will get segmentation fault in for() loop below because your loop is trying to put 10 elements where you allocated no memory at all.
What happens if uninitialized n by chance (very likely) is 2^32 * 4 bytes (ints max)?
int a[n];
You allocate 2^32 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);
You will not get segmentation fault but you will allocate 2^32 * 4 bytes of memory for your program and you will use only 10
Second if that is not enough:
for (j = 0; j <= n; ++j)
scanf("%d", arr[n];
will access 11th element of array which is undefined behavior, and you might even get segmentation fault there. As you know arrays in C arrays are indexed from 0 to n - 1 (if n is size of array).
Third your loop inside function:
for(i=0; i<=n-1; i=i+1)
is the same as:
for(i=0; i < n; ++i)
And finally, you have a bug in your code, I believe:
if(a[i]<a[0])
should be:
if (a[i] < smallest)
because it is most likely that you would like compare other number to already smallest element not to a[0]. Here is my code
#include <stdio.h>
int position_smallest(int a[],int n) {
int smallest = a[0];
int i = 0, k=0;
for(i=0; i<n; ++i) {
if(a[i]<smallest) {
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main() {
int n=0, j=0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
for(j=0; j<n; ++j) {
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
return 0;
}
The version above is legit for C99 and up standards. If you are using C89 and earlier compilers you are stack with fixed size as mentioned in #Saurabh's answer or preferably use malloc().
Here is malloc() version:
#include <stdio.h>
#include <stdlib.h>
int position_smallest(int a[],int n) {
int smallest = a[0];
int i=0,k=0;
for(i=0; i<=n-1; i=i+1) {
if(a[i]<smallest) {
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main() {
int n=0, j=0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int *a = malloc(sizeof(int) * n);
for(j=0; j<n; j=j+1) {
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
return 0;
}
Use this one:
#include <stdio.h>
int position_smallest(int a[],int n)
{
int smallest = a[0];
int i,k;
for(i=0; i<=n-1; i=i+1)
{
if(a[i]<a[0])
{
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main()
{
int n,j;
int a[100];
printf("Enter the size of the array: ");
scanf("%d", &n);
for(j=0; j<n; j=j+1)
{
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
Specify the size of the array anything but run the loop according to user's input.
And there is some problems in your function position_smallest. So if you want correct it then take a look at #Gox's answer.

How do I shift an array in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
so I am trying to do a couple of things. First I want to shift the array based on the user input. So let's say the user enters (in this order): 1, 2, 3, 4, 5. I want to shift it so that it becomes 2, 3, 4, 5, 1.
As you can see, this particular array is scalable, i.e the dimensions aren't fixed.
#include <stdio.h>
void arrayShift(int *a, int intLength);
int main() {
int arr[10] = {0}; //array for input numbers
int array = 0;
printf("Enter the size of the array (MAX): ");
scanf("%d", &array);
printf("Now please enter your %d values: \n", array);
int i;
for (i = 0; i < array; i++) {
scanf("%d", arr+i);
}
return 0;
}
Then I want to print out the and then create a function that multiplies each number by the one before it (after shifting it): so using the same numbers as before (2, 3, 4, 5, 1), we should get an output of 2, 6, 12, 20, 5.
It seems this could be done simply. For the described 'rotation' we can just copy the first element to after the last, change the starting index and call it rotated without moving all the data. And other simplifications:
#include <stdio.h>
int main() {
int number_elements;
printf("Enter the size of the array (MAX): ");
(void) scanf("%d", &number_elements); // should test return value in case of bad input
int array[number_elements + 1]; // array for input numbers (over allocate by 1 for rotation)
printf("Now please enter your %d values:\n", number_elements);
for (int i = 0; i < number_elements; i++)
{
(void) scanf("%d", array + i); // ditto re return value
}
array[number_elements] = array[0]; // rotated array now starts at 1
for (int i = 1; i <= number_elements; i++)
{
printf("%d ", array[i]); // print the rotated array
array[i - 1] *= array[i]; // multiply the rotated array
}
putchar('\n');
for (int i = 0; i < number_elements; i++) // multiplied array starts at 0 again
{
printf("%d ", array[i]); // printing the multiplied, rotated array
}
putchar('\n');
return 0;
}
USAGE
% ./a.out
Enter the size of the array (MAX): 5
Now please enter your 5 values:
1 2 3 4 5
2 3 4 5 1
2 6 12 20 5
%
I'm not sure your text and your example agree with one another so this is my assumption of what you want but it can be tweaked as needed.
Hope this helps..
#include <stdio.h>
void arrayRotate(int a[], int intLength)
{
int temp = a[0],t,i; // storing the first element in a temporary variable
for(i=1;i<intLength;i++)
a[i-1] = a[i]; // Left shifting the elements starting from index 1
a[i-1] = temp; // In the last the first index element is restored back
}
void multArr(int a[],int b[],int n)
{
int i;
b[0] = a[0]; // copying the value at index 0 to the new array
for(i=1;i<n;i++)
{
b[i] = a[i]*a[i-1]; // performing the multiplication on the new array
} // referencing the values from the old array
}
int main() {
int arr[10] = {0}, cpy[10]; //array for input numbers
int array = 0;
printf("Enter the size of the array (MAX): ");
scanf("%d", &array);
printf("Now please enter your %d values: \n", array);
int i;
for (i = 0; i < array; i++)
{
scanf("%d", arr+i);
}
arrayRotate(arr,array); // calling function for rotating
multArr(arr,cpy,array); // calling function for the multiplication stuff
for (i = 0; i < array; i++) // printing the rotated array
{
printf("%d ", arr[i]);
}
printf("\n");
for (i = 0; i < array; i++) // printing the multiplied array
{
printf("%d ", cpy[i]);
}
return 0;
}
Alright so here's what I've got so far. It's kind of working but it's also not. Specifically, the problem is when I run it, it prints 6, 12, 20, 5 1, and not 2, 6, 12, 20, 5 (this is assuming the numbers of the array are 1, 2, 3, 4, 5)
#include <stdio.h>
void shift (int arr[], int num);
void multiply (int arr[], int num);
int main() {
int arr[10] = {0}; //array for input numbers
int array = 0;
printf("Enter the size of the array (MAX): ");
scanf("%d", &array);
printf("Now please enter your %d values: \n", array);
int i;
for (i = 0; i < array; i++) {
scanf("%d", arr+i);
}
shift(arr, array);
return 0;
}
//shift function
void shift (int arr[], int num) {
int tempVar; //temporary variable
int i;
tempVar = arr[0]; //setting the temporary variable to the first element of a
for (i = 0; i < num -1; i++) {
arr[i] = arr[i +1];
printf(" %d ", arr[i]);
arr[i -1] *= arr[i];
} //arr[0] = tempVar * arr[0];
arr[i] = tempVar; //i < num, print(arr[i])
printf("%d \n", arr[i]);
for ( int i = 0; i < num; i++) {
printf(" %d ", arr[i]);
}
printf("\n");
}

How to delete duplicated values in array in C?

I want to delete duplicates values in array. For example: array[1,5,6,1,3,5,9] I want to have array[6,3,9].
I have written this, but I am having troubles:
#include<stdio.h>
main() {
int array[50], i, j, k=0, c=0, array2[50], n;
printf("Enter array dimension: "); scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("array[%d]= ", i); scanf("%d", &array[i]);
}
for (i = 0; i < n; ) {
for (j = i + 1; j < n; j++) {
if (array[i] == array[j])
i++;
else {
array2[k++] = array[i];
c++;
}
}
}
for (k = 0; k < c; k++) {
printf("%d ", array2[k]);
}
system("pause");
}
You should start by describing your problem in pseudo code, and breaking it into smaller pieces.
Start from scratch by deleting all these redundant variables, and try to implement the following algorithm:
for each element in inputArray
if not elementIsDuplicate(element)
add to outputArray
That's a single for loop. The elementIsDuplicate is separate function.
Now try to implement the function elementIsDuplicate. This function also contains a single loop, takes input parameters (int* array, int n, int currentIdx) and returns 1 or 0 indicating whether the element at currentIdx occurs anywhere else in the array.
#include<stdio.h>
int main(){
int array[50], i, j, k=0, c, n, array2[50] = {0};
printf("Enter array dimension: "); scanf("%d", &n);
for (i = 0; i < n; ++i){
int num, dup = 0;
printf("array[%d]= ", i); scanf("%d", &num);
for(j = 0; j < k; ++j){
if(array[j] == num){
array2[j] = dup = 1;
break;
}
}
if(!dup){
array[k++] = num;
}
}
for (c=i=0; i < k; ++i){
if(!array2[i])
printf("%d ", array[c++] = array[i]);
}
printf("\n");
/*
for(i=0;i<c;++i)
printf("%d ", array[i]);
printf("\n");
*/
system("pause");
return 0;
}
#include<stdio.h>
main()
{
int n, a[50], b[50], count = 0, c, d;
printf("Enter number of elements in array\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for(c=0;c<n;c++)
scanf("%d",&a[c]); //enter array elements
for(c=0;c<n;c++)
{
for(d=0;d<count;d++)
{
if(a[c]==b[d])
break;
}
if(d==count)
{
b[count] = a[c];
count++;
}
}
printf("count is: %d\n",count);
printf("Array obtained after removing duplicate elements\n");
for(c=0;c<count;c++)
printf("%d\n",b[c]);
return 0;
}
This will remove multiple duplicates from the desired array..
Example: if the input array is: 3 6 5 6 2 8 6 5 9 8 6 ,,then the output array will be: 3 6 5 2 8 9

Error in function for Selection-Sort

My code for selection-sort
#include <stdio.h>
void selection_sort(int a[], int n);
int main()
{
int size;
printf("Enter the size of array: ");
scanf("%d",&size);
int b[size],i = 0;
printf("Enter %d integers to be sorted: ",size);
while(i++ < size)
scanf("%d",&b[i]);
selection_sort(b, size);
printf("Sorted integers(by selection sort) are: ");
for(int i = 0; i < size; i++)
printf("%d",b[i]);
return 0;
}
void selection_sort(int a[], int n)
{
while(n >= 0 )
{
if(n == 0)
break;
else
{
int i = 0, c = 0;
int largest = a[0];
while(i++ < n)
if(largest < a[i])
{
c = i ;
largest = a[i];
}
int temp = a[--n];
a[n] = largest;
a[c] = temp;
selection_sort(a, n);
}
}
}
on sorting the array in ascending order
3 4 1 2
is giving weird output
2293388 4 3 0
I checked this many time but failed to remove the problem.
What should I do to work it properly?
Algorithm used :
1. search for largest element in the array.
2. Move largest element to the last position of array.
3. Call itself recursively to sort the first n -1 element of the array.
Please don't give any other solution otherwise I will get confused.
EDIT
Ah, I see what goes wrong. First of all, while (i++ < n) does not do exactly what you expect it to do. It checks if the condition i < n is true, then it increments i. However, it seems that after the conditional check, i is already incremented in the body. So for example,
while (i++ < n)
printf ("%d ", i);
will print out (with n=4):
1 2 3 4
So you first need to change that. Secondly, the outer while-loop is not at all necessary. Using one loop will suffice. Again, change the while loop in here to while (i < n) and increment i in the body. SO the final code will be:
#include <stdio.h>
void selection_sort(int a[], int n);
int main()
{
int size;
printf("Enter the size of array: ");
scanf("%d", &size);
int b[size], i = 0;
printf("Enter %d integers to be sorted: ", size);
while(i < size) {
scanf("%d", &b[i]);
i++;
}
selection_sort(b, size);
printf("Sorted integers(by selection sort) are: ");
i = 0;
for(i = 0; i < size; i++)
printf("%d ", b[i]);
printf ("\n");
return 0;
}
void selection_sort(int a[], int n)
{
if(n == 0)
return;
else
{
int i = 0, c = 0;
int largest = a[0];
while(i < n) {
if(largest < a[i])
{
c = i;
largest = a[i];
}
i++;
}
int temp = a[--n];
a[n] = a[c];
a[c] = temp;
selection_sort(a, n);
}
}
I tested this with your given input (3 4 1 2) and it prints out a sorted list: 1 2 3 4.
Whenever you see such weird big numbers, its usually an array out of bounds issue. Please take a small data-set, say 5-6 numbers, and walk through your program. I am sure you can fix it. Good luck!!

Resources