Как развернуть массив c

от admin

Reversing Array in C?

Hi i trying to implement a reverse array code but it doesnt seem to work and im really not sure why. The For loop just doesnt seem to work. I dont know why because the logic seems pretty right to me.

5 Answers 5

Avoid using gets() use fgets() instead.

for loop condition should be ‘i < n’. and prototype declaration should match.

for loop condition should be ‘i < n’. and prototype declaration should match.

and «int n» is the size of array. So «i<=n» would make the same array reversed from end to mid, and again from mid to top. So result is same as array. make «n» as half of the array size.

TDK's user avatar

I think better use macro for this task. In code below it is a macro SWAP.

Content a file main.c

Compilation as:

Result:

Notes:

  1. Just working
  2. Workint with any built-in type
  3. Poorly tested and used only the GCC compiler

4.3 The answers on this question

Testing environment

Not gonna lie, it seems as though you’re handling too much in the "reverse function". I personally like to break down my code as much as possible, so that it’s easier to find mistakes.

To start, you may want to put the swapping process (for loop) in its own function called "swap". You can do this with char pointers ‘a’ and ‘b’ as parameters.

C Program to Reverse Elements of an Array

Here, in this page we will discuss the program to reverse elements of an array in C programming language. We are given with an array and need to reverse the elements. We will discuss various algorithms to reverse the array in efficient way.

C program to reverse an array

Here, in page we will discuss various method for reversing the array. Different methods are :

Method Discussed

  • Method 1: Just print the array in reverse order
  • Method 2: Actual in-place reversing of the original array
  • Method 3: Recursive in-place reversing of the original array

Example :

  • Input : arr[5] = [10, 20, 30, 40, 50]
  • Output : Array after reversing, arr[5] = [50, 40, 30, 20, 10]

We will discuss all of these methods one by one below –

C program to reverse an array

Method 1

For an array: arr

  • Run an iterative loop from the last index of the array
  • Print each item one by one arr[i]

Let’s see how it works below –

Method 1 Code in C

Output

Method 2

For an array: arr[] with length len.

Похожие статьи