Printing Integer array in reverse - c

This is fairly simple problem to print the integer array in reverse order. Although whenever i try printing, it ends up displaying garbage value. Below is my program.
#include <stdio.h>
#include <conio.h>
int main()
{
int temp = { '\0' };
int num[9];
int i;
int j = 8;
printf("Enter 8 numbers\n");
for (i = 0; i < 8; i++)
{
scanf_s("%d", &num[i], 1);
}
for (i = 0; i <= j; i++, j--)
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
printf("\nThe numbers in reverse are\n");
for (i = 0; i <=8; i++)
{
printf("%d\n", num[i]);
}
_getch();
return 0;
}
Let just say i input numbers from 1 to 8, it does print the number in reverse but the first value it prints is a garbage value. I know i can use and If statement to counter the situation but is there a way to counter this problem without using if?

You've made two mistakes here:
With 8 numbers, the index of the highest item is 7, not 8. Set j to 7 on initialization to fix this.
When you iterate 8 numbers from index zero, use operator < or !=, not <= to avoid an off-by-one error. Your first loop does it right, but the last loop is broken.
In addition, you may want to reduce the size of the array to 8, because the ninth element is unused.

If you want to print the integers in your array in reverse, simply start at the last index, then work up to the top.
The third loop should look more like this:
int j = 7; // an array of size 8 starts at the 0th and ends at the 7th index.
while(j >= 0)
{
printf("%d", num[j]);
j--;
}

There are several logical inconsistences in your program,
You defined the array as having 9 elements
int num[9];
but enter only 8 elements
for (i = 0; i < 8; i++)
{
scanf_s("%d", &num[i], 1);
}
Thus the last element of the array with insex 8 is not initialized. Nevertheless in the loop that swaps elements of the array you access this uninitialized element
int j = 8;
//...
for (i = 0; i <= j; i++, j--)
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
There is also no need to use function scanf_s instead of scanf
Take into account that to output an array in the reverse order you need not to swap its elements.
The program that outputs an array in the reverse order without swapping its elements can look the following way
#include <stdio.h>
#include <conio.h>
#define N 9
int main( void )
{
int num[N];
int i;
printf( "Enter %d numbers\n", N );
i = 0;
while ( i < N && scanf( "%d", &num[i] ) == 1 ) i++;
printf( "\nThe numbers in reverse are\n" );
while ( i-- ) printf( "%d ", num[i] );
printf( "\n" );
_getch();
return 0;
}
If to enter a sequence of numbers
1 2 3 4 5 6 7 8 9
then the output will look like
9 8 7 6 5 4 3 2 1
If you want to swap elements of the array then the program can look like
#include <stdio.h>
#include <conio.h>
#define N 9
int main( void )
{
int num[N];
int n;
int i;
printf( "Enter %d numbers\n", N );
n = 0;
while ( n < N && scanf( "%d", &num[n] ) == 1 ) n++;
for ( i = 0; i < n / 2; i++ )
{
int tmp = num[i];
num[i] = num[n - i - 1];
num[n - i - 1] = tmp;
}
printf( "\nThe numbers in reverse are\n" );
for ( i = 0; i < n; i++ ) printf( "%d ", num[i] );
printf( "\n" );
_getch();
return 0;
}
If the input is the same as above then output will be
9 8 7 6 5 4 3 2 1

You can also keep the for loop the same and change the indexing
#define ARRAY_SIZE 8
// print in reverse order
for (i = 0; i < ARRAY_SIZE; i++)
{
printf("%d\n", num[ARRAY_SIZE - i - 1]);
}
I used a #define to make it easier to change the program when you need a different array size: just change at one place rather than the 5 you currently need.

Related

Swapping elements from an array that are prime numbers

I need to input my own array and give its own elements, from that array i need to print the same one but if theres a number that is prime, it needs to switch it with the next number. Example:
My array: 4 6 3 5 7 11 13
The new array: 4 6 5 3 11 7 13
Here prime numbers are, 3 5 7 and 13, but 13 doesnt have an element to switch itself, so it stays the same.
#include <stdio.h>
#define array 100
int prime(int b
)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return b; // not prime
}
break;
}
return b;
}
int main()
{
int n, i, a[array];
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]))
{
int temp;
temp = prime(a[i]);
prime(a[i]) == prime(a[i + 1]);
}
}
printf("\nThe new array is:\n");
printf("%d ", prime(a[i]));
return 0;
}
I haven't learned pointers so is there a way without it or?
there are few things needs to modify
need to change function prime return type to bool. since we are interest to check if array element is Prime. if array element is Prime, return True
int prime(int b)
changed to
bool prime(int b)
also need to extend check if prime() function return true and if array index is not last element then only swap array element to next, else skip
if (prime(a[i]) == 1 && a[i-1] != n)
prost(a[i]) looks typo (I guess). corrected to a[i + 1]
this is not optimized code, it just modified version of your code. if you have concern specific performance, please follow suggestion mentioned by
chux - Reinstate Monica
code:
#include <stdbool.h>
#include <stdio.h>
#define array 100
bool prime(int b)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return false; // not prime
}
break;
}
return true;
}
int main()
{
int n, i, a[array];
int temp;
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]) == 1 && a[i] != a[n-1]) /* enter loop only array element is Prime number and it is not last element */
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
a[i++];
}
printf("\nThe new array is:\n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Output for above code: check out this link
How many elements does the array have?
7
Put in 7 elements from the array!
4
6
3
5
7
11
13
My array is:
4 6 3 5 7 11 13
The new array is:
4 6 5 3 11 7 13
...Program finished with exit code 0
Press ENTER to exit console.
First of all, you have a for loop that only makes one iteration because of a break keyword, also in main in a for loop with your swapping you need to assign return values from the prime function to variables, and in the same function, you should use singe '=' because you want to assign value but not to compare. Also in your same for loop, you should check if(prime(a[i+1])) so there won't be any segfaults.

C language: When [variables++] in array[ ] work? For example, when array[j++] = arr[i]. It is doing j++ first or do = arr[i] first?

disclaimer this is not my code and this code is from Remove Duplicate Elements from an Array in C - Javatpoint
What I want to know is in the Example 2 coding part. (I edit code a bit for me or you can see the code clearly.)
/* program to delete the duplicate elements from sorted array in C. */
#include <stdio.h>
int duplicate_element ( int arr[], int num)
{
// check num is equal to 0 and num == 1
if (num == 0 || num == 1)
{
return num;
}
// create temp array to store same number
int temp [num];
// declare variable
int i, j = 0;
// use for loop to check duplicate element
for (i = 0; i < num - 1; i++)
{
// check the element of i is not equal to (i + 1) next element
if (arr [i] != arr[i + 1])
{
temp[j++] = arr[i];
}
}
temp[j++] = arr[ num - 1];
// check the original array's elements with temporary array's elements
for (i = 0; i < j; i++)
{
arr[i] = temp[i];
}
return j;
}
int main ()
{
int num;
printf (" Define the no. of elements of the array: ");
scanf (" %d", &num);
int arr[num], i;
printf (" Enter the elements: ");
// use loop to read elements one by one
for ( i = 0; i < num; i++)
{
scanf (" %d", &arr[i]);
}
printf (" \n Elements before removing duplicates: ");
for ( i = 0; i < num; i++)
{
printf (" %d", arr[i]);
}
num = duplicate_element (arr, num);
// print array after removing duplicates elements
printf (" \n Display array's elements after removing duplicates: ");
for ( i = 0; i < num; i++)
{
printf (" %d", arr[i]);
}
return 0;
}
Here's the question, what does all j++ in function duplicate_element do? (If possible I would like to know what the code is doing since line // use for loop to check duplicate element until before return too. This part I'm just curious if I know it correctly or not.)
This is my understanding (j is the final size of arr[]). In the first question, when executed
j right now is 0
temp[j++]
is it plus the value of j by 1 first then assign value arr[i] to temp[1]. (Does this right?)
The second question, in the first for loop checks when the value in arr[i] is not equal to the value in arr[i + 1] then assign value in temp[j++] with value in arr[i] until for loop is over then assign temp[j++] with arr[num - 1]
(j++ right now is dependent on the if condition for example when all value is not equal to the value of j++ == value of num - 1 and num - 1 is equal to the last value of arr)
and in the last for loop, it assigns every value in Array arr with Array temp. (Does this right?)
In short, the statement
temp[j++] = arr[i];
is equivalent to
int old_value_of_j = j;
j = j + 1;
temp[old_value_of_j] = arr[i];
For starters the code is very bad.
Firstly, the function should be declared like
size_t duplicate_element ( int arr[], size_t num );
That is the size of the passed array should be specified using the unsigned integer type size_t instead of the signed int type int. Otherwise this declaration of the variable length array
// create temp array to store same number
int temp [num];
along with this statement
temp[j++] = arr[ num - 1];
will invoke undefined behavior if the user will pass as the second argument a negative number and according to the function specification it allows to pass a negative number.
Secondly, using the variable length array temp
// create temp array to store same number
int temp [num];
makes the function unsafe. It can occur such a way that the program will be unable to define this variable length array.
The approach is too complicated, confusing and inefficient.
As for your question relative to the postfix operator ++ then according to the C Standard (6.5.2.4 Postfix increment and decrement operators)
2 The result of the postfix ++ operator is the value of the operand.
As a side effect, the value of the operand object is incremented (that
is, the value 1 of the appropriate type is added to it).
So in fact this statement
temp[j++] = arr[i];
may be equivalently rewritten like
temp[j] = arr[i];
j += 1;
As the function adds to the array temp the last element in a series of duplicated elements in the array arr then after this main loop
// use for loop to check duplicate element
for (i = 0; i < num - 1; i++)
{
// check the element of i is not equal to (i + 1) next element
if (arr [i] != arr[i + 1])
{
temp[j++] = arr[i];
}
}
you need to add the last element pf the array arr to the array temp
temp[j++] = arr[ num - 1];
Here is a demonstration program that shows how the function can be rewritten and can look more simpler.
#include <stdio.h>
size_t duplicate_element( int a[], size_t n )
{
size_t m = 0;
for (size_t i = 0; i < n; i++)
{
if (i == 0 || a[i] != a[m-1])
{
if (i != m) a[m] = a[i];
++m;
}
}
return m;
}
int main( void )
{
int a[] = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
size_t m = duplicate_element( a, N );
for (size_t i = 0; i < m; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is
1 2 2 3 3 3 4 4 4 4 5 5 5 5
1 2 3 4 5

practicing the basic - problem with program

Im new in this site hope its ok to post question like that.
Im trying to learn c language and I got a problem to solve that im stuck with.
-- I need to get 10 number and than print it but with no duplicate number:
like if i get 1 2 3 4 5 6 1 2 3 - I need to print only 1 2 3 4 5 6. --
this is what I did:
#include <stdio.h>
int main()
{
int arr1[10] = {0};
int arr2[10] = {0};
int i, j, c;
printf("Please enter 10 numbers:\n");
for (i=0; i<10; ++i) {
scanf(" %d", &arr1[i]);
}
i = j = c = 0;
for (i=0; i<10; ++i) {
while (arr1[i] != arr2[j], j<10) {
++j;
}
if (j==10) {
arr2[c] = arr1[i];
++c;
}
j=0;
}
for (i=0; i<10; ++i) {
printf("%d ", arr2[i]);
}
return 0;
}
input - 8 1 2 1 2 3 4 5 6 7
output - 8 1 2 1 2 3 4 5 6 7 (I should not print the dupicate numbers)
In this while loop
while (arr1[i] != arr2[j], j<10)
there is used an expression with the comma operator. The value of the first operand arr1[i] != arr2[j] of the comma operator is discarded and the result of the expression is the value of the second operand of the comma operator j<10.
So after the loop the variable j will be always equal to 10. In fact you have the following loop
while ( j < 10 ) {
++j;
}
because the first operand of the comma operator has no side effect.
You have to write
while ( j < c && arr1[i] != arr2[j] )
++j;
}
if (j==c) {
arr2[c] = arr1[i];
++c;
}
That is there is needed to check only c elements of the second array.
Also this for loop
for (i=0; i<10; ++i) {
printf("%d ", arr2[i]);
}
should be rewritten like
for (i=0; i < c; ++i) {
printf("%d ", arr2[i]);
}
Actually to output unique elements of an array there is no need to create a second array. The program can look the following way
#include <stdio.h>
int main( void )
{
enum { N = 10 };
int arr1[N] = {0};
printf( "Please enter %d numbers:\n", N );
for ( size_t i = 0; i < N; ++i )
{
scanf( "%d", &arr1[i] );
}
for ( size_t i = 0; i < N; ++i )
{
size_t j = 0;
while ( j != i && arr1[i] != arr1[j] ) ++j;
if ( j == i ) printf( "%d ", arr1[i] );
}
putchar( '\n' );
}
Pay attention to that you should use named constants instead of magic numbers like 10 and you should declare variables in minimum scopes where they are used.

I couldn't handle to write a histogram

My aim is to generate a histogram for repeated numbers. The code works well until the frequency is bigger than 2.
I think I know what is wrong with the code (line 9) but I cannot find an algorithm to solve it. The problem that I have is when it writes the histogram, it separates and then gathers it again.
My Input:
5
5 6 6 6 7
Output:
6:2 6:2 6:3
but the output I need is
6:3
I kind of see the problem but I couldn't solve it.
#include <stdio.h>
int main(){
int array[25];
int i, j, num, count = 1;
scanf("%d", &num);
for (i = 0; i < num; i++) {
scanf("%d", &array[i]);
for (j = 0; j < i ; j++) {
if (array [i] == array[j]) {
count++;
printf("%d:%d ", array[i], count);
}
}
array [i] = array[j];
count = 1;
}
return 0;
}
You are trying to count occurrences before all units have been accepted, which is not possible unless you maintain a separate counter for each value, which in turn is not practical if there is no restriction on the input value range or the range is large.
You need to have obtained all values before you can report any counts. Then for each value in the array, test if the value has occurred earlier, and if not, iterate the whole array to count occurrences:
#include <stdio.h>
#include <stdbool.h>
int main()
{
// Get number of values
int num = 0 ;
scanf("%d", &num);
// Get all values
int array[25];
for( int i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
// For each value in array...
for( int i = 0; i < num ; i++)
{
// Check value not already counted
bool counted = false ;
for( int j = 0; !counted && j < i; j++ )
{
counted = array[j] == array[i] ;
}
// If current value has not previously been counted...
if( !counted )
{
// Count occurnaces
int count = 0 ;
for( int j = 0; j < num; j++ )
{
if( array[j] == array[i] )
{
count++ ;
}
}
// Report
printf("%d:%d ", array[i], count);
}
}
return 0;
}
For your example input, the result is:
5
5 6 6 6 7
5:1 6:3 7:1
It is possible to merge the two inner loops performing the counted and count evaluation:
// Count occurrences of current value,
bool counted = false ;
int count = 0 ;
for( int j = 0; !counted && j < num; j++ )
{
if( array[j] == array[i] )
{
count++;
// Discard count if value occurs earlier - already counted
counted = j < i ;
}
}
// If current value has not previously been counted...
if( !counted )
{
// Report
printf("%d:%d ", array[i], count);
}
}

Trying to print 10 lines of 100 array values in C

I have an array with 100 numbers in it, and I am trying to print it out with only 10 ints on each line, and a tab between each number. It is only printing the first 10 integers and then stopping, which makes sense because of my for loop. I am clearly missing part of it to allow for it to continue through the array. I was going to try to add the line
for(int line_num = 0; line_num < 10; line_num+=10)
before the for statement after the while loop
int array_value;
int length_of_array = 100;
while (length_of_array <= 100){
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
I was also thinking of including a line like
if (array_value % 10 == 0)
printf("\n");
I figured it out! Posted the answer below.
This might be what you're looking for:
/* test.c */
#include <stdio.h>
#define ELEMENTS 100
int main (void)
{
int array [ELEMENTS];
for ( int i = 0; i < ELEMENTS; ++i )
array [i] = i;
for ( int i = 0; i < ELEMENTS; ++i ) {
printf ("%i", array[i]);
if ( (i + 1) % 10 != 0 )
printf ("\t");
else
printf ("\n");
}
return 0;
}
edit: Because of the way the tab can extend to the next line at the end of the line you have to be careful with the tab and new line character.
For clarity, rename length_of_array to offset_in_array and then set it to zero at the start. I renamed array_value and corrected your length check. I also added a check to the inner loop in case the array length gets changed and doesn't divide by 10.
Something like:
int i;
#define ARRAY_LENGTH 100
int offset_in_array = 0;
while (offset_in_array < ARRAY_LENGTH){
for(i = 0; i < 10 && offset_in_array < ARRAY_LENGTH; ++i){
printf("%d ", A[offset_in_array]);
++offset_in_array;
}
}
I haven't tried running this but it should be closer.
Just print a newline every tenth number... If it's not a tenth number, then print a tab.
for (size_t i = 0; i < array_length; ++i) {
printf("%d%c", A[i], i % 10 != 9 ? '\t' : '\n');
}
Live code available at onlinedbg.
Just change the value of length_of_array to 0 and print \n after a for loop.
int array_value;
int length_of_array = 0;
while (length_of_array <= 100) {
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
printf("\n");
}
You can use the following solution to print 10 lines of 100 array values in C:
for (int i = 0; i < 100; ++i){
printf("%i\t", A[i]);
if ((i+1)%10 == 0){
printf("\n");
}
}

Resources