Programming Course Begins
|
Programming Course began yesterday. I enjoyed it so far. Yesterday’s lecture was a general introduction to computers and today we were introduced to variables. I’m not new to programming. Though I’m no expert but I do know the basics (see one of my old posts where I wrote a guessing game in C++). As such, I’m skipping the talk about what a variable is, so that you won’t die of boredom. Instead, I’m going directly to the exercise list intended for this week. Let me cover some of the more interesting findings in these exercises. Ex. 3 Define two
#include "stdafx.h"
#include "iostream"
int _tmain(int argc, _TCHAR* argv[])
{
int a = 5;
int b = 3;
int c = a + b;
std::cout << c << std::endl;
return 0;
}
While technically violating the task, you can achieve the same result like this:
#include "stdafx.h"
#include "iostream"
int _tmain(int argc, _TCHAR* argv[])
{
int a = 5;
int b = 3;
std::cout << a + b << std::endl;
return 0;
}
There is no third variable and as a result, less memory space is reserved under run-time. Ex. 5 Define a
#include "stdafx.h"
#include "iostream"
int _tmain(int argc, _TCHAR* argv[])
{
float a = 5.47;
int b = a;
std::cout << b << std::endl;
return 0;
}
The output is 5. If I set Ex. 6 Define two
#include "stdafx.h"
#include "iostream"
int _tmain(int argc, _TCHAR* argv[])
{
float a = 0.01f;
float b = 0.02f;
//std::cout.precision(8);
std::cout << a + b << std::endl;
return 0;
}
With the line commented out, the output is Literals like Ex. 11 Define two
#include "stdafx.h"
#include "iostream"
int _tmain(int argc, _TCHAR* argv[])
{
int n,m;
float res;
std::cout <> n;
std::cin >> m;
res = (float) n*n/m;
std::cout << "The value of n^2/m is: " << res << std::endl;
return 0;
}
Important to note here is since n and m are Ex. 24 Write a program that computes
#include "stdafx.h"
#include "iostream"
int _tmain(int argc, _TCHAR* argv[])
{
int n,temp = 1;
std::cout << "Enter an integer n: " <> n;
for (int i = 1; i <= n; i++)
temp = temp * i;
std::cout << n << "! = " << temp << std::endl;
return 0;
}
Note that two special cases, namely Ex. 26 Write a guessing game where the player has to guess a number 1 to 100. After each wrong guess the computer should say if the number is less or more and add one penalty point. When the player guesses the number, the number of penalty points should be displayed and the game stopped.
#include "stdafx.h"
#include "iostream"
#include
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned int)time(0));
int n,g,p = 0; //n - number to be guessed, g - number attempted by player, p - penalty
std::cout << "Guess a number from 1 to 100!" <> g;
while (n != g)
{
if (n > g) std::cout << "More!" << std::endl;
else std::cout << "Less!" <> g;
}
std::cout << "You guessed right! You have " << p << " penalty points." << std::endl;
return 0;
}
|