C++ Loops,Variables,Files,Templates / VB 2005 Image

This is where the Admins will put tutorials submitted by users.
Post Reply
Spartan025





Posts: 13
Joined: Fri Oct 13, 2006 3:45 pm
Location: Learning C++

C++ Loops,Variables,Files,Templates / VB 2005 Image

Post by Spartan025 »

C++ Loops,Variables,Files,Templates / Vb 2005 Image

These tuts may not be good but I just want to submit what i know and help beginners start on projects or get some knowledge
-----------------------------------------------------------------------------------

C++ Loops

This explains 2 simple C++ loops , and how to do them right.

First, what is a Loop?

A Loop is a statement that executes over and over as long as
the condition is true. An example would be:

Code: Select all

// A simple Loop
i = 1   // "i" is initialized to 1
while (i <= n) { //While i is less than or equal to 

	cout << i << " "; // Print i
	i++ // Add 1 to i
}
Looking More Closely At A Loop

1. Set i = 1
2. While i is <= n
3. Print i and leave a space in between
4. Add 1 to i.
This looks very confusing but I will explain all.

There are two loop statements you can use for C++.
The While statement, and the for statment.

This diagram shows a basic While statement.

Code: Select all

while (condition) {
	c++ statements
	}
This basically means, If the condition is true, keep going,
if not, the loop ends.

Printing the numbers 1 to N
This program example prints 1 to N in order.

WhileLoop.cpp

Code: Select all

#include <iostream>
using namespace std;

int main() {

int n;
int i;

// Have the user enter a number.
cout << "Type in a number and press ENTER: ";
cin >> n;

// The number is stored in the int variable n.

//while loop
i = 1; //i, the loop counter is initilized to 1.
while (i <= n) {
	cout << i << " "; // Print i
	i++ 	// Add i to 1
}

return 0;
}
How does the program work?
1. A varible with the name n and type int is created.
2. The program prompts for the user to input a number
from the keyboard. Example:10
3. 10 is stored in the variable n.
4. i is initilized to 1.
5. A while statement is used for a loop

5a. While i(1) is less than or equal to n(10)
5b. Print 1
5c. Add 1 to i.
Since i is still onlt 2, and is less than 10,
the loop is executed again.
This keeps going unitl it reaches 10, and i becomes 11 and
the loop is no longer true, so the loop is over.
The Result:
1 2 3 4 5 6 7 8 9 10

*NOTE
There is also such things called Infinite Loops.
This is when the condition is always true and keeps executing.
If this happens, quickly exit the program and look what you did with
your code. You could also use the

Code: Select all

break;
break statement
to exit the current loop.

Step 5c. is also known as incrementing. since it is common to add 1 to a
variable, a special operator, i++ was made.
Here is a list of the 4 increment/decrement operators

Code: Select all

i++ // Return result then add 1 to i
++i // Add 1 to i then return result
i-- // Return result then subtract 1 from i
--i // subtract 1 from i then return result.
The For Statement
Like the while statment, the for statement is a loop statement.
The for statement is more organized and flexible. The for statement is
organized like this:

Code: Select all

for (i = 1;i <= 10;i++) {
cout << i << " "
}
The for statment is broken down to this:
for (initializer;condition;increment) {
statements
}

The for statements also works like the while statement, except you can
also declare varibles during a loop and initialize it. This is an
example of a program similar to the print 1 to n, except its 1-10
to save time.

Code: Select all

#include <iostream>
using namespace std;

int main() {
for (int i = 1;i <= 10; i++) {
cout << i << " ";
}
return 0;
}
This program prints 1 - 10 just like the other program.
In a for loop, you do not need all 3 steps,
initializer, condition, increment. If you do this, the compiler will ignore it
and the loop will become an infinite loop, so watch how you set up your for loops.

Example

Code: Select all

for () {
// Infinite loop, oops
}
Why C++ Loops are better?
In VB loops are like this

Code: Select all

 'A simple loop 
For i = 1 To 10
Print i
Next i
Although this is shorter, the for and while loops are much better, and can do so
much more.

There is also another loop called do-while and will post about at a later time
This basically wraps up the lesson on loops, if i have enough time, I will contribute
another lesson.

------------------------------------------------------------------------------------
This is a template for which most simple C++ programs works

Here are different kinds of templates i use for exercise or my own apps

Simple

Code: Select all

#include <iostream>
using namespace std;

int main() {
      system("PAUSE");
      return 0;
}
This is a simple template of C++ program all the preprocessors or #includes go at the top.
Any functions go before the using namespace std;

int main() is the main function of the program.
Enter all the C++ statements before system("PAUSE");

Infinite Loop User-Terminated

Code: Select all

#include <iostream>
using namespace std;

int main() {
       while(1) {
             //Statements
             //Somehting to terminate, example press 0 and enter to exit
            // otherwise keep going

      }
      system("PAUSE");
      return 0;
}
Same thing as the one before except is terminated by the user and keeps going unless terminated.

These are just suggested templates for C++ and you do not have to use them but are simple and easy to use.
-------------------------------------------------------------------------------------
C++ Variables.

In C++ there are storages in the computer that holds data. There are many specific types of data.

Code: Select all

int (variable name) // Integer, negative 2 billion to positive 2 billion
double (variable name) // Double-precison floating pt. 15 deciaml places
float (variable name) // single float pt.
bool (variable name) // Bool data: true or false
char (variable name)[bytes] // string or text
*p (variable name)//pointer, takes numerical adresses

// All these are variable types or a special storage that has specific 
// type of data
int variable type
Example: int halo_kills
The program makes a storage in the cpu with integer type named
halo_kills. This data can now be manipulated or displayed in any way you wish. This is used for counting and should not be used for decimals.

*if you use decimals in int types, the decimal is truncated or taken off
*example 3.5, .5 is cutt off, and this is a big deal, if you made a program
*that had to calculate the bytes of a halo map and you lost some numbers
*the calculation would be all wrong producing a bad halo map
*program

only use int for numbers that are not decimals. Int varibales serve as good loop variables.

4 bytes


Double Type
Example double halo_ratio_kills // Creates space in cpu with type double named halo_ratio_kills.

The reason you would use double because ratios often come out in decimals and double is the best for deciamls, they do not have the truncating problem like the int and can store bigger values. Double is not advised for loop variables


float type
Same thing as double e.g float halo_ratio_kills
but float does not have the range and accuracy of double, but double takes up more space unlike float.

Float space:4 bytes
Double space:8 bytes


Bool Type
Example bool do_u_like_halo // Creates space in the cpu that takes true and false statements name do_u_like_halo.

boolean flags: true;
false;

alternately you could use 1 for true and 0 for false

4 bytes.


Char
example char game_name[10] // Creates space in the cpu that has a text value called game_name. the "[10]" is how many bytes the string or char has. This can vary depending how long the word or text is.


Pointer
examle (data type) * ip adress// Creates a variable that gets numerical adresses or the orinial places of variables not copies. Variables are the only way to pass data from one function to another. The numerical variable to be read must match the data or base types


Variable Conventions
-make sure variables are descriptive.
-make them lower case
-seperate each word with an underscore(_)
-do not use C++ keywords
-you can only use the alphabet, 0-9 and _
------------------------------------------------------------------------------------


Part I:Ofstream


This section deals with manipulating text files in c++.(This is not how to open Halo maps though, thats binary. That is for another section.)

first you need to include a C++ preproceesor drive called

Code: Select all

#include <fstream>
meaning file stream.

there are 2 main file stream objects(there is another one but these two
are the basics)

ofstream - OutputFilestream
ifstream - InputFilestream

ofstream as you might guess produces files
ifstream reads files.

These objects are mainly for text files and not complicated binary files, such as Halo's .map binary file. Binary files are harder than text and is easier to start with text.

Example of a file being made into text

Code: Select all

#include <iostream>
#include <fstream>
#include <string.h>
// Here I included the necessary preprocessor drives for the
// C++ library
using namespace std; // Here is the necessary namespace

int main() {
        char filename[81];
        cout << "Enter the filename and press ENTER: ";
        cin.getline(filename, 81);
        
        //Char filename is the name of the txt that will be produced

       ofstream save_file_to_txt(filename);

      // Create and object called save_file_to_txt
     // you can choose any name for your object
      
//------------------------------------------------------------
// Use the save_file_to_txt object like cout to make messages
// in the txt file

   // write text to file, use the object like cout once again.
   save_file_to_txt << Halo is awesome << endl;
   save_file_to_txt.close()
  // Close the file 

  system("PAUSE");
  return 0;
}
If you read the comments it is pretty self explanitory.

Tips on ofstream:
In large programs, put these as functions.

Example,(true story) Im in 8th grade, and a few months ago is used my C++ skills to help me on my quadratic formulas. I made a program that outputted the right answer and saved into a text file with work shown. I had two functions, Save and Quadratic and main(always included).

The point is in big programs put things in functions if you know how and use infinite loops and something to terminate the infinite loop.

------------------------------------------------------------------------------------
Making An Image Reader In Visual Basic 2005 Express Edition

This explains how to open up standard images in VB

This is only simple and does not have rich features.
It only shows how to load an image using the openfiledialog

1.Open VB 05 Express
2.CLick New Project
3.Make sure Windows Application is selected
4.Name it Image Reader
5.Rename Form1.vb to MainForm.vb
6.Change the properties of MainForm stated here:
MainForm Properties
Text = Image Reader
MaximizeBox = False
MinimizeBox = False
Size
-Width = 828
-Height = 599

7.Drag a button on the form and change the properties
Button Properties
Name = btnOpen
Text = Open Image
FlatStyle = Popup
Location = (X=323, Y=12)

8.Drag a Picture Box and change its properties
Picture Box Properties
Name = pBoxImage
Size = (Width = 796) (Height = 502)
BackColor = Web White
SIzeMode = Stretch Image

-------------------------------------------------
Your Form should look like this
Image

Now from the toolbox and drag an OpenFileDialog to the form.
Select it on the Component Tray and change the properties.

Name = OpenImage
FileName = Supported Types

Now double-click the button.
It should bring you to the code editor and have the button event handler
written already

Image

Now Type The Following Code

Code: Select all

' This code handles when the user clicks the button
        OpenImage.Filter = " Bitmaps (*.bmp)|*.bmp|GIF (*.gif)|*.gif|JPG _ (*.jpg)|*.jpg|JPEG (*.jpeg)|*.jpeg|PNG (*.png)|*.png|TIFF _(*.TIFF|*.TIFF "
        If OpenImage.ShowDialog() = Windows.Forms.DialogResult.OK_ Then_
            pBoxImage.Image = System.Drawing.Image.FromFile_(OpenImage.FileName)

        End If
What the code does=
The code makes all the supported file type the program will open.
Then it shows the open file dialog.
Then the user navigates to the supported image. The image is then
passed to pBoxImage and shows the image and stretches it out so you can
see it in one box.

Code: Select all

#include <iostream>
using namespace std;

int main() {
        cout << "Initiate Control Room Console" << endl;
        cout << "Initiate functions......" << endl
        system("PAUSE");
        return 0;
}
Post Reply