C Programming – Pointer to argc

InPursuitJust for fun, here’s a little program that uses a pointer to return the number of arguments that are submitted to the program at the command line.

#include <stdio.h>

int main(int argc, char argv[])
{
int *ptrArgc;

ptrArgc = &argc;
printf("\n\nOutput number of arguments in argc: %d \n\n", *ptrArgc);

printf("\n\nOutput memory address of argc: %d \n\n", ptrArgc);

return 0;

}

First, notice the line that declares the main() function in the program. The “int argc” declares an integer that automatically fills itself with the number of arguments entered at the command line when you run the program. The name of the program is the first argument, so the smallest number it can return is 1. The “char argv[]” is a character array that contains all the arguments entered at the command line, with “argv[0]” returning the name of the program itself.

The line “int *ptrArgc;” line declares a pointer and the “ptrArgc = &argc;” line assigns the memory address of argc to the pointer.

When printf() is used for the first time, ptrArgc is dereferenced with an asterisk. This causes it to print the value contained in argc instead of the memory address.

The second time printf() is used, ptrArgc is not dereferenced, so it prints the number actually contained in ptrArgc, which is the memory address that holds the value for argc.

Try compiling and running this program, entering different numbers of arguments at the command line. Notice the assigned memory address changes when you run the program.

C Programming – Binary to Decimal Converter

InPursuit

There are 10 kinds of people in this world, those who understand binary and those who don’t. — Unknown

While reading a book on assembly language programming, I came across a section that discussed different numbering systems used and how to convert from one to another. I gave myself some assignments to complete one at a time. Here’s the first one. This converter takes an 8-bit, unsigned binary number, entered at the command line as argv[1], and converts it to its decimal equivalent.

This was a fun assignment. It can easily be modified to take a 16-bit number instead, simply by changing the number of iterations in the for() loop and the starting number for the myCount variable. It uses the pow() function in math.h but everything else in the code is pretty straight forward. I have not tested it fully but it does compile and work using the Visual Studio 2012 command line compiler.

// function receives a string containing an 8-bit, unsigned binary integer 
// returns the decimal integer value of the binary integer
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(int argc, char *argv[])
{
 const char *binNumber = argv[1];
 int decNumber = 0;
 int myDecCount;
 int myCount = 7;

 puts("\n\nBinary to Decimal Converter\nby David Peterson Harvey\n\n");

if (argc == 2)
 {
 printf("%s converts to %d\n\n", binNumber, decNumber);
 // if argv[1] == 8 digits long, binNumber = {argv[1]};
 if(strlen(argv[1]) == 8)
 {
 for(myDecCount=0; myDecCount <=7; myDecCount++) 
 {
 if(binNumber[myCount] == '1')
 {
 decNumber = decNumber + pow(2, myDecCount);
 }
 printf("\nCurrent number %d.\nCurrent count %d.\n\n", myDecCount, decNumber);
 myCount--;
 }
 }
 else
 {
 printf("You must enter a binary number 8 digits long. You entered %s.\n\n", argv[1]);
 }
 }
 else
 {
 printf("To use program:\n\n\t %s 8-digit_binary_number\n\n", argv[0]);
 }
return 0;
}

C – Temperature Conversion

InPursuit I’ve been having fun, reading through a couple of books. One is the second addition of K&R’s “The C Programming Language,” arguably the standard for the C programming language. Early in the book, they provide the reader with a simple conversion table between Fahrenheit and Celsius. I decided it would be fun to take their code a step further and provide a little more functionality to the program. In my spec, I would have the original table generation available but I would also provide functionality to allow the user to enter his or her own temperatures for conversion. The original table provided a one way conversion then displayed the results in a table so the user could reference the table. I had to provide calculations both ways, from Fahrenheit to Celsius and from Celsius to Fahrenheit.

Here’s the original program.

int main()
{
/* print Fahrenheit-Celsius table
for fahr = 0, 20, ..., 300 */
int fahr, celsius;
int lower, upper, step;

lower = 0;
upper = 300;
step = 20;
fahr = lower;

puts("Conversion Table:\n\n");
while(fahr <= upper)
{
celsius = 5 * (fahr-32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr = fahr + step;
}
}

Here is my version. Notice I used the switch statement, evaluating characters input using getch() to determine what to do. If the user chooses anything except an invalid response or ‘q’ to quit, the appropriate function is called. Also, notice that the user input conversions get the number to convert as a string then convert the number as an int using atoi(). This is not the only way to do a conversion from string to int, nor is it usually considered the best way, since it gives no error reporting, but it is a good, quick and dirty way to do conversions of this type.

This was written and compiled as a console program using Visual Studio Express 2012. It will not compile on Linux systems without a few changes. I have a similarly working version for Linux I will post immediately following. It is not perfect and there’s a quick workaround for a problem using scanf() but it gives a decent look at using switches and functions in Linux C.

#include <stdio.h>
char getDecision()
{
char decision;

system("cls");
puts("\n\nTemperature Converter\n\n");
puts("\t(c) Celsius to Fahrenheit\n\t(f) Fahrenheit to Celsius\n\t(t) Conversion Table\n\t(q) Quit\n\nMake your selection ...\n\n");
decision = getch();

return decision;
}

void displayTable()
{
/* print Fahrenheit-Celsius table
for fahr = 0, 20, ..., 300 */
int fahr, celsius;
int lower, upper, step;

lower = 0;
upper = 300;
step = 20;
fahr = lower;

puts("Conversion Table:\n\n");
while(fahr <= upper)
{
celsius = 5 * (fahr-32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr = fahr + step;
}
puts("\n");
}

void convertFtoC()
{
char numberString[256];
int celsius, fahr;
// get the number to convert as a string
puts("Converting Fahrenheit to Celsius\n\n");
puts("Enter number to convert ...\n\n");
fgets (numberString, 256, stdin);
// convert the string number to an integer
fahr = atoi(numberString);
// do the calculations
celsius = 5 * (fahr-32) / 9;
// print the results
printf("%d Fahrenheit = %d Celsius\n\n", fahr, celsius);
}

void convertCtoF()
{
char numberString[256];
int celsius, fahr;

// get the number to convert as a string
puts("Converting Celsius to Fahrenheit\n\n");
puts("Enter number to convert ...\n\n");
fgets (numberString, 256, stdin);
// convert the string number to an integer
celsius = atoi(numberString);
// do the calculations
fahr = (celsius * 9) / 5 + 32;
// print the results
printf("%d Celsius = %d Fahrenheit\n\n", celsius, fahr);
}

int main()
{
char decision = 'x';

decision = 'x';

while(decision != 'q')
{
decision = getDecision();

switch(decision)
{
case 'q':
system("cls");
puts("\n\nTemperature Converter\n\n");
puts("Program exited with no errors.\n\n");
exit(0);
break;
case 'c':
convertCtoF();
break;
case 'f':
convertFtoC();
break;
case 't':
displayTable();
break;
default :
puts("Invalid selection.\n\n");
}
puts("\nPress any key to continue ...\n\n");
getch();
}
return 0;

Now, here’s the code that compiles on a Linux machine.

#include <stdio.h> 
#include <stdlib.h> 
 
char getDecision() 
{ 
    char maindecision; 
 
    system("clear"); 
    puts("\n\nTemperature Converter\n\n"); 
    puts("\t(c) Celsius to Fahrenheit\n\t(f) Fahrenheit to Celsius\n\t(t) Conversion Table\n\t(q) Quit\n\nEnter your selection ...\n\n"); 
    maindecision = getchar(); 
 
    return maindecision; 
} 
 
void displayTable() 
{ 
    /* print Fahrenheit-Celsius table 
    for fahr = 0, 20, ..., 300 */ 
    int fahr, celsius; 
    int lower, upper, step; 
 
    lower = 0; 
    upper = 300; 
    step = 20; 
    fahr = lower;             
 
    puts("Conversion Table:\n\n"); 
    while(fahr <= upper) 
    { 
        celsius = 5 * (fahr-32) / 9; 
        printf("%d\t%d\n", fahr, celsius); 
        fahr = fahr + step; 
    } 
    puts("\n"); 
} 
 
void convertFtoC() 
{ 
    char numberString[256]; 
    int celsius, fahr; 
    // get the number to convert as a string 
    system("clear"); 
    puts("Converting Fahrenheit to Celsius\n\n"); 
    puts("Enter degrees Fahrenheit ...\n\n"); 
    // get and process the number 
    if(scanf("%s", numberString)) 
    { 
        // convert the string number to an integer 
        fahr = atoi(numberString); 
        // do the calculations 
        celsius = 5 * (fahr-32) / 9; 
        // print the results 
        printf("\n\n%d Fahrenheit = %d Celsius\n\n", fahr, celsius); 
    } 
    else printf("\n\nIncorrect input received.\n\n"); 
} 
 
void convertCtoF() 
{ 
    char numberString[256]; 
    int celsius, fahr; 
 
    // get the number to convert as a string 
    system("clear"); 
    puts("Converting Celsius to Fahrenheit\n\n"); 
    puts("Enter degrees Celsius ...\n\n"); 
    // get and process the number 
    if(scanf("%s", numberString)) 
    { 
        // convert the string number to an integer 
        celsius = atoi(numberString); 
        // do the calculations 
        fahr = (celsius * 9) / 5 + 32; 
        // print the results 
        printf("\n\n%d Celsius = %d Fahrenheit\n\n", celsius, fahr); 
    } 
    else puts("\n\nIncorrect input received.\n\n"); 
} 
 
int main() 
{ 
    char decision = 'x'; 
 
    decision = 'x'; 
 
    while(decision != 'q') 
    { 
        decision = getDecision(); 
 
        switch(decision) 
        { 
            case 'q': 
                system("clear"); 
                puts("\n\nTemperature Converter\n\n"); 
                puts("Program exited with no errors.\n\n"); 
                exit(0); 
                break; 
            case 'c': 
                convertCtoF(); 
                break; 
            case 'f': 
                convertFtoC(); 
                break; 
            case 't': 
                displayTable(); 
                break; 
            default : 
                puts("Invalid selection.\n\n"); 
        } 
        getchar(); 
        puts("\nEnter to continue ...\n\n"); 
        getchar(); 
    } 
    return 0; 
} 

Pursuing a Dream Written in Code


InPursuit
What is this dream?

It all started years ago, when I was in my late teens. My friend, Bill, had a computer. I was enthralled with the things he could do with it. It was amazing to see the things he programmed on his Apple computer. I think it was the iie but I don’t remember the model number for sure. Unfortunately, Bill didn’t see his dream of being a programmer. He died of leukemia when he was about 18 or 19 years old. I think he would have been a great contributor to excellence in the computer-driven world we have today.

I’ve wandered my own path in life but computers and music have always been of prime importance. I tried computer programming when I was younger but the math classes discouraged me. I’ve taught music forever, own and operate my own business that does a variety of media production (including music and video) and teaches music and art in our local community. I worked as a technical writer for a number of years, went to school for music and to learn the business of the entertainment industry, and also write and manage the company’s web pages. My interest in programming has never left but my own near death experience in November 2012 has given me an enhanced appreciation of life and the impetus to do the things I’ve wanted to do for a long time.

So, Here’s the Plan

I am currently doing websites in PHP and HTML (my strongest web languages), with MySQL and CSS (necessary companions) and a smattering of Javascript (my weakest language and the closest to being my nemesis). I will be working to update these skills as I go in my daily work.

The areas of interest I have in learning and using additional languages include refreshing my knowledge of C, continuing in C++ and getting farther with Java than I have gone. I learned C years ago but got stuck on pointers. How silly that seems now. I didn’t get very far with C++; I’m going through the tutorial now and can tell you that a couple of years makes a big difference. I stopped for a while in Java but need to go through all the object oriented stuff more fully.

Will You Join Me on My Journey?

I will be posting about my journey here as I strive to become a better programmer. It doesn’t mean I will only post about computer programming. I will also be posting about music, my other great passion, and the two great things you are never supposed to discuss in polite company, namely, religion and politics. You are welcome to join me as I continue a journey that is years in the making. There may be wisdom and wit; that often happens when I’m at my best. You may also, from time to time, catch me at my worst. I hope you will gain something from every minute of it.