Home > Enterprise >  Swapping numbers with characters inside an array
Swapping numbers with characters inside an array

Time:06-10

I have to generate a random array with 0, 1, or 2 and swap those with specific characters. E.g.: every single 1 should be displayed as 'B'. I got my random array but I have no idea how to swap out the variables inside my array. The numbers should be replaced in the print only.

#include <stdio.h>
#include <stdlib.h>
#include <time.h> 

#define N 5
#define M 5

void print_array();
char get_symbol();
           
int main(void) {
    int i, j;
    int a[M][N];
    srand(time(NULL)); // Initialisiere Zufallsgenerator
    // Weise den Elementen des Arrays Zufallszahlen zu
    for (i = 0; i < M; i  ) { //i-te Zeile
        for (j = 0; j < N; j  ) { //j-te Spalte
            a[i][j] = (rand() % 3); // Erzeuge Zufallszahl
        }
    }
    print_array(a, M, N);
}

void print_array(int a[][N], int m, int n) {
    int i, j;
    printf("Spalte : ");
    for (j = 0; j < n; j  ) {
        printf("%d ", j   1);
    }
    printf("\n\n");
    for (i = 0; i < m; i  ) {
        printf("Zeile %d: ", i   1);
        for (j = 0; j < n; j  ) {
             printf("%d ", a[i][j]);
        }
        printf("\n");
    }
}

// this function is only returning "B"

void print_array(int a[][N], int m, int n) {
    int i, j;
    printf("Spalte : ");
    for (j = 0; j < n; j  ) {
        printf("%d ", j   1);
    }
    printf("\n\n");
    for (i = 0; i < m; i  ) {
        printf("Zeile %d: ", i   1);
        for (j = 0; j < n; j  ) {
            if (a[i][j] = 0) {
                printf("A");
            }
            else if(a[i][j] = 1) {
                printf("B");
            }    
            else {
                printf("C");
            }
        }
        printf("\n");
    }
}

CodePudding user response:

You are using "=" instead of "==" for comparing two values in if else conditions.

       for (j = 0; j < n; j  ) {
        if (a[i][j] = 0){
            printf("A");
        }
        else if(a[i][j] = 1){
            printf("B");
        }    
        else{
            printf("C");
        }
    }

You have to compare values not assign while you are doing the opposite.

    for (j = 0; j < n; j  ) {
        if (a[i][j] == 0){
            printf("A");
        }
        else if(a[i][j] == 1){
            printf("B");
        }    
        else{
            printf("C");
        }
    }

Replace your code with above code.

  •  Tags:  
  • c
  • Related