When you're coding around in circles and editing line after line of mystifying code in dismay, when you're exhausted, mind numb and flickering in and out of consciousness, from a tenuous session of extreme programming, this is the one place to turn to for that little bit of inspiration, that spark which sets off a genius idea, and the occasional chuckle from a terrible joke or weird phrase.
Monday, 31 December 2012
Program update...
Yep, my Copter game is coming along nicely. I've just made the roof and floor lines of the cave move to make it seem as though the bird is flying forwards...
Wednesday, 26 December 2012
Creating a webpage using HTML5, JavaScript and processing.js
OK, so, I've been making some programs using processing.js over the past few weeks and I've been wondering, "OK, so it's all very well making shapes and lines and stuff and combining them to make cute birds and then using a draw() loop to make cheesy animations, but how do you make a webpage which contains a canvas which is then used to draw those birds and cheesy animations on?"
Well, here is a very basic way of doing it (colour-coded as well!)...
Anything in italics must be replaced by the thing described.
<!--The usual HTML tags-->
<!DOCTYPE html>
<html>
<head>
<script src="processing-1.4.1.js"></script>
<!--This "imports" the functions in the processing-1.4.1.js file. THIS FILE MUST BE SAVED IN THE SAME FOLDER AS THIS HTML FILE!-->
</head>
<body>
<script type="application/processing" data-processing-target="id-of-the-canvas">
void setup() {
// "set up" code (e.g. canvas size, canvas background...) here
// e.g.:
// size(400, 400)
// background(0, 0, 0);
}
void draw() {
// include the draw() function if you want an animation. Put all the animation code here
// e.g.:
// fill(random(0, 255), random(0, 255), random(0, 255));
// ellipse(200, 200, 200, 200);
}
</script>
<canvas id="id-of-the-canvas"></canvas>
</body>
</html>
You can download the processing-1.4.1.js file from this webpage - click "processing-1.4.1.js". Remember to save it in the same folder as the HTML file.
Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>My awesome colour-changing circle!</title>
<style type="text/css">
h1, h2 { font-family:"Comic Sans MS"; font-weight:bold; text-decoration:underline; text-align:center; }
h1 { color:red; }
h2 { color:blue; }
</style>
<script src="processing-1.4.1.js"></script>
</head>
<body>
<h1>Hey, guys - check out my awesome colour-changing circle!!</h1>
<h2>Try mousing over the canvas!</h2>
<script type="application/processing" processing-data-target="canvas">
void setup() {
size(400, 400);
}
void draw() {
background(50, 50, 75);
fill(random(0, 255), random(0, 255), random(0, 255));
ellipse(200, mouseY, 200, 200);
}
</script>
<canvas id="canvas"></canvas>
</body>
</html>
And here's what the webpage looks like:
Just in case you were wondering, yes, I did write all that code myself, and yes, I DID do it all from scratch. :)
Update 09/01/2013: data-processing-type works as well, but it should be data-processing-target, according to the official Processing.js website.
Well, here is a very basic way of doing it (colour-coded as well!)...
Anything in italics must be replaced by the thing described.
<!--The usual HTML tags-->
<!DOCTYPE html>
<html>
<head>
<script src="processing-1.4.1.js"></script>
<!--This "imports" the functions in the processing-1.4.1.js file. THIS FILE MUST BE SAVED IN THE SAME FOLDER AS THIS HTML FILE!-->
</head>
<body>
<script type="application/processing" data-processing-target="id-of-the-canvas">
void setup() {
// "set up" code (e.g. canvas size, canvas background...) here
// e.g.:
// size(400, 400)
// background(0, 0, 0);
}
void draw() {
// include the draw() function if you want an animation. Put all the animation code here
// e.g.:
// fill(random(0, 255), random(0, 255), random(0, 255));
// ellipse(200, 200, 200, 200);
}
</script>
<canvas id="id-of-the-canvas"></canvas>
</body>
</html>
You can download the processing-1.4.1.js file from this webpage - click "processing-1.4.1.js". Remember to save it in the same folder as the HTML file.
Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>My awesome colour-changing circle!</title>
<style type="text/css">
h1, h2 { font-family:"Comic Sans MS"; font-weight:bold; text-decoration:underline; text-align:center; }
h1 { color:red; }
h2 { color:blue; }
</style>
<script src="processing-1.4.1.js"></script>
</head>
<body>
<h1>Hey, guys - check out my awesome colour-changing circle!!</h1>
<h2>Try mousing over the canvas!</h2>
<script type="application/processing" processing-data-target="canvas">
void setup() {
size(400, 400);
}
void draw() {
background(50, 50, 75);
fill(random(0, 255), random(0, 255), random(0, 255));
ellipse(200, mouseY, 200, 200);
}
</script>
<canvas id="canvas"></canvas>
</body>
</html>
And here's what the webpage looks like:
Just in case you were wondering, yes, I did write all that code myself, and yes, I DID do it all from scratch. :)
Update 09/01/2013: data-processing-type works as well, but it should be data-processing-target, according to the official Processing.js website.
Monday, 24 December 2012
Some things I'd like to say... Copter game!
Firstly, I promise that I will eventually finish my hangman game in both C and Java. I've had a lazy month and I haven't done much to improve the code that currently doesn't work....... *sigh*
Now, what I REALLY wanted to blog about was how my Copter game was doing. Yep - you read it right - I'm making a Copter game! You know, that game on the iPhone where you have to guide a helicopter through a cave-like thing, avoiding obstacles and... Yeah, avoiding obstacles. You know, that game that went out of fashion about 25 years ago? Yeah, well, being the sad and boring person I am, I'm creating a version of that game using functions and variables from Processing.js (Thanks, Ruben) on Khan Academy. At the moment, I've drawn the cave ceiling and floor and a bird which will be the thing you need to guide through the cave. I'm going to give the user an option to either control the bird using the mouse or using the spacebar (which is harder).
This is the code I have written so far:
//start draw loop
var draw = function() {
//set background colour
background(28, 3, 25);
//roof dimension variables
var x1 = 0;
//stroke and fill colours for roof and floor
stroke(0, 0, 0);
fill(255, 255, 0);
//roof of cave
for (var i = 0; i < width/100; i++) {
rect(x1, height-25, 100, 25);
x1 += 100;
}
//floor dimension variables
x1 = 0;
//floor of cave
for (i = 0; i < width/100; i++) {
rect(x1, 0, 100, 25);
x1 += 100;
}
//bird position variables
var x = height/2-15;
//randomly generate bird RGB values
var r = random(0, 255),
g = random(0, 255),
b = random(0, 255);
//draw bird
if (mouseY > 25 && mouseY < height-55) {
x = mouseY;
// legs
strokeWeight(7);
line(125, 240, 125, 320);
line(125, 320, 98, 349);
line(125, 320, 163, 346);
line(125, 320, 139, 361);
line(200, 240, 200, 320);
line(200, 320, 169, 355);
line(200, 320, 238, 346);
line(200, 320, 215, 363);
strokeWeight(1);
// body (I still don't fully understand how Beziers work, but I think they're the only way to make the curved shape of a bird's body)
fill(r, g, b);
bezier(283, 130, 223, 116, 80, 100, 63, 262);
bezier(63, 262, 331, 276, 281, 153, 265, 136);
// beak
triangle(290, 85, 290, 100, 330, 100);
triangle(290, 100, 290, 115, 330, 100);
// head
ellipse(250, 100, 100, 100);
// eye
ellipse(270, 80, 25, 25);
// eyeball
fill(0, 0, 0);
ellipse(275, 75, 10, 10);
noFill();
} else {
textFont(createFont("cursive", 30), 30);
text("You lose! Ha!", 50, height/2);
}
};
And here's what's drawn on the canvas:
Now, what I REALLY wanted to blog about was how my Copter game was doing. Yep - you read it right - I'm making a Copter game! You know, that game on the iPhone where you have to guide a helicopter through a cave-like thing, avoiding obstacles and... Yeah, avoiding obstacles. You know, that game that went out of fashion about 25 years ago? Yeah, well, being the sad and boring person I am, I'm creating a version of that game using functions and variables from Processing.js (Thanks, Ruben) on Khan Academy. At the moment, I've drawn the cave ceiling and floor and a bird which will be the thing you need to guide through the cave. I'm going to give the user an option to either control the bird using the mouse or using the spacebar (which is harder).
This is the code I have written so far:
//start draw loop
var draw = function() {
//set background colour
background(28, 3, 25);
//roof dimension variables
var x1 = 0;
//stroke and fill colours for roof and floor
stroke(0, 0, 0);
fill(255, 255, 0);
//roof of cave
for (var i = 0; i < width/100; i++) {
rect(x1, height-25, 100, 25);
x1 += 100;
}
//floor dimension variables
x1 = 0;
//floor of cave
for (i = 0; i < width/100; i++) {
rect(x1, 0, 100, 25);
x1 += 100;
}
//bird position variables
var x = height/2-15;
//randomly generate bird RGB values
var r = random(0, 255),
g = random(0, 255),
b = random(0, 255);
//draw bird
if (mouseY > 25 && mouseY < height-55) {
x = mouseY;
// legs
strokeWeight(7);
line(125, 240, 125, 320);
line(125, 320, 98, 349);
line(125, 320, 163, 346);
line(125, 320, 139, 361);
line(200, 240, 200, 320);
line(200, 320, 169, 355);
line(200, 320, 238, 346);
line(200, 320, 215, 363);
strokeWeight(1);
// body (I still don't fully understand how Beziers work, but I think they're the only way to make the curved shape of a bird's body)
fill(r, g, b);
bezier(283, 130, 223, 116, 80, 100, 63, 262);
bezier(63, 262, 331, 276, 281, 153, 265, 136);
// beak
triangle(290, 85, 290, 100, 330, 100);
triangle(290, 100, 290, 115, 330, 100);
// head
ellipse(250, 100, 100, 100);
// eye
ellipse(270, 80, 25, 25);
// eyeball
fill(0, 0, 0);
ellipse(275, 75, 10, 10);
noFill();
} else {
textFont(createFont("cursive", 30), 30);
text("You lose! Ha!", 50, height/2);
}
};
And here's what's drawn on the canvas:
Friday, 7 December 2012
*In Progress* My person...
Say hello to Bob :)
Original code:
// arms
stroke(13, 94, 64);
strokeWeight(10);
line(175, 260, 110, 150);
line(225, 260, 290, 150);
noStroke();
// body
fill(28, 5, 71);
triangle(200, 100, 110, 330, 280, 330);
// face
fill(255, 255, 70);
ellipse(200, 100, 150, 150);
// eyes
fill(255, 255, 255);
ellipse(170, 70, 30, 10);
ellipse(230, 70, 30, 10);
// eyeballs
fill(0, 0, 0);
ellipse(170, 70, 10, 10);
ellipse(230, 70, 10, 10);
What it looks like:
What I aim to do next:
Original code:
// arms
stroke(13, 94, 64);
strokeWeight(10);
line(175, 260, 110, 150);
line(225, 260, 290, 150);
noStroke();
// body
fill(28, 5, 71);
triangle(200, 100, 110, 330, 280, 330);
// face
fill(255, 255, 70);
ellipse(200, 100, 150, 150);
// eyes
fill(255, 255, 255);
ellipse(170, 70, 30, 10);
ellipse(230, 70, 30, 10);
// eyeballs
fill(0, 0, 0);
ellipse(170, 70, 10, 10);
ellipse(230, 70, 10, 10);
What it looks like:
What I aim to do next:
- Add more facial features
- Add legs
- Add some animations
- Add some user interaction
Wednesday, 5 December 2012
Some shapes...
We are now learning how to draw shapes using a different programming language (Mr Patel thinks it's something like JavaScript).
Original Code:
// a rectangle
rect(60, 80, 20, 5);
//rect(x-axis, y-axis, width, height);
// a circle/ellipse
ellipse(10, 10, 5, 5);
//ellipse(x-axis-from-centre, y-axis-from-centre, width, height);
// a line
line(100, 100, 206, 200);
//line(x-axis-of-first-point, y-axis-of-first-point, x-axis-of-second-point, y-axis-of-second-point);
What it looks like:
Original Code:
// a rectangle
rect(60, 80, 20, 5);
//rect(x-axis, y-axis, width, height);
// a circle/ellipse
ellipse(10, 10, 5, 5);
//ellipse(x-axis-from-centre, y-axis-from-centre, width, height);
// a line
line(100, 100, 206, 200);
//line(x-axis-of-first-point, y-axis-of-first-point, x-axis-of-second-point, y-axis-of-second-point);
What it looks like:

- x-axis = distance from far left side (of screen, display, etc.)
- y-axis = distance from top (of screen, display, etc.)
Monday, 3 December 2012
And the answer to this week's poll question...
At the time that this post was published, there were still 29 minutes left until the poll closed. If you read this post before the poll closes... You know which answer to pick :)
To find the size of an array in C, you type:
sizeof(array);
Replace 'array' with the name of the array variable you want to find the size of.
By the way, in Java, you have to type:
array.length;
...And whoever voted for:
WTFIsTheSizeOfThisArray(array);
...I salute you. You have an amazing sense of humour.
To find the size of an array in C, you type:
sizeof(array);
Replace 'array' with the name of the array variable you want to find the size of.
By the way, in Java, you have to type:
array.length;
...And whoever voted for:
WTFIsTheSizeOfThisArray(array);
...I salute you. You have an amazing sense of humour.
Friday, 30 November 2012
Thursday, 29 November 2012
Tuesday, 27 November 2012
*In Progress* (Yes, that means it's In Progress!) Hangman Game - PART 2
Today, I attempted to read words from a file and put them into a char array. I wanted to randomly select one of these words and use it in the game. Unfortunately, C is just doing my head in because it is, like, soooooooooo difficult to read lines from a file! Java is much easier in this way.... *Sigh* :(
I WILL TRY TO GET THIS CODE WORKING OVER THE WEEKEND AND FINISH IT NEXT LESSON.
Code:
/* Copyright (C) Ming Yin Code Stuff 2012. All Rights Reserved.
* Stealing any fragments, or the whole, of this code is strictly against the UK law and is liable for prosecution.
* IGNORANCE OF THE LAW IS NO DEFENCE.
* YOU HAVE BEEN WARNED. MWAHAHAHAHA........
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
/* This is a simple hangman game console application. The user is required to input a letter when prompted. If that letter is part of the word that the user needs to guess, the user is notified of this and is asked to guess another letter.
* The user has 10 guesses to correctly guess all the letters in the word. If that limit is succeeded, the user has failed and is notified of this. If the user succeeds, the program will print a message of congratulations.
*/
int main() {
FILE *file_ptr = fopen("hardwords.txt", "rt"); // This line declares a file pointer which points to the "hardwords.txt" file, which contains the hardest words to guess in hangman.
if (file_ptr == NULL) {
printf("An error has occurred while attempting to open a file. This program will now commit suicide. :)\n");
printf("Seriously though, this program will now have to shut down because it can't randomly select a word for you to guess. I'm sorry.");
return 1;
}
char cWords[50], // This is the char array that will contain all the words in the "hardwords.txt" file.
*cWord, // This is the word that the user has to guess. It will be chosen from the words in the "hardwords.txt" file.
*cGuessed = malloc(1), // This is a DYNAMIC CHAR ARRAY.
cGuess;
// printf("%ld", sizeof(cGuessed));
int iSuccess = 0,
iGuesses = 10,
iInWord = 0,
iLettersLeft = sizeof(cWord),
iNLettersGuessed = 0,
iLetterGuessed = 0;
while (fgets(cWords, 50, file_ptr) != NULL) {
printf("%s", cWords);
}
printf("%c\n", cWords[1]);
printf("********Welcome to...********\n");
sleep(2);
printf("********Ming's amaaaazzzziiiinnnnggg hangman game!!!!********\n");
sleep(1);
printf("This word has %d letters.\n", iLettersLeft);
sleep(1);
printf("You have %d guesses.\n", iGuesses);
printf("Guess a letter, any letter.\n");
while (!iSuccess && iGuesses > 0) {
scanf(" %c", &cGuess);
cGuess = toupper(cGuess);
/*if (iNLettersGuessed == 0) {
printf("%d\n", sizeof(cGuessed) - 1);
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("Stuff and stuff: %d %c\n", iNLettersGuessed, cGuessed[0]);
} else {
int i;
for (i = 0; i < sizeof(cGuessed); i++) {
if (cGuess == cGuessed[i]) {
iLetterGuessed = 1;
}
}
if (!iLetterGuessed) {
cGuessed = realloc(cGuessed, iNLettersGuessed*sizeof(char));
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("%d %s", iNLettersGuessed, cGuessed);
} else {
printf("That letter has already been guessed.\n");
printf("cGuessed: %s", cGuessed);
continue;
}
iLetterGuessed = 0;
}*/
int i;
for (i = 0; i < sizeof(cWord); i++) {
if (cGuess == cWord[i]) {
iInWord++;
}
if (i == sizeof(cWord) - 1) {
if (!iInWord) {
printf("Sorry, that letter is not in the word. Try again.\n");
} else {
printf("That letter appears %d %s in the word. Felicitations!\n", iInWord, (iInWord == 1) ? "time" : "times");
iLettersLeft -= iInWord;
printf("There %s %d %s left.\n", (iLettersLeft == 1) ? "is" : "letters", iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters");
}
}
}
if (iLettersLeft == 0) {
printf("You, my (wo)man, have completed the game! Congrats!!!\n");
iSuccess = 1;
break;
}
if (!iInWord) {
iGuesses--;
}
if (iGuesses == 0) {
printf("Well, it IS true that there %s only %d %s left, but you've run out of guesses. YOU'VE BEEN HANGED!!!!!\n", (iLettersLeft == 1) ? "is" : "are", iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters");
break;
} else {
printf("Du hast %d Schaetzungen mehr (You have %d %s left).\n", iGuesses, iGuesses, (iGuesses == 1) ? "guess" : "guesses");
}
iInWord = 0;
}
if (iSuccess) {
printf("Well done! You correctly guessed the word %s!! I'm, like, soooo proud of you, O.M.G.!\n", cWord);
printf("Here, have a cookie....");
} else {
printf("OH MY GOD, YOU DEAD! Seriously, can you not even guess the word %s?! WTF?!\n", cWord);
printf("As Taran would say, Let-down......");
}
return 0;
}
BY THE WAY, IF ANYONE HAS ANY TIPS ON HOW I COULD IMPROVE THE CODE IN TERMS OF SIMPLIFYING IT OR MAKING IT MORE CONSISTENT, PLEASE COMMENT ON THIS POST!! In return, I will +1 and follow your blog and you will live your wonderful life knowing that a sad, lonely geek has acknowledged your contribution to his program. :)
I WILL TRY TO GET THIS CODE WORKING OVER THE WEEKEND AND FINISH IT NEXT LESSON.
Code:
/* Copyright (C) Ming Yin Code Stuff 2012. All Rights Reserved.
* Stealing any fragments, or the whole, of this code is strictly against the UK law and is liable for prosecution.
* IGNORANCE OF THE LAW IS NO DEFENCE.
* YOU HAVE BEEN WARNED. MWAHAHAHAHA........
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
/* This is a simple hangman game console application. The user is required to input a letter when prompted. If that letter is part of the word that the user needs to guess, the user is notified of this and is asked to guess another letter.
* The user has 10 guesses to correctly guess all the letters in the word. If that limit is succeeded, the user has failed and is notified of this. If the user succeeds, the program will print a message of congratulations.
*/
int main() {
FILE *file_ptr = fopen("hardwords.txt", "rt"); // This line declares a file pointer which points to the "hardwords.txt" file, which contains the hardest words to guess in hangman.
if (file_ptr == NULL) {
printf("An error has occurred while attempting to open a file. This program will now commit suicide. :)\n");
printf("Seriously though, this program will now have to shut down because it can't randomly select a word for you to guess. I'm sorry.");
return 1;
}
char cWords[50], // This is the char array that will contain all the words in the "hardwords.txt" file.
*cWord, // This is the word that the user has to guess. It will be chosen from the words in the "hardwords.txt" file.
*cGuessed = malloc(1), // This is a DYNAMIC CHAR ARRAY.
cGuess;
// printf("%ld", sizeof(cGuessed));
int iSuccess = 0,
iGuesses = 10,
iInWord = 0,
iLettersLeft = sizeof(cWord),
iNLettersGuessed = 0,
iLetterGuessed = 0;
while (fgets(cWords, 50, file_ptr) != NULL) {
printf("%s", cWords);
}
printf("%c\n", cWords[1]);
printf("********Welcome to...********\n");
sleep(2);
printf("********Ming's amaaaazzzziiiinnnnggg hangman game!!!!********\n");
sleep(1);
printf("This word has %d letters.\n", iLettersLeft);
sleep(1);
printf("You have %d guesses.\n", iGuesses);
printf("Guess a letter, any letter.\n");
while (!iSuccess && iGuesses > 0) {
scanf(" %c", &cGuess);
cGuess = toupper(cGuess);
/*if (iNLettersGuessed == 0) {
printf("%d\n", sizeof(cGuessed) - 1);
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("Stuff and stuff: %d %c\n", iNLettersGuessed, cGuessed[0]);
} else {
int i;
for (i = 0; i < sizeof(cGuessed); i++) {
if (cGuess == cGuessed[i]) {
iLetterGuessed = 1;
}
}
if (!iLetterGuessed) {
cGuessed = realloc(cGuessed, iNLettersGuessed*sizeof(char));
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("%d %s", iNLettersGuessed, cGuessed);
} else {
printf("That letter has already been guessed.\n");
printf("cGuessed: %s", cGuessed);
continue;
}
iLetterGuessed = 0;
}*/
int i;
for (i = 0; i < sizeof(cWord); i++) {
if (cGuess == cWord[i]) {
iInWord++;
}
if (i == sizeof(cWord) - 1) {
if (!iInWord) {
printf("Sorry, that letter is not in the word. Try again.\n");
} else {
printf("That letter appears %d %s in the word. Felicitations!\n", iInWord, (iInWord == 1) ? "time" : "times");
iLettersLeft -= iInWord;
printf("There %s %d %s left.\n", (iLettersLeft == 1) ? "is" : "letters", iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters");
}
}
}
if (iLettersLeft == 0) {
printf("You, my (wo)man, have completed the game! Congrats!!!\n");
iSuccess = 1;
break;
}
if (!iInWord) {
iGuesses--;
}
if (iGuesses == 0) {
printf("Well, it IS true that there %s only %d %s left, but you've run out of guesses. YOU'VE BEEN HANGED!!!!!\n", (iLettersLeft == 1) ? "is" : "are", iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters");
break;
} else {
printf("Du hast %d Schaetzungen mehr (You have %d %s left).\n", iGuesses, iGuesses, (iGuesses == 1) ? "guess" : "guesses");
}
iInWord = 0;
}
if (iSuccess) {
printf("Well done! You correctly guessed the word %s!! I'm, like, soooo proud of you, O.M.G.!\n", cWord);
printf("Here, have a cookie....");
} else {
printf("OH MY GOD, YOU DEAD! Seriously, can you not even guess the word %s?! WTF?!\n", cWord);
printf("As Taran would say, Let-down......");
}
return 0;
}
BY THE WAY, IF ANYONE HAS ANY TIPS ON HOW I COULD IMPROVE THE CODE IN TERMS OF SIMPLIFYING IT OR MAKING IT MORE CONSISTENT, PLEASE COMMENT ON THIS POST!! In return, I will +1 and follow your blog and you will live your wonderful life knowing that a sad, lonely geek has acknowledged your contribution to his program. :)
Wednesday, 21 November 2012
Hangman Game *In Progress*
*Update 26/11/2012* - Some of you have been coming up to me and saying stuff like "It doesn't work!!" Well, that's kinda what "*In Progress*" means. The whole point of me writing "*In Progress*" in the title was to indicate that my hangman game is, well, In Progress!
Anyway, that's my rant over....
I have been creating a hangman game. The code is below, but it doesn't work that well yet...
/* Copyright (C) Ming Yin Code Stuff 2012. All Rights Reserved.
* Stealing any fragments, or the whole, of this code is strictly against the UK law and is liable for prosecution.
* IGNORANCE OF THE LAW IS NO DEFENCE.
* YOU HAVE BEEN WARNED. MWAHAHAHAHA........
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
/* This is a simple hangman game console application. The user is required to input a letter when prompted. If that letter is part of the word that the user needs to guess, the user is notified of this and is asked to guess another letter.
* The user has 10 guesses to correctly guess all the letters in the word. If that limit is succeeded, the user has failed and is notified of this. If the user succeeds, the program will print a message of congratulations.
*/
int main() {
char cWord[6] = "CHEESE", // This is the word that the user has to guess
*cGuessed = malloc(1), // This is a DYNAMIC CHAR ARRAY.
cGuess;
printf("%d", sizeof(cGuessed));
int iSuccess = 0,
iGuesses = 10,
iInWord = 0,
iLettersLeft = sizeof(cWord),
iNLettersGuessed = 0,
iLetterGuessed = 0;
printf("********Welcome to...********\n");
sleep(2);
printf("********Ming's amaaaazzzziiiinnnnggg hangman game!!!!********\n");
sleep(1);
printf("This word has %d letters.\n", iLettersLeft);
sleep(1);
printf("You have %d guesses.\n", iGuesses);
printf("Guess a letter, any letter.\n");
while (!iSuccess && iGuesses > 0) {
scanf(" %c", &cGuess);
cGuess = toupper(cGuess);
if (iNLettersGuessed == 0) {
printf("%d\n", sizeof(cGuessed) - 1);
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("Stuff and stuff: %d %c\n", iNLettersGuessed, cGuessed[0]);
} else {
int i;
for (i = 0; i < sizeof(cGuessed); i++) {
if (cGuess == cGuessed[i]) {
iLetterGuessed = 1;
}
}
if (!iLetterGuessed) {
cGuessed = realloc(cGuessed, iNLettersGuessed*sizeof(char));
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("%d %s", iNLettersGuessed, cGuessed);
} else {
printf("That letter has already been guessed.\n");
printf("cGuessed: %s", cGuessed);
continue;
}
iLetterGuessed = 0;
}
int i;
for (i = 0; i < sizeof(cWord); i++) {
if (cGuess == cWord[i]) {
iInWord++;
}
if (i == sizeof(cWord) - 1) {
if (!iInWord) {
printf("Sorry, that letter is not in the word. Try again.\n");
} else {
printf("That letter appears %d %s in the word. Felicitations!\n", iInWord, (iInWord == 1) ? "time" : "times");
iLettersLeft -= iInWord;
printf("There are %d %s left.\n", iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters");
}
}
}
if (iLettersLeft == 0) {
printf("You, my (wo)man, have completed the game! Congrats!!!\n");
iSuccess = 1;
break;
}
if (!iInWord) {
iGuesses--;
}
if (iGuesses == 0) {
printf("Well, it IS true that there %s only %d %s left, but you've run out of guesses. YOU'VE BEEN HANGED!!!!!\n", (iLettersLeft == 1) ? "is" : "are", iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters");
break;
} else {
printf("Du hast %d Schaetzungen mehr (You have %d %s left).\n", iGuesses, iGuesses, (iGuesses == 1) ? "guess" : "guesses");
}
iInWord = 0;
}
if (iSuccess) {
printf("Well done! You correctly guessed the word %s!! I'm, like, soooo proud of you, O.M.G.!\n", cWord);
printf("Here, have a cookie....");
} else {
printf("OH MY GOD, YOU DEAD! Seriously, can you not even guess the word %s?! WTF?!\n", cWord);
printf("As Taran would say, Let-down......");
}
return 0;
}
And the Java version... :)
/* Copyright (C) Ming Yin Code Stuff 2012. All Rights Reserved.
* Stealing any fragments, or the whole, of this code is strictly against the UK law and is liable for prosecution.
* IGNORANCE OF THE LAW IS NO DEFENCE.
* YOU HAVE BEEN WARNED. MWAHAHAHAHA........
*/
import java.util.Scanner;
class Game {
/* This is a simple hangman game console application. The user is required to input a letter when prompted. If that letter is part of the word that the user needs to guess, the user is notified of this and is asked to guess another letter.
* The user has 10 guesses to correctly guess all the letters in the word. If that limit is succeeded, the user has failed and is notified of this. If the user succeeds, the program will print a message of congratulations.
*/
public static void main(String[] args) {
char cWord[6] = "CHEESE",
cGuess;
boolean bSuccess = false;
int iGuesses = 10,
iInWord = 0,
iLettersLeft = cWord.length,
iNLettersGuessed = 0,
iLetterGuessed = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("********Welcome to...********");
try {
Thread.sleep(2);
} catch (InterruptedException e) {
System.err.println("PROBLEM! PROBLEM! PROBLEM! This program will now exit.");
}
System.out.println("********Ming's amaaaazzzziiiinnnnggg hangman game!!!!********");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.err.println("PROBLEM! PROBLEM! PROBLEM! This program will now exit.");
}
System.out.println("This word has " + iLettersLeft + " letters.");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.err.println("PROBLEM! PROBLEM! PROBLEM! This program will now exit.");
}
System.out.println("You have " + iGuesses + " guesses.");
System.out.println("Guess a letter, any letter.");
while (!bSuccess && iGuesses > 0) {
cGuess = scanner.findWithinHorizon(".", 0).charAt(0);
cGuess = Character.toUpperCase(cGuess);
/*if (iNLettersGuessed == 0) {
printf("%d\n", sizeof(cGuessed) - 1);
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("Stuff and stuff: %d %c\n", iNLettersGuessed, cGuessed[0]);
} else {
int i;
for (i = 0; i < sizeof(cGuessed); i++) {
if (cGuess == cGuessed[i]) {
iLetterGuessed = 1;
}
}
if (!iLetterGuessed) {
cGuessed = realloc(cGuessed, iNLettersGuessed*sizeof(char));
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("%d %s", iNLettersGuessed, cGuessed);
} else {
printf("That letter has already been guessed.\n");
printf("cGuessed: %s", cGuessed);
continue;
}
iLetterGuessed = 0;
}*/
for (int i = 0; i < cWord.length; i++) {
if (cGuess == cWord[i]) {
iInWord++;
}
if (i == sizeof(cWord) - 1) {
if (!iInWord) {
System.out.println("Sorry, that letter is not in the word. Try again.");
} else {
System.out.println("That letter appears " + iInWord + " " + (iInWord == 1) ? "time" : "times" + " in the word. Felicitations!");
iLettersLeft -= iInWord;
System.out.println("There are " + iLettersLeft + " " + iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters" + " left.");
}
}
}
if (iLettersLeft == 0) {
System.out.println("You, my (wo)man, have completed the game! Congrats!!!");
bSuccess = true;
break;
}
if (!iInWord) {
iGuesses--;
}
if (iGuesses == 0) {
System.out.println("Well, it IS true that there " + (iLettersLeft == 1) ? "is" : "are" + " only " + iLettersLeft + " " + (iLettersLeft == 1) ? "letter" : "letters" + " left, but you've run out of guesses. YOU'VE BEEN HANGED!!!!!");
break;
} else {
System.out.println("Du hast " + iGuesses + " Schaetzungen mehr (You have " + iGuesses + " " + (iGuesses == 1) ? "guess" : "guesses" + " left).");
}
iInWord = 0;
}
if (bSuccess) {
System.out.println("Well done! You correctly guessed the word " + cWord + "!! I'm, like, soooo proud of you, O.M.G.!");
System.out.println("Here, have a cookie....");
} else {
System.out.println("OH MY GOD, YOU DEAD! Seriously, can you not even guess the word " + cWord + "?! WTF?!\n", cWord);
System.out.println("As Taran would say, Let-down......");
}
}
}
Anyway, that's my rant over....
I have been creating a hangman game. The code is below, but it doesn't work that well yet...
/* Copyright (C) Ming Yin Code Stuff 2012. All Rights Reserved.
* Stealing any fragments, or the whole, of this code is strictly against the UK law and is liable for prosecution.
* IGNORANCE OF THE LAW IS NO DEFENCE.
* YOU HAVE BEEN WARNED. MWAHAHAHAHA........
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
/* This is a simple hangman game console application. The user is required to input a letter when prompted. If that letter is part of the word that the user needs to guess, the user is notified of this and is asked to guess another letter.
* The user has 10 guesses to correctly guess all the letters in the word. If that limit is succeeded, the user has failed and is notified of this. If the user succeeds, the program will print a message of congratulations.
*/
int main() {
char cWord[6] = "CHEESE", // This is the word that the user has to guess
*cGuessed = malloc(1), // This is a DYNAMIC CHAR ARRAY.
cGuess;
printf("%d", sizeof(cGuessed));
int iSuccess = 0,
iGuesses = 10,
iInWord = 0,
iLettersLeft = sizeof(cWord),
iNLettersGuessed = 0,
iLetterGuessed = 0;
printf("********Welcome to...********\n");
sleep(2);
printf("********Ming's amaaaazzzziiiinnnnggg hangman game!!!!********\n");
sleep(1);
printf("This word has %d letters.\n", iLettersLeft);
sleep(1);
printf("You have %d guesses.\n", iGuesses);
printf("Guess a letter, any letter.\n");
while (!iSuccess && iGuesses > 0) {
scanf(" %c", &cGuess);
cGuess = toupper(cGuess);
if (iNLettersGuessed == 0) {
printf("%d\n", sizeof(cGuessed) - 1);
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("Stuff and stuff: %d %c\n", iNLettersGuessed, cGuessed[0]);
} else {
int i;
for (i = 0; i < sizeof(cGuessed); i++) {
if (cGuess == cGuessed[i]) {
iLetterGuessed = 1;
}
}
if (!iLetterGuessed) {
cGuessed = realloc(cGuessed, iNLettersGuessed*sizeof(char));
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("%d %s", iNLettersGuessed, cGuessed);
} else {
printf("That letter has already been guessed.\n");
printf("cGuessed: %s", cGuessed);
continue;
}
iLetterGuessed = 0;
}
int i;
for (i = 0; i < sizeof(cWord); i++) {
if (cGuess == cWord[i]) {
iInWord++;
}
if (i == sizeof(cWord) - 1) {
if (!iInWord) {
printf("Sorry, that letter is not in the word. Try again.\n");
} else {
printf("That letter appears %d %s in the word. Felicitations!\n", iInWord, (iInWord == 1) ? "time" : "times");
iLettersLeft -= iInWord;
printf("There are %d %s left.\n", iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters");
}
}
}
if (iLettersLeft == 0) {
printf("You, my (wo)man, have completed the game! Congrats!!!\n");
iSuccess = 1;
break;
}
if (!iInWord) {
iGuesses--;
}
if (iGuesses == 0) {
printf("Well, it IS true that there %s only %d %s left, but you've run out of guesses. YOU'VE BEEN HANGED!!!!!\n", (iLettersLeft == 1) ? "is" : "are", iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters");
break;
} else {
printf("Du hast %d Schaetzungen mehr (You have %d %s left).\n", iGuesses, iGuesses, (iGuesses == 1) ? "guess" : "guesses");
}
iInWord = 0;
}
if (iSuccess) {
printf("Well done! You correctly guessed the word %s!! I'm, like, soooo proud of you, O.M.G.!\n", cWord);
printf("Here, have a cookie....");
} else {
printf("OH MY GOD, YOU DEAD! Seriously, can you not even guess the word %s?! WTF?!\n", cWord);
printf("As Taran would say, Let-down......");
}
return 0;
}
And the Java version... :)
/* Copyright (C) Ming Yin Code Stuff 2012. All Rights Reserved.
* Stealing any fragments, or the whole, of this code is strictly against the UK law and is liable for prosecution.
* IGNORANCE OF THE LAW IS NO DEFENCE.
* YOU HAVE BEEN WARNED. MWAHAHAHAHA........
*/
import java.util.Scanner;
class Game {
/* This is a simple hangman game console application. The user is required to input a letter when prompted. If that letter is part of the word that the user needs to guess, the user is notified of this and is asked to guess another letter.
* The user has 10 guesses to correctly guess all the letters in the word. If that limit is succeeded, the user has failed and is notified of this. If the user succeeds, the program will print a message of congratulations.
*/
public static void main(String[] args) {
char cWord[6] = "CHEESE",
cGuess;
boolean bSuccess = false;
int iGuesses = 10,
iInWord = 0,
iLettersLeft = cWord.length,
iNLettersGuessed = 0,
iLetterGuessed = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("********Welcome to...********");
try {
Thread.sleep(2);
} catch (InterruptedException e) {
System.err.println("PROBLEM! PROBLEM! PROBLEM! This program will now exit.");
}
System.out.println("********Ming's amaaaazzzziiiinnnnggg hangman game!!!!********");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.err.println("PROBLEM! PROBLEM! PROBLEM! This program will now exit.");
}
System.out.println("This word has " + iLettersLeft + " letters.");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.err.println("PROBLEM! PROBLEM! PROBLEM! This program will now exit.");
}
System.out.println("You have " + iGuesses + " guesses.");
System.out.println("Guess a letter, any letter.");
while (!bSuccess && iGuesses > 0) {
cGuess = scanner.findWithinHorizon(".", 0).charAt(0);
cGuess = Character.toUpperCase(cGuess);
/*if (iNLettersGuessed == 0) {
printf("%d\n", sizeof(cGuessed) - 1);
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("Stuff and stuff: %d %c\n", iNLettersGuessed, cGuessed[0]);
} else {
int i;
for (i = 0; i < sizeof(cGuessed); i++) {
if (cGuess == cGuessed[i]) {
iLetterGuessed = 1;
}
}
if (!iLetterGuessed) {
cGuessed = realloc(cGuessed, iNLettersGuessed*sizeof(char));
cGuessed[sizeof(cGuessed) - 1] = cGuess;
iNLettersGuessed++;
printf("%d %s", iNLettersGuessed, cGuessed);
} else {
printf("That letter has already been guessed.\n");
printf("cGuessed: %s", cGuessed);
continue;
}
iLetterGuessed = 0;
}*/
for (int i = 0; i < cWord.length; i++) {
if (cGuess == cWord[i]) {
iInWord++;
}
if (i == sizeof(cWord) - 1) {
if (!iInWord) {
System.out.println("Sorry, that letter is not in the word. Try again.");
} else {
System.out.println("That letter appears " + iInWord + " " + (iInWord == 1) ? "time" : "times" + " in the word. Felicitations!");
iLettersLeft -= iInWord;
System.out.println("There are " + iLettersLeft + " " + iLettersLeft, (iLettersLeft == 1) ? "letter" : "letters" + " left.");
}
}
}
if (iLettersLeft == 0) {
System.out.println("You, my (wo)man, have completed the game! Congrats!!!");
bSuccess = true;
break;
}
if (!iInWord) {
iGuesses--;
}
if (iGuesses == 0) {
System.out.println("Well, it IS true that there " + (iLettersLeft == 1) ? "is" : "are" + " only " + iLettersLeft + " " + (iLettersLeft == 1) ? "letter" : "letters" + " left, but you've run out of guesses. YOU'VE BEEN HANGED!!!!!");
break;
} else {
System.out.println("Du hast " + iGuesses + " Schaetzungen mehr (You have " + iGuesses + " " + (iGuesses == 1) ? "guess" : "guesses" + " left).");
}
iInWord = 0;
}
if (bSuccess) {
System.out.println("Well done! You correctly guessed the word " + cWord + "!! I'm, like, soooo proud of you, O.M.G.!");
System.out.println("Here, have a cookie....");
} else {
System.out.println("OH MY GOD, YOU DEAD! Seriously, can you not even guess the word " + cWord + "?! WTF?!\n", cWord);
System.out.println("As Taran would say, Let-down......");
}
}
}
Wednesday, 7 November 2012
Just some bit more work on strings and char arrays... (And Gangnam Style :))
I did something similar some time ago, but just in case you love my blog so much that you just can't resist some more juicy, fat code, here we go....
Original Code:
#include <stdio.h>
int main()
{
char *string = "Herro World!";
char myName[10];
myName[0] = 'M';
myName[1] = 'I';
myName[2] = 'N';
myName[3] = 'G';
myName[4] = 'A';
myName[5] = 'L';
myName[6] = 'I';
myName[7] = 'N';
myName[8] = 'G';
myName[9] = '\0';
char psyOppa[20] = {'O', 'p', 'p', 'a', ' ', 'G', 'a', 'n', 'g', 'n', 'a', 'm', ' ', 'S', 't', 'y', 'l', 'e', '\0'};
int i = 0;
for (i = 0; i < sizeof(psyOppa); i++) // sizeof() returns the size of an array
{
printf("%s, %s, %s\n", string, myName, psyOppa);
}
return 0;
}
Output:
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
This simple program creates char arrays - a.k.a. strings. The general syntax for arrays in C is:
<the-type-of-variable-that-the array-is-full-of> <name>[<number-of-variables-in-array>];
<name>[0] = .......;
<name>[1] = .......;
etc.....
For example, to create an array of 3 integers, write:
int intArray[3];
intArray[0] = 1;
intArray[1] = 2;
intArray[2] = 3;
A shorthand way of creating an array is:
int intArray[3] = {1, 2, 3};
Original Code:
#include <stdio.h>
int main()
{
char *string = "Herro World!";
char myName[10];
myName[0] = 'M';
myName[1] = 'I';
myName[2] = 'N';
myName[3] = 'G';
myName[4] = 'A';
myName[5] = 'L';
myName[6] = 'I';
myName[7] = 'N';
myName[8] = 'G';
myName[9] = '\0';
char psyOppa[20] = {'O', 'p', 'p', 'a', ' ', 'G', 'a', 'n', 'g', 'n', 'a', 'm', ' ', 'S', 't', 'y', 'l', 'e', '\0'};
int i = 0;
for (i = 0; i < sizeof(psyOppa); i++) // sizeof() returns the size of an array
{
printf("%s, %s, %s\n", string, myName, psyOppa);
}
return 0;
}
Output:
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
Herro World!, MINGALING, Oppa Gangnam Style
This simple program creates char arrays - a.k.a. strings. The general syntax for arrays in C is:
<the-type-of-variable-that-the array-is-full-of> <name>[<number-of-variables-in-array>];
<name>[0] = .......;
<name>[1] = .......;
etc.....
For example, to create an array of 3 integers, write:
int intArray[3];
intArray[0] = 1;
intArray[1] = 2;
intArray[2] = 3;
A shorthand way of creating an array is:
int intArray[3] = {1, 2, 3};
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:
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:
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....
I will use the code from my multifunctional calculator but add new functionality to it.
What I thought when I originally started....
- "Hmm... It seems quite easy, but it's actually harder than I thought..."
- "If the memory is going to be expandable, I will need an array, but one that can actually expand and get bigger."
- "In Java, you have that handy ArrayList class which would solve all my problems..."
- "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!).
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:
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 mAnd now another one... yThe 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...
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:
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".
#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:
#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:
- 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.
- Clean up code, make it more consistent.
- Change the input values from type int to type double or float.
- Add more functionality: make the user be able to input more than two numbers, add square-root and other mathematical functions, etc.
- 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!
Tuesday, 25 September 2012
Global Variables
Code:
#include<stdio.h>
static int anotherNum = 200;
int main()
{
extern int anotherNum;
printf("Value of anotherNum is %d\n", anotherNum);
anotherNum += 50;
printf("Value is now %d\n", anotherNum);
extern int num;
printf("Value of num is %d\n", num += 50);
printf("Value of num is now %d", num);
return 0;
}
From another file...
int num = 100;
Output:
#include<stdio.h>
static int anotherNum = 200;
int main()
{
extern int anotherNum;
printf("Value of anotherNum is %d\n", anotherNum);
anotherNum += 50;
printf("Value is now %d\n", anotherNum);
extern int num;
printf("Value of num is %d\n", num += 50);
printf("Value of num is now %d", num);
return 0;
}
From another file...
int num = 100;
Output:
Value of anotherNum is 200
Value is now 250
Value of num is 150
Value of num is now 150
I learned how to:
- Create global variables and use them
- Use global variables from another file
Subscribe to:
Posts (Atom)




