Moving the elements of an array - c

I'm trying to make a program that moves the elements of an array from right to left and then prints them, but the only thing that the program prints is the last value: why?
int main (){
int n = 5;
int array[n];
int i = 0;
int temp = 0;
while (i < n) {
printf("Insert the values\n");
scanf("%d", &array[i]);
i++;
}
i = 0;
temp = array[i];
i = n-1;
while (i > 0) {
i--;
array[i] = array[i+1];
}
i = 0;
while (i < n) {
printf("%d\n", array[i]);
i++;
}
return 0;
}
Example of input and expected output:
Input: 1,2,3,4,5
Output: 2,3,4,5,1

In the loop
i = n-1;
while (i > 0) {
i--;
array[i] = array[i+1];
}
The value of the last element is written to the second last element, and after that the value of the second last element (now the value of the last element) is written to the third last element. The other elements will also get the value of the last element like this.
The order of process should be reversed like this:
i = 0;
while (i+1 < n) {
array[i] = array[i+1];
i++;
}

Step through your code. You start off with the last element, and copy it to the second to the last element. Say the elements are {1, 2, 3, 4, 5}. This means that array[3] before you enter the loop is 4, but after the first iteration, is 5 (array[i] (4)] = array[i+1 (5)] (5)). Then you move down to array[2], and set it to array[3], which is now five. This repeats for the whole array, until all elements contain 5 (the last value). By the way you aren't even using temp, did you intend to do something with it and forget?

You have to preserve the first element of the array (array [0]) in a temp variable then shift the array elements from 0 to n-2, then you will have to insert the first element (array [0]) at the index of last element array [n-1]
#include <stdio.h>
#include <stdlib.h>
int main (){
int n = 5;
int array[n];
int i = 0;
while (i < n) {
printf("Insert the value :");
scanf("%d", &array[i]);
i++;
}
int temp = array[0];
i = 0;
while (i < n-1) {
array[i] = array[i+1];
i++;
}
array[n-1]=temp;
printf("\n\n");
i = 0;
while (i < n) {
printf("%d\n", array[i]);
i++;
}
return 0;
}

When you want to move elements to the left, you must first put i in the temporary variable because the value of this variable must remain to move to the previous elements.
i = n-1;
while (i >1) {
temp = array[i-1];
array[i-2] = temp;
array[i-1] = array[i];
i--;
}

Related

How do I return a recursive function with an array of ints as argument?

I'm a beginner in programing so please be understanding with my code.. I'm working on a problem set where I have to implement a selection sort using recursion. I feel like it should work but I get an error message and i can't figure out why.
the problem set consists in that I use a recursive function where i have to look for the largest number in an array, store it in the last position and sort the entire array using this method.
int array[n];
printf ("enter numbers: ");
for (i = 0; i < n; i++)
{
scanf ("%i", &array[i]);
}
selection_sort(n, array);
printf ("sorted numbers: ");
for (i = 0; i < n; i++)
{
printf ("%i", array[i]);
}
return 0;
here is the recursive function that i'd like to implement.
i used curpos to store the position of the largest number,
lastpos to store the location of the last element in the array,
and a tmp variable to store the largest number.
and this is the error message that i get.
.c:67:34: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'int *'; take the address with & [-Werror,-Wint-conversion]
return selection_sort(n, array[n-1]);
^~~~~~~~~~
&
if (n <= 0)
{
return 1;
}
else
{
for (i = 0; i < n; i++)
{
if (tmp <= array[i]) //look for the largest number and update it into tmp
{
tmp = array[i];
curpos = array[i]; //remember the location of the current largestnumber
}
}
lastpos = array[n-1]; // save the last element into a variable before swap
array[n-1] = tmp; // put the largest number into the last element
curpos = lastpos; // put the last element before swap into the changed location.
return selection_sort(n, array[n-1]);
}
}
I hope you can give me a hand to understand the recursion better. thank you so much in advance.
The return value is a red herring. You don't use it so your function may as well be void.
if (n <= 0)
{
return 1;
}
The second thing to notice is that you can't pass an array to a function. You are passing a pointer to the beginning of the array. This is good, because otherwise you wouldn't be able to sort it.
else
{
for (i = 0; i < n; i++)
{
Right here is an issue. You haven't initialised tmp and curpos. You need to do that before the loop.
if (tmp <= array[i]) //look for the largest number and update it into tmp
{
tmp = array[i];
curpos = array[i]; //remember the location of the current largestnumber
}
}
lastpos = array[n-1]; // save the last element into a variable before swap
array[n-1] = tmp; // put the largest number into the last element
curpos = lastpos; // put the last element before swap into the changed location.
Finally, right here you have the right idea, but the wrong notation. You want to pass the same array, but 1 less element
return selection_sort(n, array[n-1]);
Should be:
return selection_sort(n-1, array);
}
The error message means that in this call
return selection_sort(n, array[n-1]);
you are passing an element of the array of the type int with the index n-1. But the function expects a pointer of the type int *.
Moreover the value of the first parameter is always the same and equal to n.
Also the return type of the function does not make a sense. The function should be declared with the return type void.
Also you need to swap two elements if within the array there is found an element that is greater than the last element.
The function can be declared and defined the following way
void selection_sort( int a[], size_t n )
{
if (!( n < 2 ))
{
size_t i = --n;
for (size_t j = n; j-- != 0; )
{
if (a[i] < a[j]) i = j;
}
if (i != n)
{
int tmp = a[i];
a[i] = a[n];
a[n] = tmp;
}
selection_sort( a, n );
}
}
Here is a demonstration program.
#include <stdio.h>
void selection_sort( int a[], size_t n )
{
if (!( n < 2 ))
{
size_t i = --n;
for (size_t j = n; j-- != 0; )
{
if (a[i] < a[j]) i = j;
}
if (i != n)
{
int tmp = a[i];
a[i] = a[n];
a[n] = tmp;
}
selection_sort( a, n );
}
}
int main( void )
{
int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
selection_sort( a, N );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9

Using C Print all the most frequent elements in a list

Sample input:
3 4 6 3 3
Expected output:
3
3
3
(printing all the most frequent numbers)
My code:
#include<stdio.h>
#include<stdlib.h>
//Program to count most occuring element
int findMostFrequentElement(int A[], int n)
{
for (int i = 0; i < n; i++) //Sort the array
{
int temp;
for (int j = i+1; j < n; j++)
{
if(A[i] > A[j])
{
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
}
//finnd the most occuring element
int max_count = 1, res = A[0], count = 1;
for (int i = 1; i < n; i++) {
if (A[i] ==A[i - 1])
count++;
else {
if (count > max_count) {
max_count = count;
res = A[i - 1];
}
count = 1;
}
}
// If last element is most frequent
if (count > max_count)
{
max_count = count;
res = A[n - 1];
}
return res; //return the most repeatinng element
}
//Driver Program
int main(int argc, char* argv[])
{
int n; //Array Size Declaration
printf("Enter the number of elements ");
n = atoi(argv[1]);
int array[n]; //Array Declaration
printf("Enter the array elements");
for(int i=0;i<n;i++) //Initializing Array Elements
{
array[i] = atoi(argv[2]);
}
int maxElement = findMostFrequentElement(array, n); //Function call
printf("\n Maximum Repeating Element : %d",maxElement); //Prints the most occuring element
return 0;
}
Any ideas how to fix this? My count isn't printing all the most frequent numbers but instead is just printing the most frequent number. I'm trying to do it using arguments and not scanf
First of all, if you want to get the inputs using arguments you should fix your main function because if you want to store the number of the array's elements in the array then you should also ignore the first element of array in your function findMostFrequentElement. If not, then store it in n and then get the elements! Your main problem is that you are not getting inputs for the elements of array and in the address of elements are some values that you haven't changed! atoi doesn't work like scanf. It should be used after you get the inputs for typecasting.
Second, after you find the most frequent number, you should count the number of times that it has occured so that you can print the most frequent number that many times using for or while which you have done. So, to fix it you should use something like:for (int j=0;j<max_count;j++) printf("%d\n",res); but if there could be several different numbers as output, I suggest that you add another for at the end of your function so that if there are other numbers that are frequent you can find them and print them.

Have I written the Selection Sort Algoithm in C the right way?

A question in my book explained selection sort in three lines and then asked the reader to write CODE for it in C. I have written the code here and it is working fine, but I am a little confused whether I have written it in the right way or not. Please read the code, I have even added comments and correct me if needed.
#include <stdio.h>
#define VALUESIZE 10
int main(void)
{
int temp;
int value[VALUESIZE] = {3, 5, 46, 89, 72, 42, 312, 465812, 758, 1};
// Printing array just for the user to see.
for (int k=0; k<VALUESIZE; k++)
{
printf("[");
printf("%d", value[k]);
printf("] ");
}
printf("\n");
// Sorting algo begins
for (int i=0; i < VALUESIZE - 1; i++) // This will obviously loop through each element in our array except the last element as it will automatically be sorted after n-1 steps
{
for (int j= i+1; j <= VALUESIZE; j++) // This nested loop will go through each element which appears after ith element. For e.g. If i = 2, then j will loop through entire array starting from j = 3
{
if (value[i] > value[j]) // This basic if statement will compare our ith and following jth value
{
temp = value[i]; // If the program finds any value[j] greater than value[i], then the values will be swapped.
value[i] = value[j];
value[j] = temp;
}
}
}
// Now after sorting, print the new sorted array.
for (int l=0; l<VALUESIZE; l++)
{
printf("[");
printf("%d", value[l]);
printf("] ");
}
printf("\n");
}
Select sort needs to iterate through the array to compare the ith value. At the end of this pass it will swap the 2 values. This is a reason why its not a very good sort algorithm for medium or large arrays.
I have changed your code a bit below
Untested but should work:
// Sorting algo begins
for (int i = 0; i < arr_length - 1; i++)
{
int min = i;
for (int j = i + 1; j <= arr_length; j++)
{
if (value[j] < value[min])
{
min = j;
}
}
//now swap
int cache = value[min];
value[min] = value[i];
value[i] = cache;
}

How to find the most repeated value in a array?

I'm trying to find the most repeated int number of my vector.
Here is my code:
for (i = 0; i < dim; i++){
temp = vet[i];
for (i = 0; i < dim; i++){
if(vet[i] == temp){
count++;
}
}
if (most < count){
most = count;
elem = vet[i];
}
}
return elem;
}
It's not correct. I hope you can help me. Thank you!
The most obvious problem is that your code uses i in both the inner and the outer loops. The most and count variables are uninitialized in the above code, and count needs to be reset before starting the inner loop each time.
The method used in this code of iterating over the entire array for each element to count appearances is not very efficient. The efficiency could be improved by starting the inner loop from i + 1, instead of from 0. By doing this, the first frequency count for each element will be correct, though the later counts will be low since the earlier indices will not be visited. But this does not matter, since the first count will have set the most variable if possible. The count variable can be set to 1 before the inner loop begins, since the ith element is the test value, and the inner loop will skip this index. This change will substantially reduce the number of array accesses.
Note that this function will return the value of the first element in the array that is also the most frequently appearing.
int get_most_common(int vet[], size_t dim)
{
size_t i, j, count;
size_t most = 0;
int temp, elem;
for(i = 0; i < dim; i++) {
temp = vet[i];
count = 1;
for(j = i + 1; j < dim; j++) {
if(vet[j] == temp) {
count++;
}
}
if (most < count) {
most = count;
elem = vet[i];
}
}
return elem;
}
You can always try the brute force method, count the frequency of each element, then find the maximum one.
To implement a full version of such function with efficiency, you will need special data structure such as hashtable or dictionary.
But the following codes work well if you just need to return the first item that match such condition.
#include <stdio.h>
// returns the first matched most frequent item of a list
// list items of same value must be grouped, for example, a sorted list
// only returns the first matched item
int max_frequent_item_of(int vet[], int dim)
{
int i = 0;
// element and its count of current sublist
int current = vet[0];
int current_count = 0;
// most frequent element and its count of the list so far
int most = vet[0];
int most_count = 0;
while (i < dim) {
// if i-th element still belong to current sublist, run the counter
if (vet[i] == current) {
current_count += 1;
i += 1;
}
// otherwise, the current sublist just ended
else {
// update the most frequent element
if (current_count > most_count) {
most = current;
most_count = current_count;
}
// reset current sublist
current = vet[i];
current_count = 1;
i += 1;
}
}
printf("most frequent item %d, count %d\n", most, most_count);
return most;
}
int main(void)
{
// vet must be in order, sort with `qsort` if necessary
int vet[] = {1, 1, 2, 3, 4, 4, 4, 8, 9, 9};
int size = 10;
int n;
printf("list: ");
for (n = 0 ; n < size; n++)
{
printf("%d ", vet[n]);
}
printf("\n");
max_frequent_item_of(vet, size);
return 0;
}
output
list: 1 1 2 3 4 4 4 8 9 9
most frequent item 4, count 3
I write This Code do what you need and extra if two numbers have the same repeating times, it returns the Bigger one.
int ReturnMostRepeated(int val[], size_t dim)
{
size_t i,j,count;
int temp=0, temp2;
for(i =0;i<dim;i++)
{
count = 1;
for(j=i+1;j<dim;j++)
{
if(val[j]==val[i])
{
count++;
}
}
if (count>temp)
{
temp = count;
temp2 = val[i];
}else if(count == temp) if (val[i]>temp2) temp2 = val[i];
}
return temp2;
}

Comparing numbers inside of an array

Values are entered into an array by the user and then i have this For Loop to compare the numbers once they have all been entered. What i'm trying to do is find the first larger number in the array.
i = 0;
next = a[++i];
for (i = 0; i < len; i++)
{
if (a[i] > a[next])
{
++next;
if (a[i] < a[next])
{
printf("%d is the first larger number.", a[i]);
}
}
}
When I debug my program I see that when "i" is being compared to a[next] its not taking the value of the number inside that position "i" of the array. i've attempted using "i" instead of a[i] when starting my If statements but that doesn't seem to fix the issue.
Here is my Corrected code. made a few more minor changes just for practice
#include <stdio.h>
int main(int argc, const char * argv[])
{
const int len = 4;
int a[len];
int i;
int j = a[i-1];
for (i = 0; i < len; i++) {
printf("Enter a number:");
scanf("%d", &a[i]);
}
i = 0;
for (i = 1; i < len; i++) {
if (a[i] > a[j])
{
printf("%d is the first larger number.", a[i]);
break;
}
}
}
I think you're looking for the first place where the array is not decreasing; i.e., the index of the first element i such that a[i] > a[i-1].
for (i = 1; i < len; i++) {
if (a[i] > a[i-1]) {
printf("%d is the first larger number", a[i]);
break;
}
}
A new version, printing out the first part of the sequence:
for (i = 1; i < len; i++) {
if (a[i] > a[i-1]) {
printf("\n%d is the first larger number", a[i]);
break;
}
printf("%d ", a[i]);
}
Whatever what you are trying to achieve!! you never say:
next = a[++i];
than
a[i] > a[next] !! a[next] can be beyond the size of your array
EX:
A[] = {0, 7, 2, 3, 1}
next = A[1] = 7
A[next] = A[7] = !! //what u think it is?
Assuming that you are looking for the first local maximum, one solution is to declare a variable called best to keep track of the largest number seen so far. Set best to the first element of the array a[0]. Then check for the first element of the array that is less than best.
best = a[0];
for ( i = 1; i < len; i++ )
{
if ( a[i] > best )
best = a[i];
else if ( a[i] < best )
break;
}
printf( "%d is the first larger number.\n", best );

Resources