In this lab, we will be creating our first C program in Visual Studio. I haven’t had time in the class to explain everything you have to do in the class yet, so it’s important that you follow the instructions very carefully.
Launch Visual Studio go Start | Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010.
If you get asked what settings to use, choose Visual C++ settings
The program looks like this:
Go to File | New and choose Project
In the left pane, choose Visual C++ and in the right pane choose Empty Project (This step is very important!)
For Name, enter MyFirstProject and in location, choose U:\ This step is also very important. You must always save your projects on your U:\ drive. That’s your private student drive. Your screen should look like this:
And click OK to create the project
Your screen should look something like this:
If you have the Property Manager pane visible, (as in the above screenshot), you can close it by clicking on the X in the corner of the pane.
In the right hand pane is your Solution Explorer. This is where we will put the CPP files for this project. These files are known as source code files, because these files contain the programming instructions for the project in the C language.
Move your mouse cursor to the Solution Explorer pane and right click on the folder for Source Files. Choose Add | New Item:
Now select CPP file and enter MyFirstFile as the name:
The file will then be created and opened for you to edit. Notice that Visual Studio has added a .cpp extension to the file automatically:
Now we are going to type in our first C program. Be careful not to mix up:
{} (curly brackets) with () (round brackets)
: (colons) with (semi-colons)
, (comma) with . (period)
“ (double quotes) with ‘ (single quotes)
They all have very different meaning in programming. To indent your code, don’t use the SPACE key, use the TAB key instead:
Once you have typed this program in EXACTLY as written, go to the Build menu and choose Build Solution. If you entered the program correctly, then the message:
1>------ Build started: Project: MyFirstProject, Configuration: Debug Win32 ------
1> MyFirstFile.cpp
1> MyFirstProject.vcxproj -> u:\MyFirstProject\Debug\MyFirstProject.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
Should appear in the Output pane. If you get errors in the build, these are called Syntax errors and these errors will be listed in the output window, similar to this:
1>------ Build started: Project: MyFirstProject, Configuration: Debug Win32 ------
1> MyFirstFile.cpp
1>u:\myfirstproject\myfirstproject\myfirstfile.cpp(9): error C2143: syntax error : missing ';' before '}'
1>u:\myfirstproject\myfirstproject\myfirstfile.cpp(17): error C2664: 'message' : cannot convert parameter 2 from 'const char [13]' to 'char'
1> There is no context in which this conversion is possible
1>u:\myfirstproject\myfirstfile.cpp(22): error C2664: 'message' : cannot convert parameter 2 from 'const char [13]' to 'char'
1> There is no context in which this conversion is possible
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
If you double click on the line where the error is listed in the Output pane, Visual Studio will bring you to the line of the program where it thinks the error has occurred, so you can go and correct the error. If you get errors, then go back and double check that you have entered the program exactly. Once you get no errors, its it now time to run the program. Press the play button on the toolbar:
If all goes well, a window should pop open that looks like this:
Congratulations! You have now written your first C program. Press any key to terminate (stop running) the program.
Now to experiment with your program, try the following:
Changing the text: "I love DIT!!" To be something else
Change the number 10 in the two for loops to be different numbers else
Rebuild your program and run it again and see what happens
Download this sample program which has examples of how to declare variables, use printf and scanf.
In this lab we will write a program to calculate the roots of a quadratic equation using the quadratic formula:
The roots of a quadratic equation in the form:
Ax2 + Bx + C
Are given by the quadratic formula
If you are not sure how to do this on pen and paper, read this article which explains how to do it. For practice, calculate the roots of the following formula on pen and paper FIRST:
2x2 – 4x – 3 = 0
You should get the answer:
2.581139
-0.581139
You probably all learned how to use this in secondary school :-), but if you need some revision, read this article first.
To complete this lab:
Enter a value for a
2
Enter a value for b
-4
Enter a value for c
-3
x1 = 2.581139
x2 = -0.581139
Hints!
If you get this program completed before the end of the lab, try creating extra programs that do the following:
Prompts the user for the value in Euro’s and outputs the dollar amount (look up the exchange rate on the internet)
Prompts the user for hours minutes and seconds amounts and outputs the amount of seconds. For example 10 hours, 5 minutes and 20 seconds is 3920 seconds
Read this tutorial on the use of the IF statement for some revision
Also download this example program from the course website which gives lots of examples of using the if statement.
In this tutorial, we will be trying out the if statements we worked on in the class on Monday.
x1 | 100 |
y1 | 100 |
x2 | 120 |
y2 | 150 |
bx | 115 |
by | 120 |
Advanced!
For some extra practice, see if you can use “if else if...” to solve this problem:
Between 0 and 39 | Fail |
Between 40 and 49 | Pass |
Between 50 and 59 | 2.2 |
Between 60 and 69 | 2.1 |
Between 70 and 100 | First |
Anything else | Invalid mark |
Lab 4 - Allegro & loops
Firstly I generally never recommend using lab time to go on Facebook, but today is an exception. Log onto facebook and “like” the DIT School of Computing page:
http://www.facebook.com/ditschoolofcomputing
Now for those of you on Twitter, log on to your Twitter accounts and “follow” the DIT School of Computing:
http://twitter.com/#!/ditcomputing
Ok thats the end of FB & Twitter for today :-)
For the rest of this lab we will be experimenting with Allegro!
Allegro is brilliant C games programming library. Firstly, you need to install Allegro in Visual Studio:
Create a new Empty C++ project.
Go to the menu item Project and choose Properties
In the left pane, choose Configuration Properties | VC++ Directories.
In the right hand pane, click “Include Directories” and click the little down arrow that appears in the right text box to edit this value.
Click Edit
In the edit windows that pops up, click the new icon:
Now type in the following into the line that appears:
M:\allegro-4.4.2-msvc-10.0\include
(This assumes M: is student distrib!)
You might prefer to navigate to this folder in Windows Explorer and copy and paste the path
It should now look like something this:
Click on Ok and now do the same for Library Directories. This time enter:
M:\allegro-4.4.2-msvc-10.0\lib
Click Ok. Now, while still in the project properties, go to Linker | Input in the left pane. In the right pane click on Additional Dependancies and in the window that pops up type:
allegro-4.4.2-md.lib
Your screen should now look like this:
Thats how you set up Allegro in Visual Studio.
On your home computers and laptops only you will need to perform an additional step which is to all the Allegro bin folder to the system path. It is not necessary to do this in the lab as its already setup for you. To do this, type in path into the search box and choose “Edit the system environment variables”. Enter the path to the allegro bin folder. Separate different folders with a ; (semi-colon):
You will need to restart Visual Studio for this change to take effect. Reminder! Dont do this step on a lab computer! Its not necessary.
Now type this program into a new CPP file that you have added to your project:
Compile and run the project. If all is well, you should see a green line appear on the screen. Fantastic. You have just written your first Allegro program.
Before you go any further. Go through your program line by line and write a comment beside each line explaining what you think the line of code does.
For the rest of this lab you will be adding code where it says
//Put your code in here!
The most important parameters the line function and the numbers 10, 10, 100, 100. These represent the X1, Y1 and X2, Y2 values for the start and end points of line.
Try and write the code to implement the following shapes:
Use the allegro functions line and circle in your solutions. be sure and reference the Allegro documentation if you need it.
In your solution, make use of for loops
Remember in your solution:
The best line of code you ever wrote is the line you didn't have to write
For this lab, we take inspiration from the classic game “Buck Rogers and the Planet of Zoom” that we looked at in the class on Monday. Here is a YouTube video:
Create a new project in visual studio 2010 and set up Allegro as described in the previous lab (see above for step by step instructions). Dont forget there are three settings you need to make!
Add a new CPP file and type in the following code:
Dont forget the END_OF_MAIN()
Get the program to compile and run. When it does, you should see a screen appear which looks something like this:
It should display a line and a point. Check out the statements that start with:
line
putpixel
Which achieve this.
The aim of this lab is to create a screen like this:
Do this in three steps
1. Draw the road (calculate the center of the screen and use a for loop)
2. Draw the horizontal perspective lines (notice that the gap between the lines increases) (Use a while loop for this)
3. Draw the random star field with 100 stars in random colours. You should calculate random X and Y positions for the starts. Look at how I calculate random colours to see how this can be done
For a bonus two marks (12 marks in total) , draw in the starship Enterprise somewhere in the scene:
Lab 6
Before starting this lab make sure you understand how the line and circle function works in Allegro:
line(backBuffer, X1, Y1, X2, Y2, makecol(R, G, B));
Where X1, Y1 and X2 Y2 are the coordinates of the start and end of a line and R, G, B are the intensity of red green and blue to use with values between 0 and 255.
circle(backBuffer, X, Y, RADIUS, makecol(R, G, B));
Where X and Y are the center of the circle and RADIUS is the radius of the circle.
Remember! The origin (0,0) is in the top left of the window in Allegro
Also make sure you understand the basics of functions that we discussed in the class. Here is a link to the program that we created in the class.
For this lab you have to create a function which draws either a happy or a sad face at a particular position on the screen:
To complete this lab.
On a DIT Lab computer:
http://www.youtube.com/watch?v=jMF-phmnupc
On your home computer or laptop:
http://www.youtube.com/watch?v=G5cEXCeLdNk
Add a new CPP file to your project and type in (or copy and paste) the following code:
#include <allegro.h>
BITMAP * backBuffer;
// Create your function here!!
//
void main()
{
if (allegro_init() != 0)
{
return;
}
set_color_depth(desktop_color_depth());
if (set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0) != 0)
{
return;
}
backBuffer = create_bitmap(640, 480);
install_keyboard();
bool done = false;
while (! done)
{
if (key[KEY_ESC])
{
done = true;
break;
}
clear_to_color(backBuffer, makecol(0, 0, 0));
// Call your function from here!!
blit(backBuffer, screen, 0, 0, 0, 0, 640, 480);
}
}
// Dont forget the END_OF_MAIN below
END_OF_MAIN()
drawFace(BITMAP * buffer, int x, int y, int r, int g, int b, bool smile)
Where x and y are the position to draw the face (the top left corner)
r, g, b are the red green and blue values to use when drawing
If the parameter smile is true, then draw the smile face
If the parameter smile is false, then draw the sad face.
For a bonus 2 marks (12 marks in total), use for loops to “wallpaper” the screen with alternating happy and sad faces.
Lab 7
For this lab, we will not be using Allegro, so there is no need to set up Allegro in Visual Studio.
The aim of this lab is to write some for loops to draw some Christmas star shapes. Next week we can draw some of these using Allegro.
Write for loops to draw the following shapes:
(Hint! You can put a for loop inside another for loop)
Before attempting to code these up, spend some time to analyse the patterns. Figure out exactly what needs to happen in each iteration of each loop. Remember:
printf("\n");
Prints a “carriage return” (new line)
printf(“*”);
Prints a star symbol, but does not bring the cursor to a new line. The \n is the bit that brings the cursor to a new line. Here are the shapes:
Shape 1:
*
**
***
****
*****
******
*******
********
*********
**********
***********
************
*************
**************
***************
****************
*****************
******************
*******************
Shape 2:
*
**
***
****
*****
******
*******
********
*********
**********
***********
**********
*********
********
*******
******
*****
****
***
**
Shape 3:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
For a bonus 2 marks, write a while loop to print out the Fibonachi series up to 200. For anyone who has not seen (or read) the DiVinci code, it should look like this:
0
1
1
2
3
5
8
13
21
34
55
89
144
Notice that the first two numbers are 0 and 1 and every subsequent number is the sum of the previous two numbers.
The number of users logging into a network every hour is input from the keyboard into a 24-element array of integers. Write a program to display a report of the form:
Time Logins % of Total
0:00 - 1:00 10 2.82
1:00 - 2:00 4 1.13
2:00 - 3:00 3 0.85
3:00 - 4:00 10 2.82
4:00 - 5:00 15 4.23
5:00 - 6:00 18 5.07
6:00 - 7:00 22 6.20
7:00 - 8:00 27 7.61
8:00 - 9:00 8 2.25
9:00 - 10:00 19 5.35
10:00 - 11:00 18 5.07
11:00 - 12:00 23 6.48
12:00 - 13:00 34 9.58
13:00 - 14:00 12 3.38
14:00 - 15:00 25 7.04
15:00 - 16:00 28 7.89
16:00 - 17:00 32 9.01
17:00 - 18:00 11 3.10
18:00 - 19:00 8 2.25
19:00 - 20:00 8 2.25
20:00 - 21:00 7 1.97
21:00 - 22:00 5 1.41
22:00 - 23:00 5 1.41
23:00 - 24:00 3 0.85
Maximum 34 occurred between 12:00-13:00
Minimum 3 occurred between 2:00-3:00
Some hints!
int array[5] = {3, 5, 2, 1, 99};
Part 1
Using pen and paper, perform the following calculations:
Part 2
How much memory in bytes is allocated by the following C code:
#define COUNT 24
int[COUNT] numbers;
float[COUNT] floats;
char[COUNT] chars;
You can use the sizeof operator in C to write a program to test your answer. Check out this program which we wrote in the class for an example of how to use it.
Part 3
Write a C program that asks the user to enter a number in decimal format. Print out the number in binary
Here is an example interaction:
Enter a number:
20
In binary:
00000000000000000000000000010100
Hints!
Part 4 - Something to think about.
The ASCII code for A is 65 (decimal), so the following code will print out the character A. Why? because %c inside printf means treat the variable as a character:
char c;
c = 65;
printf("%c\n", c);
However! The following code will also print the character A
char c;
c = 321;
printf("%c\n", c);
Why?????!!! Answers on a post card to...
The dead body of world famous computer scientist Professor Turing of the DIT School of Computing was recently discovered in his office - K26 in Kevin St. The police investigators suspect that he was murdered while working on a new top secret encryption algorithm which can encode messages inside C programs. In his bloodied hand, was found a printout of a C program and the police have no idea what it does or if it means anything. The police also found a printout of an ASCII table on the desk.
As a crack C programmer, the police have contacted you to see if you can figure out what (if any) messages might be hidden inside the program.
Unfortunately, the police have also insisted that you cant type the program into Visual Studio as they suspect that all the computers are being monitored (possibly by the murderer or something :-)). I strongly suggest you work in teams of no more than 3 people to figure this lab out.
So you have to work out what exactly the program does and what messages it might contain on pen and paper. Below is the printout of the program and an ASCII table:
Only after you have figured out the message on pen and paper, type it into Visual Studio and step through the program using the debugger (F5, F9, F10 and F11) to verify your answer.
Write a function that takes two bank balance amounts (as float pointers) and an interest rate (as a float). The function should add the interest to the bank balances. Here is the prototype:
void calcInterest(float * balanceA, float * balanceB, float rate);
For example, the following code:
float a, b, rate;
a = 200.0f;
b = 300.0f;
rate = 10.0f;
calcInterest(& a, & b, rate);
printf("balance a: %f balance b: %f\n", a, b);
Should print
balance a: 220.000000 balance b: 330.000000
Read the following CAREFULLY SEVERAL TIMES before starting the lab:
Write a function that takes the day in the year as a parameter (an int) and also the month and day of the month (as int pointers). The purpose of the function is to calculate what month and day of the month, the day in the year corresponds to and assign these to the locations pointed to by the pointer parameters.
Here is a prototype for the function:
bool dateCalc(int dayInYear, int * month, int *dayInMonth)
The function should return false if dayInYear > 365 or < 1 otherwise it should return true.
For example, the following code:
int day, month, dayInMonth;
day = 59;
dateCalc(day, & month, & dayInMonth);
printf("Day of the year %d is month %d and day in month %d\n", day, month, dayInMonth);
Should print out:
Day of the year 59 is month 2 and day in month 28
Hints!
Consider the following bool arrays as if they were bits in a byte and convert them to decimal. Work this out on pen and paper first and come up with an algorithm. Do not attempt to start coding until you have come up with the algorithm first.
bool bits[8] = {true, false, true, false, false, false, false, false}; // This is the number 5
// Work the rest out yourself
bool bits[8] = {false, false, true, false, true, true, false, true};
bool bits[8] = {true, false, true, true, true, true, false, true};
bool bits[8] = {false, false, false, false, true, true, false, true};
bool bits[8] = {true, true, true, true, true, true, true, true};
Once you have an algorithm, write a function that takes an array of bools as a parameter and the size of the array. The function should consider the array of bools as if they were bits and return the decimal equivalent. For example, the following program fragment should print the number 180:
bool bits[8] = {false, false, true, false, true, true, false, true};
int val = toDecimal(bits, 8);
printf("%d\n", val);
Here is the function prototype:
int toDecimal(bool * bits, int size);
In your solution, make use or pointer arithmetic instead of using array notation to get access to the elements of the array.
You will probably have to make use of the pow function from math.h in your answer.
Here is the Allegro circle drawing code from the class on Tuesday. Make sure you can compile and run the program. In order to make Allegro programs work on the lab computers, you need to do an additional step.
BEFORE YOU START VISUAL STUDIO
In Windows, go to Start | Settings | Control Panel | System
Find the button for Environment Variables (you may have to click around a few tabs to find it).
In the User Environment Variables settings, click New. In Variable Name, enter
PATH
and in Variable Value enter
M:\allegro-4.4.2-msvc-10.0\bin
Click on ok and then the start Visual Studio to load your project.
The following sequences of binary numbers represent latitude and longitude for locations on the earth encoded as IEEE754 floating point numbers:
01000010010101010110011000101010
11000000110010000101010001110100
01000010010000110111010110100011
01000000000101011111000110011101
01000010000110111000111011001100
11000010100110100001000111011001
Decode these numbers (use pen and paper) to discover the latitude and longitude. Now use this URL (a little app I hacked that makes use of Google maps to reverse geocode latitude and longitude into addresses) to figure out where these locations are:
http://tunepal.org/tunepal/maps/revgeo.php?lat=32.1&long=2.59
Replacing the numbers 32.1 and 2.59 with the numbers you have decoded.
Want an interesting challenge?
See if you can write a program in C to automatically decode these binary numbers into decimal.
Read this article for a refresher on strings in C.
Google have developed a new algorithm for rating how funny a youtube video is by counting the number of times the letters “lol” appear in the comments of the video. Write a C function that takes a comment string as a parameter
and returns the lol count. For example:
void main()
{
char * s1 = "Wow that was so funny lol.";
char * s2 = "lol!! I laughed so rhard! lol";
char * s3 = "U r lame. lol lol lol";
char * s4 = "lollollollollollollollol!!!!!";
printf("lolcount of %s = %d\n"
, s1
, lolCount(s1));
printf("lolcount of %s = %d\n"
, s2
, lolCount(s2));
printf("lolcount of %s = %d\n"
, s3
, lolCount(s3));
printf("lolcount of %s = %d\n"
, s4
, lolCount(s4));
getchar();
}
Prints out :
lolcount of Wow that was so funny lol. = 1
lolcount of lol!! I laughed so rhard! lol = 2
lolcount of U r lame. lol lol lol = 3
lolcount of lollollollollollollollol!!!!! = 8
Here is the function prototype:
int lolCount(char * comment)
Advanced: