Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C Exercises: Change the array elements

C Basic Declarations and Expressions: Exercise-127 with Solution

Write a C program that reads an array of integers (length 8), replace the 1st element by the 8th, 2nd by the 7th and so on. Print the final array.

Sample Solution:

C Code:

#include <stdio.h>
int main ()
{
  unsigned short i, j;
  short array_nums[8], n, temp1, temp2;
  printf("Input 8 array elements:\n");
  for (i = 0; i < 8; i++)
  {
    scanf("%hd", &n);
    array_nums[i] = n;
  }

  for (i = 0, j = 7; i <= 4 && j >= 4; i++, j--)
  {
    temp1 = array_nums[i];
    temp2 = array_nums[j];
    array_nums[i] = temp2;
    array_nums[j] = temp1;
  }
 printf("\nModified array:\n");
  for (i = 0; i < 8; i++)
    printf("array_nums[%d] = %d\n", i, array_nums[i]);
}

Sample Output:

Input 8 array elements:
25
35
17
-5
29
45
60
65

Modified array:
array_nums[0] = 65
array_nums[1] = 60
array_nums[2] = 45
array_nums[3] = 29
array_nums[4] = -5
array_nums[5] = 17
array_nums[6] = 35
array_nums[7] = 25

Flowchart:

C Programming Flowchart: Change the array elements.

C programming Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C program that reads an array (length 7) and print all array positions that store a value less or equal to 0.
Next: Write a C program that reads an array of integers (length 10), fill the array elements with number o to a (given number) n – 1 repeated times where 2 <= n <=10.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



C Programming: Tips of the Day

Static variable inside of a function in C

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

Ref : https://bit.ly/3fOq7XP