Ustaad Cali Xasa: Software Design Using C+ +
Ustaad Cali Xasa: Software Design Using C+ +
cout << "This is the message that would appear on screen." << endl;
Note that a message string is enclosed in double quotes. The << symbols point in the
direction of data flow: from the message string to the cout output stream. The endl
moves the cursor to the beginning of the next line on the screen. Finally, note that the
command, like all C++ statements, ends with a semicolon.
So, how do you incorporate an output statement like the above into a C++ program? Read
the output.cpp example, which is copied here for convenience:
/* Filename: output.cpp
#include <iostream>
using namespace std;
int main(void)
{
cout << "Start of program" << endl;
cout << endl << "You can print whatever you like!" << endl;
cout << endl << "End of program" << endl;
return 0;
}
Items enclosed by /* and */ are comments and are ignored by the compiler. The above
example shows the stype of comments expected at the top of each program. This section
should give the filename, author, date, and a brief (but complete) description. The
description should explain what the program does overall, its inputs, and its outputs.
A short comment that fits on one line can be started with the // symbols. Anything on the
same line but coming after the // is taken as a comment and is ignored by the compiler.
Consider the following two examples:
// This is a comment.
cout << "Hello" << endl; // This is a comment, too.
Let's return to the sample program that we were discussing. The iostream header is
included whenever you want to do input or output. Since most programs use input and
output, you will nearly always want iostream. Note that older C++ compilers have a
similar iostream.h header that can be included. Some compilers support both. In our
examples we will use the version of the header without the .h extension. (Warning:
sometimes the two versions do not give exactly the same capabilities.) When using
headers without the .h extension, also use the std namespace as shown. This namespace
is needed in order to have access to many items that we will use in our programs.
The program above consists of just a main function. All C++ programs must have a main
function. They can also have other functions. program begins at the top of the main
function. There are other ways to write a main function (such as using void, not int, in
front of main, but the above method is about very common and will be used throughout
these notes. The int in front of main indicates that the main function will return an
integer value to the operating system when the function is finished. You can see that the
last line of the main function does indeed return the value 0. (Especially in the UNIX
operating system, this return value can be used to check on how a program finished. For
example, 0 could be used for successful termination and some other number could be
returned to indicate an error condition. We will not really use main's return value in our
examples.)
Execution of the program begins at the top of the main function. Note that the commands
to be carried out by the main function are listed in sequence inside of curly braces. These
commands are carried out in sequence, one after the other, unless they contain something
that alters this standard order of execution. The last command inside of the main function
is typically return 0.
Note that the commands inside of a function (and the braces) are indented a uniform 3
spaces. This is a typical indenting style. Although the compiler does not care about
indenting, it makes it much easier for those people who must read the program. In this
case, it makes it clearer what statements belong to the main function.
See proto.cpp for an outline of a typical C++ program file. It shows how the comment
section should be laid out, where to include the headers, etc.
Input
If we can do output, surely we can also do input. The usual method involves reading data
from the cin input stream. This normally reads its data from what the user types at the
keyboard. For example, to read in an integer (int as it is called), you might use:
int num;
cin >> num;
Note the use of the variable num. A variable is used to hold a value, much like a variable
in algebra. In C++ all variables must be declared. Here the variable num is declared to be
of type int, which means that it can hold a whole number (withing some reasonable
range). A variable is implemented as a named memory location. Thus, the name num
refers to some location in the computer's main memory where the value for num is stored.
Our input statement is one way in which to place a value into the variable num. Note that
the >> symbols point in the direction of data flow: from the cin stream to the variable.
Look at iotest.cpp for an example program that uses both input and output. This program
takes the common approach of printing a prompt before each input operation. That way,
the user of the program is instructed about what to enter at each point. Note the use of
two new data types: char and float. A char variable can hold one single character
(letter, digit, or special symbol such as +). A float holds a real value (which can be a
whole number or number with a decimal point, such as 3.1416). Once again there is a
certain range of legal values for a float, but this range is large enough that we can put
off worrying about it for now.
Assignment Statements
Can we do something other than input and output? One thing we can do is to assign a
value into a variable. The simplest form of the assignment statement is as in the following
example:
int num;
num = 45;
A single = sign is used for assignment. It does not mean "equals" as in algebra. (C++ uses
==, two equals signs, for equals.) The = means assignment. An assignment statement is
always executed from right to left. First, the value on the right hard side is figured out
(here the literal number 45) and is then copied into the variable on the left hand side (here
the variable num). Thus, our example copies 45 into the variable.
The left hand side of an assignment statement needs to be a variable, something that can
be assigned a value. The right hand side can be an expression. An expression is anything
that evaluates to a reasonable value. For example, if we have an integer variable on the
left hand side of the = sign, we could use anything that has an integer value on the right
hand side. Here are some examples using integer variable and values:
int num, answer, temp, value;
num = 45;
answer = num + 1;
temp = num;
value = 2 * num + answer;
As before, we place 45 into num. The second assignment statement first figures out the
value of its right hand side as 46 and then copies the 46 into answer. The next one copies
45 from num into temp. The last one looks up the values of num and temp to figure out its
right hand side value (as 136) and then copies the 136 into value.
Assignment statements can also be used to put character data into character variables. A
literal character value must be written with single quotes around it, as in 'A', whereas a
literal integer or floating point value is written without quotes, as in 3.1416. Here is an
example using some assignment statements with character variables:
char Ch, Save;
Ch = 'T';
Save = Ch;
In this short example, the character T is copied into variable Ch. The second assignment
statement starts on the right hand side, evaluating Ch as 'T'. This character is then copied
into the variable Save.
Simple Computations
Assignment statements can be used to carry out simple computations. At last we can
compute something! For example, to find the area of a rectangle we would want to
multiply the length by the width and probably then store the answer in some variable. The
computation could be carried out by an assignment statement such as:
Area = Length * Width;
Look at area1.cpp for an example program that finds the area of a rectangle. It uses float
variables since the length, width, and area might not be whole numbers. Note how the
user is prompted to enter the length and width. Note, too, how different sections of the
program are separated by blank lines. That is not too important in such a short program,
but in longer ones in can help greatly in improving readability. Consistently indenting by
3 spaces all of the items inside of the function is also used as before.
Stack Overflow
• Questions
• Tags
• Users
• Badges
• Unanswered
• Ask Question
up
I have used the code many times as the starting of my program but never knew what it
vote
really meant which brought me to the question,What does Int Main() mean in C++ ?
0 c++
down link|edit|flag
vote favorite
H4cKL0rD
352426
Watch the capitalization... C++ is case sensitive. int main() – Brian R. Bondy Feb 15 '10 at 2:19
6 Answers
active oldest votes
up
The function main is the first function executed in a compiled C/C++ program (unless you jump
vote
through hoops to configure it otherwise). Why is it called main and not do_this_function_first?
12 Probably to keep similarities to earlier programming languages.
down
vote accepted
By convention, your program returns an integer value (the return value of main) to the shell to
indicate whether the program completed successfully (a zero) or non-successfully (non-zero,
often related to an error code).
link|edit|flag
answered Feb 15 '10 at 2:19
Mark Rushakoff
43.9k244107
While it's the primary entry point, global and static initialization can cause other functions to be
called prior to main (i.e. int x = foo(); outside of the function will cause mean foo() will be
executed prior to main()). – R Samuel Klatchko Feb 15 '10 at 2:41
@R Samuel I didn't know that. Interesting, thanks! – Ninefingers Feb 15 '10 at 2:49
@R Samuel: That is true, however, in some operating systems (especially ones that don't have
.init/.fini section support), compilers are basically required to put all the .init code into the top of
main instead (and register .fini code with atexit). Hence, it's very important for main to be
compiled with a C++ compiler (even though main usually has no name mangling done to it,
unlike most other C++ functions), even if all the other C-like functions used by the program can
instead be compiled with a C compiler. – Chris Jester-Young Feb 15 '10 at 2:53
up
The main function is the entry point to your program, meaning that the code there will execute
vote
when your program starts. You are declaring the main function to return an integer. You are
2 supposed to return 0 if your program ran successfully and a non-zero value otherwise.
down link|edit|flag
vote answered Feb 15 '10 at 2:18
Raul Agrait
1,673725
up
From the C++ Primer, 4th edition:
vote
1 "Every C++ program contains one or more functions, one of which must be named main. A
function consists of a sequence of statements that perform the work of the function. The
down
vote operating system executes a program by calling the function named main. That function
executes its constituent statements and returns a value to the operating system. The operating
system uses the value returned by main to determine whether the program succeeded or failed.
A return value of 0 indicates success. The main function is special in various ways, the most
important of which are that the function must exist in every C++ program and it is the (only)
function that the operating system explicitly calls. We define main the same way we define
other functions. A function definition specifies four elements: the return type, the function name,
a (possibly empty) parameter list enclosed in parentheses, and the function body. The main
function may have only a restricted set of parameters.[...] The main function is required to have
a return type of int, which is the type that represents integers. The int type is a built-in type,
which means that the type is defined by the language."
Related to the meaning of int main is the following entry in Bjarne Stroustrup's C++ Style and
Technique FAQ:
Can I write "void main()"?
Finally, there have been in the past two other questions on stackoverflow that are very related:
and
link|edit|flag
edited Feb 15 '10 at 3:22
Alexandros Gezerlis
1,104210
up
It's the entry point to your program - the primary, "main" function, as it were.
vote
0 link|edit|flag
answered Feb 15 '10 at 2:17
down
vote
Michael Petrotta
18.9k22149
up
Main is the entry point in to you program, for a c or c++ program to run you must have this Main
vote
method as the point for your program to start executing from. It also takes in command line
0 arguments you wish to pass in. more info here:
down http://en.wikipedia.org/wiki/Main_function_%28programming%29#C_and_C.2B.2B
vote
link|edit|flag
answered Feb 15 '10 at 2:19
Craig
38319
up
I'll add to this, not in "answer" as such but some more technical info. "main" is indeed the
vote
startup routine for most C common runtimes, and C++ and as such Java has static void Main()
0 too, for no other reason than history. What usually happens is the entry point is elsewhere in
down the executable and main is called later after the appropriate libraries are loaded in for the
vote platform.
That said, there are alternatives. Two frequent ones appear on Windows:
WinMain or WMain is the main routine used by the Windows API for GUI applications. You'll see
this, too, with MinGW as well as Visual Studio, using the option from LINK.EXE
/SUBSYSTEM:WINDOWS.
If you were to use /SUBSYSTEM:NATIVE you'd generate a Windows "Native App", that is to
say, Native to the kernel and not to the Win32 subsystem (read up on that if you're
interested - the stuff going on behind the Windows launch screen and programs like chkdisk
are examples on WinNT+ platforms). These processes have an entry point at
NtProcessStartup(), totally different to the main you'd expect.
What I'm trying to say is that main is the standard name for an entry point but not by any means
the only one - many APIs work differently, some with good reason, others not, and not all (in
fact all of the above) don't conform to the usual int main(int argc, char** argv) definition. "main"
in the sense of the the usual option plus all of the above is simply "where your code starts", or if
you want to talk at a system level, the address at which to start executing.
Hope that gives you some background info in case you see any alternatives.
link|edit|flag
answered Feb 15 '10 at 2:47
Ninefingers
8,0541629
Your Answer
•
•
• http://stackoverflow.com/editing-help
Name
log o Email
never show n
r
in
Home Page
Post Your Answ er
Not the answer you're looking for? Browse other questions tagged c++ or
ask your own question.
Hello World!
This is a collaboratively edited question and answer site for professional and enthusiast
programmers. It's 100% free, no registration required.
about » faq »
tagged
c++ × 58347
asked
1 year ago
viewed
847 times
latest activity
1 year ago
electronics.stackexchange.com
Is the Microblaze soft cpu better than the Cortex M3 soft cpu
– kurtnelle
3 answers fpga
Linked
Difference between void main and int main?
why do we give int main in c++ and not void main?
Related
What does template <unsigned int N> mean?
What does this C++ error mean?
What does this mean const int*& var?
what does this code mean?
what does (int) mean in C programming
What does this C++ code mean?
What does “int 0x80” mean in assembly code?
“int -> int -> int” What does this mean in F# ?
What does this “label” mean in C++?
What does int argc, char *argv[] mean?
What does ~ mean in C++?
what does allocator mean in STL
What does the :: mean in C++?
What does this line mean?
What does string::npos mean
what does this mean ?
What does -> mean in C++?
What does |= mean in C++?
What does int & mean
what does this mean in c int a:16; ?
What does : :: mean in C++?
What does an extra 0 in front of an int value mean?
int max = ~0; What does it mean?
What does this symbol mean in C++? “~”
What does '&' mean in C++?
question feed
about | faq | new blog | chat | data | podcast | legal | advertising info | contact us | feedback always
welcome
■ stackoverflow.com ■ api/apps ■ careers ■ serverfault.com ■ superuser.com ■ meta
■ area 51 ■ webapps ■ gaming ■ ubuntu ■ webmasters ■ cooking ■ game development
■ math ■ photography ■ stats ■ tex ■ english ■ theoretical cs ■ programmers ■ unix
■ apple ■ wordpress
http://creativecommons.org/licenses/by-sa/2.5/
rev 2011.2.17.1
site design / logo © 2011 stack overflow internet services, inc; user contributions licensed under cc-
wiki with attribution required
Stack Overflow works best with JavaScript enabled
Search
Starting out
Getting Started
Tutorials
Lesson 1: The basics
of C++(Printable Version)
Quizzes
Moving on
Advanced Tutorials This tutorial series is designed for everyone: even if
Articles you've never programmed before or if you have
Challenges extensive experience programming in other languages
Tips and Tricks and want to expand into C++! It is for everyone who
Jobs wants the feeling of accomplishment from a working
program.
Resources
Source Code
Syntax Reference
Getting
Snippets
Links Directory
Glossary
Set Up - C++
Book Reviews
Function Lookup Compilers
The very first thing you need to do, before starting
Questions
out in C++, is to make sure that you have a compiler.
Programming FAQ What is a compiler, you ask? A compiler turns the
Message Board
program that you write into an executable that your
Ask an Expert
computer can actually understand and run. If you're
Email
About Us taking a course, you probably have one provided
through your school. If you're starting out on your
own, your best bet is to use Code::Blocks. Our page
on setting up Code::Blocks will take you through
setting up the Code::Blocks compiler in great detail.
Advanced Compiler
Details
If you've got some prior experience, or just want a
menu of choices, you should know that there are
several common compilers. If you're new to
programming, just skip this section!
Intro to the C+
+ Language
A C++ program is a collection of commands, which
tell the computer to do "something". This collection of
commands is usually called C++ source code,
source code or just code. Commands are either
"functions" or "keywords". Keywords are a basic
building block of the language, while functions are, in
fact, usually written in terms of simpler functions--
you'll see this in our very first program, below.
(Confused? Think of it a bit like an outline for a book;
the outline might show every chapter in the book;
each chapter might have its own outline, composed of
sections. Each section might have its own outline, or
it might have all of the details written up.) Thankfully,
C++ provides a great many common functions and
keywords that you can use.
#include <iostream>
int main()
{
cout<<"HEY, you, I'm alive! Oh, and Hello
World!\n";
cin.get();
}
Let's look at the elements of the program. The
#include is a "preprocessor" directive that tells the
compiler to put code from the header called iostream
into our program before actually creating the
executable. By including header files, you gain access
to many different functions. For example, the cout
function requires iostream. Following the include is
the statement, "using namespace std;". This line tells
the compiler to use a group of functions that are part
of the standard library (std). By including this line at
the top of a file, you allow the program to use
functions such as cout. The semicolon is part of the
syntax of C++. It tells the compiler that you're at the
end of a command. You will see later that the
semicolon is used to end most commands in C++.
#include <iostream>
int main()
{
cout<<"HEY, you, I'm alive! Oh, and Hello
World!\n";
cin.get();
return 1;
}
The final brace closes off the function. You should try
compiling this program and running it. You can cut
and paste the code into a file, save it as a .cpp file.
Our Code::Blocks tutorial actually takes you through
creating a simple program, so check it out if you're
confused.
An Aside on
Commenting
Your Programs
As you are learning to program, you should also start
to learn how to explain your programs (for yourself, if
no one else). You do this by adding comments to
code; I'll use them frequently to help explain code
examples.
User interaction
and Saving
Information
with Variables
So far you've learned how to write a simple program
to display information typed in by you, the
programmer, and how to describe your program with
comments. That's great, but what about interacting
with your user? Fortunately, it is also possible for
your program to accept input. The function you use is
known as cin, and is followed by the insertion
operator >>.
Declaring Variables
in C++
To declare a variable you use the syntax "type
<name>;". Here are some variable declaration
examples:
int x;
char letter;
float the_float;
It is permissible to declare multiple variables of the
same type on the same line; each one should be
separated by a comma.
int a, b, c, d;
If you were watching closely, you might have seen
that declaration of a variable is always followed by a
semicolon (note that this is the same procedure used
when you call a function).
Case Sensitivity
Now is a good time to talk about an important
concept that can easily throw you off: case sensitivity.
Basically, in C++, whether you use uppercase or
lowercase letters matters. The words Cat and cat
mean different things to the compiler. In C++, all
language keywords, all functions and all variables are
case sensitive. A difference in case between your
variable declaration and the use of the variable is one
reason you might get an undeclared variable error.
Using Variables
Ok, so you now know how to tell the compiler about
variables, but what about using them?
#include <iostream>
int main()
{
int thisisanumber;
Changing and
Comparing Variables
Of course, no matter what type you use, variables are
uninteresting without the ability to modify them.
Several operators used with variables include the
following: *, -, +, /, =, ==, >, <. The * multiplies,
the - subtracts, and the + adds. It is of course
important to realize that to modify the value of a
variable inside the program it is rather important to
use the equal sign. In some languages, the equal sign
compares the value of the left and right values, but in
C++ == is used for that task. The equal sign is still
extremely useful. It sets the left input to the equal
sign, which must be one, and only one, variable equal
to the value on the right side of the equal sign. The
operators that perform mathematical functions should
be used on the right side of an equal sign in order to
assign the result to a variable on the left side.
For example:
Name
Search
Search:
login: sign in
[register]
remember me
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Documentation
Ascii Codes
Boolean Operations
Numerical Bases
Introduction:
Basics of C++:
· Structure of a program
· Constants
· Operators
· Basic Input/Output
Control Structures:
· Control Structures
· Functions (I)
· Functions (II)
· Arrays
· Character Sequences
· Pointers
· Dynamic Memory
· Data Structures
Object Oriented
Programming:
· Classes (I)
· Classes (II)
· Polymorphism
Advanced Concepts:
· Templates
· Namespaces
· Exceptions
· Type Casting
· Preprocessor directi...
Arrays
Published by Juan Soulie
Last update on Sep 29, 2009 at 10:53am UTC
An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an
index to a unique identifier.
That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with
int for example, with a unique
a different identifier. Instead of that, using an array we can store 5 different values of the same type,
identifier.
For example, an array to contain 5 integer values of type int called billy could be represented like this:
where each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered
from 0 to 4 since in arrays the first index is always 0, independently of its length.
Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:
where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always enclosed in
square brackets[]), specifies how many of these elements the array has to contain.
Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as:
Initializing arrays.
When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be
initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static
arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled
with zeros.
In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by
enclosing the values in braces { }. For example:
The amount of values between braces{ } must not be larger than the number of elements that we declare for the array between square
brackets[ ]. For example, in the example of array billy we have declared that it has 5 elements and in the list of initial values within
braces { } we have specified 5 values, one for each element.
When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty [ ]. In this case,
the compiler will assume a size for the array that matches the number of values included between braces { }:
After this declaration, array billy would be 5 ints long, since we have provided 5 initialization values.
name[index]
Following the previous examples in which billy had 5 elements and each of those elements was of type int, the name which we can
use to refer to each element is the following:
For example, to store the value 75 in the third element of billy, we could write the following statement:
billy[2] = 75;
and, for example, to pass the value of the third element of billy to a variable called a, we could write:
a = billy[2];
Therefore, the expression billy[2] is for all purposes like a variable of type int.
Notice that the third element ofbilly is specified billy[2], since the first one is billy[0], the second one is
billy[1], and therefore, the third one is billy[2]. By this same reason, its last element is billy[4]. Therefore, if we
write billy[5], we would be accessing the sixth element of billy and therefore exceeding the size of the array.
In C++ it is syntactically correct to exceed the valid range of indices for an array. This can create problems, since accessing out-of-range
elements do not cause compilation errors but can cause runtime errors. The reason why this is allowed will be seen further ahead when we
begin to use pointers.
At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related to arrays. They perform
two different tasks: one is to specify the size of arrays when they are declared; and the second one is to specify indices for concrete array
elements. Do not confuse these two possible uses of brackets [ ] with arrays.
If you read carefully, you will see that a type specifier always precedes a variable or array declaration, while it never precedes an access.
1 billy[0] = a;
2 billy[a] = 75;
3 b = billy [a+2];
4 billy[billy[a]] = billy[2] + 5;
Multidimensional arrays
Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a bidimensional table
made of elements, all of them of a same uniform data type.
jimmy represents a bidimensional array of 3 per 5 elements of type int. The way to declare this array in C++ would be:
and, for example, the way to reference the second element vertically and fourth horizontally in an expression would be:
jimmy[1][3]
Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many indices as needed. But be careful! The
amount of memory needed for an array rapidly increases with each dimension. For example:
declares an array with a char element for each second in a century, that is more than 3 billion chars. So this declaration would consume
more than 3 gigabytes of memory!
Multidimensional arrays are just an abstraction for programmers, since we can obtain the same results with a simple array just by putting a
factor between its indices:
None of the two source codes above produce any output on the screen, but both assign values to the memory block called jimmy in the
following way:
We have used "defined constants" ( #define) to simplify possible future modifications of the program. For example, in case that we
decided to enlarge the array to a height of 4 instead of 3 it could be done simply by changing the line:
#define HEIGHT 3
to:
#define HEIGHT 4
Arrays as parameters
At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory
by value as a parameter to a function, but we are allowed to pass its address. In practice this has almost the same effect and it is a much
faster and more efficient operation.
In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the
element type of the array, an identifier and a pair of void brackets []. For example, the following function:
accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as:
procedure (myarray);
As you can see, the first parameter ( int arg[] ) accepts any array whose elements are of type int
, whatever its length. For that
reason we have included a second parameter that tells the function the length of each array that we pass to it as its first parameter. This
allows the for loop that prints out the array to know the range to iterate in the passed array without going out of range.
In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional array parameter is:
base_type[][depth][depth]
Notice that the first brackets [] are left blank while the following ones are not. This is so because the compiler must be able to determine
within the function which is the depth of each additional dimension.
Arrays, both simple or multidimensional, passed as function parameters are a quite common source of errors for novice programmers. I
recommend the reading of the chapter about Pointers for a better understanding on how arrays operate.
Previous:Previous: Next:Next:
Previous: Next:
Functions (II) index Character Sequences