Home > Enterprise >  How do I make these if statements scalable in C?
How do I make these if statements scalable in C?

Time:10-17

This is my code. The goal is to convert the grayscale values to ASCII characters and print an image of Lena. I did it like this but my teacher said it isn't scalable, which is true. I'm relatively new to coding, so is there any way to make this shorter? I thought of using a for loop but can't figure out how.

#include <stdio.h>
#include "lenaArray.h" //This library imports a 2D array of Lena

//Functions used in code;

char charGrayScale(int grayScale)
{
   //This function converts the grayscale values of every index array to a character in the ASCII
    if (grayScale < 25)  return ' ';
    if (grayScale < 50)  return '.';
    if (grayScale < 75)  return ':';
    if (grayScale < 100) return '-';
    if (grayScale < 125) return '=';
    if (grayScale < 150) return ' ';
    if (grayScale < 175) return '*';
    if (grayScale < 200) return '#';
    if (grayScale < 225) return '%';
    return '@';
}

CodePudding user response:

Something like a lookup table would be possible:

#include <stdio.h>
#include "lenaArray.h" //This library imports a 2D array of Lena

//Functions used in code;

const char* GRAYSCALE_CHARS = {' ', '.', ':', '-', '=', ' ', '*', '#', '%'};

char charGrayScale(int grayScale)
{
    const int index = (grayScale/25);
    if (index >= (sizeof(GRAYSCALE_CHARS)/sizeof(GRAYSCALE_CHARS[0]))) return '@';
    return GRAYSCALE_CHARS[index];
}

CodePudding user response:

I assume that by 'scalable' your teacher wants you to get rid of the hard-coded values, to be able to 'scale' your solution towards arbitrary integeger inputs (e.g. not bound to a fixed value 0-255). This can be combined with a lookup table implementation as written in the previous answer by Louis Wilke.

E.g. something like this:

#include <stdio.h>
#include "lenaArray.h" //This library imports a 2D array of Lena

//Functions used in code;

const char greyscaleChars[] = {' ', '.', ':', '-', '=', ' ', '*', '#', '%', '@'};

const char charGreyScale(int greyScale, int min, int max) {
    int step = (max - min) / (sizeof charGreyScale);
    return greyscaleChars[greyScale/step - 1];
} 

Please note I have not tested this code, it is just intended to show the idea.

  • Related