Thursday, January 27, 2011

Converting an integer into a character string, C style.

Today in class during OOP344 we were presented with an interesting challenge. We were asked to convert an integer into a character string without using any of the standard libraries. It took me some time to figure this out but I finally came up with a unique solution, now I know most of you will say it uses string library and the stdio library (thats okay, the point is to do the conversion without using any libraries).


I am sure my submission is still subject to a few revision and I welcome any input anyone can provide.


#include <stdio.h>
#include <string.h>


void asciiConv(int digit, char characters[]);

int main() {
    int nums;
    char chars[10];

    printf("Please enter a digit upto 9 characters: ");
    scanf("%d", &nums);
    asciiConv(nums, chars);
    printf("char string: %s\n", chars);

    return 0;
}


/* The following function converts an integer into a char array */
void asciiConv(int digit, char characters[]) {

    int i=0, j=0, slength=0, negative = 0;
    char temp_1, temp_2;

    if (digit < 0) {
        negative = 1;
        digit = -digit;
    }
   
    do {
        characters[i++] = (digit % 10) + '0';            /* Reverse digits input into array #1. */
    } while ((digit /= 10) > 0);             /* Divide the digit by 10 removing the digit previously inputed into array #1. */   

    if (negative) {
        characters[i++] = '-';
    }

    characters[i] = '\0';        /* Add null byte - helpful for doing strlen. */
    slength = strlen(characters);

    for (i = 0, j = (slength-1); i < j; i++, j--) {        /* Reverse array #1 order. */
        temp_1 = characters[i];
        temp_2 = characters[j];
        characters[j] = temp_1;
        characters[i] = temp_2;
    }
}   

Friday, January 14, 2011

Hello Everyone

Hi there everyone,
         I just wanted to introduce myself to everyone. My name is Ahmad Ali and this is my Seneca@York blog. I am currently in the 3rd semester and I am attending Computer Programming and Analysis. This blog will be a reflection of my interests and hobbies as well as my courses here at Seneca@York.
         I am currently attempting to learn Java programing language on my part time so I can edit and customize open source gaming environments. So if you are aware of a good guide please let me know.
         Two of my favorite classes this semester are INT322 and OOP344 because I enjoy learning high level programming languages. I am very excited to learn these two courses this semester and I can't wait until I am capable of developing fully dynamic websites and applications.