Monday, 29 October 2012

Pointers - the basics

I did a bit on pointers today. The comments in the code below explain how the program works.

Original Code:

/* 
 * This program demonstrates the basics of pointers.
 * It demonstrates:
 * 1) What pointers do
 * 2) Pointing to an array
 * 3) Pointers in function parameters
 */
#include<stdio.h>
void basicPointerStuff();
void pointerArithmetic();
void pointersInParameters1();
void pointersInParameters2();

int main()
{
    basicPointerStuff();
    pointerArithmetic();
    pointersInParameters1();
    
    return 0;
}

/* 
 * This function demonstrates the VERY basics of pointers.
 * They are variables which POINT to another variable.
 * If you do Java, they somewhat resemble a reference variable pointing to an object...
 */
void basicPointerStuff()
{
    int x = 57;
    int *ptr = &x; // The POINTER variable
    printf("Value of x: %d\n", x);
    printf("Value of ptr: %p\n", ptr);
    /* 
     * A reference variable in Java contains bits that tell the program how to access the object it is referring to.
     * It's sort of the same for pointers in C.
     */
    printf("What does ptr point to? %d\n", *ptr); // Watch out for the asterisk!
}

/*
 * In this function, ptr points to an array. 
 * If you increment ptr, it points to the next element in the array.
 */
void pointerArithmetic()
{
    int x[5] = {1, 2, 3, 4, 5};
    int *ptr = x; // Note that there is NOT an "&"
    printf("%d\n", *ptr);
    printf("%d\n", ++*ptr);
    printf("%d\n", ++*ptr);
}

/*
 * C, like Java, is PASS BY VALUE.
 * That means that if a function uses a value passed to it via its brackets and changes it, the variable with the original value is NOT affected.
 * But since pointers POINT to a variable, a function can CHANGE the value of a variable in a different function using a pointer.
 * This part of the program demonstrates how this is done.
 */
void pointersInParameters1()
{
    int x = 5;
    int *ptr = &x;
    printf("Value of x: %d\n", x);
    pointersInParameters2(ptr);
    printf("Now x is: %d\n", x);
    printf("(Cool init?!)\n");
}

void pointersInParameters2(int *num)
{
    *num += 5;
    /*
     * Although num is not the same pointer as ptr, they both POINT to the variable x.
     * So you can directly change the value of x, as shown above.
     */
}

Output:

Value of x: 57
Value of ptr: 0x7fff62858eac
What does ptr point to? 57
1
2
3
Value of x: 5
Now x is: 10
(Cool init?!)

Sunday, 28 October 2012

Data structures - part 1

Continuing on from the previous post, no, I did NOT just sit there and cry but instead, I went on the internet and found out about data structures and pointers. Apparently, I'll have to make my own ArrayList substitute and I'll need to know about these two things.

So here is a basic introduction to data structures.

In C, the basic user-defined type is the structure (keyword struct). First, you need to define a template  and then declare variables having the new type.

At this point, I almost cried out out loud, "But that's just like classes and objects in Java!" And indeed, there are loads of similarities between structures in C and classes in Java.

Do note that I am making all this stuff up so it might all be nonsense, but let's carry on...

The way to define a structure is as follows:
struct <type-name> {
    <primitive variables>
}; //Don't forget the semi-colon at the end!!!!!!

For example, a piece of music would have a name and a composer (among other things) so a structure defining a piece of music would look something like this:
struct pOMusic {
    char *name;
    char *composer;
};

Then, to declare a variable of type pOMusic, you write this:
struct pOMusic moonlightSonata; //moonlightSonata is the variable name

To set the name and composer of the piece of music write either:
moonlightSonata.name = "Moonlight Sonata";
moonlightSonata.composer = "Beethoven";
OR:
moonlightSonata = {"Moonlight Sonata", "Beethoven"}; //This is like array notation

I could also have just written:

struct pOMusic {
    char *name;
    char *composer;
} moonlightSonata = {"Moonlight Sonata", "Beethoven"}; //Again, DON'T forget the semi-colon at the end!!!!!!

Yeah, so... VERY similar to how Java classes and objects work (except for some major differences.... *ahem*...).

Here is a full working program demonstrating many of the things described above along with some other stuff:

Original Code:

#include <stdio.h>

int main() {
    struct film {
        char *name;
        int ratingOutOfTen;
    } charlieAndTheChocolateFactory = {"Charlie and the Chocolate Factory", 8};
    struct film skyfall, theLorax;
    skyfall.name = "Skyfall";
    skyfall.ratingOutOfTen = 10;
    theLorax.name = "The Lorax";
    theLorax.ratingOutOfTen = 11; //yes, this was intentional...
    
    struct film iceAge = {"Ice Age", 7};
        
    printf("Let the %s, when it crumbles, we will stand tall, face it all together... %s's rating is %d/10 while the film with the worst rating is %s. I like %s but its rating is only %d out of ten.", skyfall.name, theLorax.name, theLorax.ratingOutOfTen, iceAge.name, charlieAndTheChocolateFactory.name, charlieAndTheChocolateFactory.ratingOutOfTen);
    
    return 0;
}

Output:

Let the Skyfall, when it crumbles, we will stand tall, face it all together... The Lorax's rating is 11/10 while the film with the worst rating is Ice Age. I like Charlie and the Chocolate Factory but its rating is only 8 out of ten.


My next project...

Hey Guys! As a super-advanced challenge for me, I'm going to create a calculator with an expandable memory.

I will use the code from my multifunctional calculator but add new functionality to it.

What I thought when I originally started....

  1. "Hmm... It seems quite easy, but it's actually harder than I thought..."
  2. "If the memory is going to be expandable, I will need an array, but one that can actually expand and get bigger."
  3. "In Java, you have that handy ArrayList class which would solve all my problems..."
  4. "But there isn't an ArrayList class in C!!"
What will I do?! Will I give up? Will I rage quit? Will I just sit there and cry?

Stayed tuned for the next exciting instalment of What Will Ming Do Next?...

Yeah... So excited...

Tuesday, 23 October 2012

Answer to this week's poll question...

So, Which package is all the techy GUI stuff for Java located in?
ANSWER: javax.swing.
Well done to the one person who gave it a shot (although you got it wrong) :). The javax.swing package includes classes such as javax.swing.JFrame and javax.swing.JApplet, which are used to make frames and applets (what a shocker!).

Tuesday, 9 October 2012

How to input a char in Java...

Original Code:
import java.lang.*;
import java.util.Scanner;

public class Program {
    public static void main(String[] args) {
        char cCharacter1,
            cCharacter2;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Type in a character ");
        cCharacter1 = scanner.findWithinHorizon(".", 0).charAt(0);
        System.out.print("And now another one... ");
        cCharacter2 = scanner.findWithinHorizon(".", 0).charAt(0);
        System.out.print("The characters you typed are " + cCharacter1 + " and " + cCharacter2);
    }
}


Example of an interaction:
Type in a character m
And now another one... y
The characters you typed are m and y

Java...

import java.lang.*;
public class Program {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

I think you can guess what the output is...

Mein Taschenrechner ist fertig!

So, I said I'd improve it a lot, but I thought I'd just start a new project. So here is a slightly improved - and the FINAL version - of my multifunctional calculator.

Original Code:
#include <stdio.h>
int getUserInput();
int main()
{
 char cOperator,
     cCarryOn,
     cAgain;
 float fFirst,
     fSecond,
     fResult;

  printf("Enter first number ");
  scanf(" %f", &fFirst);
   
  printf("Enter second number ");
  scanf(" %f", &fSecond);

  printf("First number is %f and second number is %f\n", fFirst, fSecond);
   
  printf("Is this what you want? (y/n) ");
  scanf("  %c", &cCarryOn);
  while (cCarryOn != 'y' && cCarryOn != 'n')
  {
      printf("Type either 'y' or 'n' (without quotation marks) ");
      scanf(" %c", &cCarryOn);
  }
  if (cCarryOn == 'n')
  {
      printf("Program will now start again.\n");
      main();
  }
  else
  {
      printf("OK, let's continue.\n");
  }
 
   
   printf("What operator? +, -, * or /? ");
   scanf(" %c", &cOperator);
   while (cOperator != '+' &&
        cOperator != '-' &&
        cOperator != '*' &&
        cOperator != '/')
   {
     printf("Try again ");
     scanf(" %c", &cOperator);
   }
   
  switch (cOperator)
  {
      case '+':
      fResult = fFirst + fSecond;
      break;
      case '-':
      fResult = fFirst - fSecond;
      break;
      case '*':
      fResult = fFirst * fSecond;
      break;
      case '/':
      fResult = fFirst / fSecond;
      break;
      default:
      printf("Ah... Something wrong happened. Program will now restart");
      main();
      break;
  }

  printf("The final answer is %f\n", fResult);
   
  printf("Perform another calculation? (y/n) ");
  scanf(" %c", &cAgain);
  while (cAgain != 'y' && cAgain != 'n')
  {
      printf("Type 'y' or 'n' (without quotation marks) ");
      scanf(" %c", &cAgain);
  }
  if (cAgain == 'y')
  {
      main();
  }
  printf("Thank you for using this calculator. Bye!");
  return 0;
}


Example of an interaction:
Enter first number 43
Enter second number 2
First number is 43.000000 and second number is 2.000000
Is this what you want? (y/n) d
Type either 'y' or 'n' (without quotation marks) y
OK, let's continue.
What operator? +, -, * or / ?/
The final answer is 21.500000
Perform another calculation? (y/n) y
Enter first number 23
Enter second number 2
First number is 23.000000 and second number is 2.000000
Is this what you want? (y/n) y
OK, let's continue.
What operator? +, -, * or / ?e
Try again /
The final answer is 11.500000
Perform another calculation? (y/n) y
Enter first number 43
Enter second number 2
First number is 43.000000 and second number is 2.000000
Is this what you want? (y/n) -
Type either 'y' or 'n' (without quotation marks) y
OK, let's continue.
What operator? +, -, * or / ?-
The final answer is 41.000000
Perform another calculation? (y/n) n
Thank you for using this calculator. Bye!

Friday, 5 October 2012

Getting a string input

Original Code:

#include <stdio.h>

int main()
{
    char string[50],
     string1[] = {'A', 'c', 'i', 'd', '\0'},
     *string2 = "base";
    printf("What is your name?\n");
    gets(string);
    printf("Your name is: \n");
    puts(string);
    
    printf("%ss and %ss", string1, string2);
    
    return 0;
}

Output:
I have learned that there is no String class in C as there is in Java, so you must use a char array. I have learned two ways that you can create a string in C. To print a string, you need to use "%s" and not something like "%c".

Multi-functional calculator - VERSION ONE.

Code:
#include <stdio.h>
int getUserInput();
int main()
{
 char cOperator,
     cCarryOn,
     cAgain;
 int dFirst,
     dSecond,
     dResult;

 // printf("first is %d and second is %d", first, second);
  printf("Enter first number");
  scanf(" %d", &dFirst);
   
  printf("Enter second number");
  scanf(" %d", &dSecond);

  printf("First number is %d and second number is %d\n", dFirst, dSecond);
   
  printf("Is this what you want? (y/n)");
  scanf("  %c", &cCarryOn);
  while (cCarryOn != 'y' && cCarryOn != 'n')
  {
      printf("Type either 'y' or 'n' (without quotation marks)");
      scanf(" %c", &cCarryOn);
  }
  if (cCarryOn == 'n')
  {
      printf("Program will now start again.\n");
      main();
  }
  else
  {
      printf("OK, let's continue.\n");
  }
 
   
   printf("What operator? +, -, * or /?");
   scanf(" %c", &cOperator);
   while (cOperator != '+' &&
        cOperator != '-' &&
        cOperator != '*' &&
        cOperator != '/')
   {
     printf("Try again");
     scanf(" %c", &cOperator);
   }
   
  switch (cOperator)
  {
      case '+':
      dResult = dFirst + dSecond;
      break;
      case '-':
      dResult = dFirst - dSecond;
      break;
      case '*':
      dResult = dFirst * dSecond;
      break;
      case '/':
      dResult = dFirst / dSecond;
      break;
      default:
      printf("Ah... Something wrong happened. Program will now restart");
      main();
      break;
  }

  printf("The final answer is %d\n", dResult);
   
  printf("Perform another calculation? (y/n)");
  scanf(" %c", &cAgain);
  while (cAgain != 'y' && cAgain != 'n')
  {
      printf("Type 'y' or 'n' (without quotation marks)");
      scanf(" %c", &cAgain);
  }
  if (cAgain == 'y')
  {
      main();
  }
  else
  {
      printf("Thank you for using this calculator. Bye!");
  }
  return 0;
}


Output (Example):

WHAT I NEED TO WORK ON:
  1. There seems to be a bug with stops the program from exiting after the user types 'n' when asked if (s)he wants to perform another calculation - see the red lines in the output.
  2. Clean up code, make it more consistent.
  3. Change the input values from type int to type double or float.
  4. Add more functionality: make the user be able to input more than two numbers, add square-root and other mathematical functions, etc.
I knew most of this already beforehand as it is very similar to Java, but here are some points to note:
  • scanf() sometimes requires you to add a space before the "%-" bit in the quotation marks, otherwise the program sometimes goes loopy. I honestly don't know why!