COMPUTER SCIENCE
Friday, December 19, 2014
Wednesday, October 1, 2014
Friday, September 26, 2014
Computer History Museum: Celebrating 35 Years
The Computer History Museum marks its 35th birthday on September 24th. Visitors from around the world see an impressive set of exhibits, but the history of the institution and its collection is almost as interesting as a visit to the Museum itself.
The Museum has come a long way from a coat closet in Massachusetts to the beautiful multi-building permanent facility that today houses engaging exhibits and the largest collection of computing artifacts in the world.
Join us as Museum co-founder Gordon Bell and Museum Chairman Len Shustek discuss with Museum President and CEO John Hollar the making of the leading museum devoted to the computing and its impact on society.
The Museum has come a long way from a coat closet in Massachusetts to the beautiful multi-building permanent facility that today houses engaging exhibits and the largest collection of computing artifacts in the world.
Join us as Museum co-founder Gordon Bell and Museum Chairman Len Shustek discuss with Museum President and CEO John Hollar the making of the leading museum devoted to the computing and its impact on society.
Thursday, September 25, 2014
Welcome
We created this website to teach participant programmers, even those with a poor base, how to use HTML but not only. We invite you to start the programming course right away. But first, "the menu"...
- Beginner`s guide - For those of you who are beginners in the way of creating a web page
- HTML Tutorials - For those of you who start the creation of web pages with some HTML base
This series of tutorials is made to give you some experience, so that you can be capable to read and write in HTML, to be able to save documents and after that to see your work in a web browser. Unfortunately this page does not have a rubric for teaching you how to use all base functions of an computer, so in this point of view you can ask for help to a friend of yours so that you will be helped in :
- Knowing what is an notepad and how to use it
- Knowing how to open a file using internet Explorer(or any other
browser, you can choose it ) - Knowing how yo make and what represents a copy/paste
First web page
For the beginning copy next HTML cod in notepad. Assure that the operation
is right executed or the page will not function.
is right executed or the page will not function.
<html>
<head>
</head>
<body> <h2>My first web page !</h2>
</body>
</html>
|
Thee upper code, is all you need to create a simple web page. Now you can save the document in notepad selecting from File menu the Save As option. In the new opened window, select All Files. We will give a name to the file, for example "index.html", without using the quotation marks. Check twice before you push the Save button. I will ask you to try to remember where you have saved the file because we will work with this file a bit later.
How to see your first web pages - Browsers
So that you can see your web page, you should use a browser. Browsers are those internet programs who interpret HTML cods, similar with those you have copied and saved in notepad. These transforms the HTML cod in a web page that can be read by any internet user. The most used browsers are:
- Internet Explorer
- Fire Fox
- Opera
- Netscape Navigator
How to see your first web page
If you want to see your web page, you have to open "index.html" file in a browser.In this way, open a new Internet Explorer window and follow my instructions:
- From File select Open
- Click on Browse so that you open Windows Explorer
- Do you remember where you have saved the file? Very well, there
you must go. - When you found it do a double-click to open it
Congratulation ! YOu have just opened your first web page.
HTML DESCRIPTION
Description
This program demonstrates the every function of the Icon programming language by displaying the sum of the numbers from 1 to 100.Source Code
procedure main()
local n, sum # Declare two local variables
sum := 0; # Set the sum to zero
every n := 1 to 100 do # For n equal to 1, 2, 3, 4, 5 ...
sum := sum + n; # ...add n to the sum
write ( "The sum of all numbers from 1 to 100 is ", sum );
end
Click here to download a zip file containing the source code.Sample Run
The sum of all numbers from 1 to 100 is 5050
Click here to download a zip file containing the executable for MS-DOS.Program Notes
This program was implemented using Version 9.1 of Icon for MS-DOS.HTML WRITE (RUN)
Description
This program prints the phrase "Hello World"Source Code
<HTML>
<HEAD>
<TITLE>Hello World in HTML</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Hello World!</H1></CENTER>
</BODY>
</HTML>
Sample Run
Hello World!
HISTORY
History
HTML, which stands for HyperText Mark-Up Language, is the language for describing structured documents as well as the language used to create web pages in the Internet. The language is based on an existing, international formatting standard SGML, Standard Generalized Mark-Up Language, which is used for text processing. HTML is a simplified version of SGML.Significant Language Features
HTML files are written in ACSII text, so the user can use any text editor to create his/her web page, though a browser of one sort or another is necessary to view the web page. HTML is case insensitive with its language commands. The characters within the document, however, are case sensitive. The language consists of various "tags" which are known as elements. These allow the browser to understand (and put into the desired/specified format) the layout, background, headings, titles, lists, text and/or graphics on the page. The elements are classified according to their function in the HTML document. There are head elements and body elements. The head elements identify properties of the entire document, while body elements actually mark text as content and show a change in the appearance in one way or another. Most elements have a beginningAreas of Application
HTML only has one area of application at this time and that is the development of web pages. However, not all browsers support all the tags in all versions of HTML. Because of this, it is wise not to design your web page for a specific browser, because what may look fantastic on your browser has no guarantee of looking great on someone else's browser.HTML
HTML
HTML stands for Hypertext Markup Language.HTML files are basically special text files:
- Contain special control sequences or tags that control how text is to be formatted.
- HTML files are the ``source code'' for Web Browsers
- A browser reads the HTML file and
- Tries to display it using the tags to control layout.
- Titles
- Heading Levels
- Styles of font (e.g Bold, Italic)
- Lists and list items
- Hypertext links to other URLs and files.
Hypertext Terminology
Below is listed some common terms you will need to become familiar with:- Page
- - Refers to a single HTML file. Sometimes referred to as a document
- Home page
- - Refers to a designated entry point for access to a local web
- Hot spot
- - A region of displayed hypertext that, when selected, links the user to another location
- web
- - A set of hypertext pages considered to be a single work
- Web or WWW
- - the union of all hypertext on all Web servers worldwide
Creating HTML Documents
HTML files are Plain text (ascii) format, created using any text editor.
Many WYSIWYG HTML editors exist, e.g. Claris Home Page, Macromedia Dreamweaver. Netscape Communicator also has a built in editor.
It is however recommended that you at least learn the basics of HTML tagging before you dive into WYSIWYG editing as this mask the programming issues and ultimately hinders the learning process.
C PROGRAMME
PROGRAMMING
c mouse programs
Mouse programs using c :- Do everything with mouse using these c programs or source codes, on this page you will find sample mouse programs using c. Programs ranging from how to use mouse in c graphics and in text mode. how to initialize mouse, how to know where the mouse is clicked, which mouse button is clicked i.e left or right, how to restrict mouse pointer. Below is a list of mouse programs made using c language. Mouse interrupt is handled using int86 function of dos.h header file. All these programs have been made using turbo c compiler.
C programming examples
C programming examples: These programs illustrate various programming elements, concepts such as using operators, loops, functions, single and double dimensional arrays, performing operations on strings, files, pointers etc. Browse the code from simple c program to complicated ones you are looking for, every one of them is provided with output. C program download with executable files, so that you save on your computer and run programs without compiling the source code. All programs are made using c programming language and Codeblocks, most of these will work under Dev C++ compiler also. Download software you need to develop codes. The first program prints "Hello World" on screen.
C programming codes
Hello world
Print Integer
Addition
Odd or Even
Add, subtract, multiply and divide
Check vowel
Leap year
C program examples
Example 1 - C hello world program
/* A very simple c program printing a string on screen*/
#include <stdio.h>
main()
{
printf("Hello World\n");
return 0;
}
Output of above program:
"Hello World"
Example 2 - c program to take input from user using scanf
#include <stdio.h>
main()
{
int number;
printf("Enter an integer\n");
scanf("%d",&number);
printf("Integer entered by you is %d\n", number);
return 0;
}
Output:
Enter a number
5
Number entered by you is 5
Example 3 - using if else control instructions
#include <stdio.h>
main()
{
int x = 1;
if ( x == 1 )
printf("x is equal to one.\n");
else
printf("For comparison use == as = is the assignment operator.\n");
return 0;
}
Output:
x is equal to one.
Example 4 - loop example
#include <stdio.h>
main()
{
int value = 1;
while(value<=3)
{
printf("Value is %d\n", value);
value++;
}
return 0;
}
Output:
Value is 1
Value is 2
Value is 3
Example 5 - c program for prime number
#include <stdio.h>
main()
{
int n, c;
printf("Enter a number\n");
scanf("%d", &n);
if ( n == 2 )
printf("Prime number.\n");
else
{
for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n % c == 0 )
break;
}
if ( c != n )
printf("Not prime.\n");
else
printf("Prime number.\n");
}
return 0;
}
Example 6 - command line arguments
#include <stdio.h>
main(int argc, char *argv[])
{
int c;
printf("Number of command line arguments passed: %d\n", argc);
for ( c = 0 ; c < argc ; c++)
printf("%d. Command line argument passed is %s\n", c+1, argv[c]);
return 0;
}
Above c program prints the number and all arguments which are passed to it.
Example 7 - Array program
#include <stdio.h>
main()
{
int array[100], n, c;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
printf("Array elements entered by you are:\n");
for ( c = 0 ; c < n ; c++ )
printf("array[%d] = %d\n", c, array[c]);
return 0;
}
Example 8 - function program
#include <stdio.h>
void my_function();
main()
{
printf("Main function.\n");
my_function();
printf("Back in function main.\n");
return 0;
}
void my_function()
{
printf("Welcome to my function. Feel at home.\n");
}
Example 9 - Using comments in a program
#include <stdio.h>
main()
{
// Single line comment in c source code
printf("Writing comments is very useful.\n");
/*
* Multi line comment syntax
* Comments help us to understand code later easily.
* Will you write comments while developing programs ?
*/
printf("Good luck c programmer.\n");
return 0;
}
Example 10 - using structures in c programming
#include <stdio.h>
struct programming
{
float constant;
char *pointer;
};
main()
{
struct programming variable;
char string[] = "Programming in Software Development.";
variable.constant = 1.23;
variable.pointer = string;
printf("%f\n", variable.constant);
printf("%s\n", variable.pointer);
return 0;
}
Example 11 - c program for Fibonacci series
#include <stdio.h>
main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}
Example 12 - c graphics programming
#include <graphics.h>
#include <conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm,"C:\\TC\\BGI");
outtextxy(10,20, "Graphics source code example.");
circle(200, 200, 50);
setcolor(BLUE);
line(350, 250, 450, 50);
getch();
closegraph( );
return 0;
}
For GCC users
If you are using GCC on Linux operating system then you need to modify programs. For example consider the following program which prints first ten natural numbers
#include <stdio.h>
#include <conio.h>
int main()
{
int c;
for ( c = 1 ; c <= 10 ; c++ )
printf("%d\n", c);
getch();
return 0;
}
Above source code includes a header file <conio.h> and uses function getch, but this file is Borland specific so it works in turbo c compiler but not in GCC. So the code for GCC should be like
#include <stdio.h>
int main()
{
int c;
/* for loop */
for ( c = 1 ; c <= 10 ; c++ )
printf("%d\n", c);
return 0;
}
If using GCC then save the code in a file say “numbers.c”, to compile the program open the terminal and enter command “gcc numbers.c”, this will compile the program and to execute the program enter command “./a.out”, do not use quotes while executing commands.
C programming tutorial
C program consists of functions and declarations or instructions given to the computer to perform a particular task. The process of writing a program involves designing the algorithm, a flowchart may also be drawn, and then writing the source code, after developing the program you need to test it and debug it if it does not meet the requirement. To make a program you need a text editor and a compiler. You can use any text editor of your choice and a compiler. C compiler converts source code into machine code that consists of zero and one only and directly executed on machine. An IDE or Integrated Development Environment provides a text editor, compiler, debugger etc. for developing programs or projects.Download Codeblocks IDE it provides an ideal environment for development. It can import Microsoft Visual C++ projects, extendable as it uses plug-ins, open source and cross platform.
A c program must have at least one function which is main, function consists of declaration and statements, a statement is an expression followed by a semicolon, for example a + b, printf("c program examples") are expressions and a + b; and printf("C is an easy to learn computer programming language."); are statements. To use a variable we must indicate its type whether it is an integer, float, character. C language has many built in data types and we can make our own using structures and unions. Every data type has its own size that may depend on machine for example an integer may be of 2 or 4 Bytes. Data is stored in binary form i.e. group of bits where each bit may be '0' or '1'. Keywords such as switch, case, default, register etc. are special words with predefined meaning and can't be used for other purposes. Memory can be allocated during compile time or at run time using malloc or calloc. C language has many features such as recursion, preprocessor, conditional compilation, portability, pointers, multi threading by using external libraries, dynamic memory allocation due to which it is used for making portable software programs and applications. Networking API's are available using which computer users can communicate and interact with each other, share files etc. C standard library offers functions for mathematical operations, character strings and input/output and time. The process of making programs which is known as coding requires knowledge of programming language and logic to achieve the desired output. So you should learn c programming basics and start making programs. Learning data structures such as stacks, queues, linked lists etc. using c programming provides you a greater understanding as you learn everything in detail. General belief is to go for other high level languages but it's a good idea to learn c before learning C++ or Java. C++ programming language is object oriented and it contains all the features of c language so learning c first will help you to easily learn C++ and then you can go for Java programming.
C programming books
If you are a beginner then buy anyone of first two books mentioned below and if you have previous programming experience or you know basics of c language then you can buy third one.
C hello world program
C hello world program: c programming language code to print hello world. This program prints hello world, printf library function is used to display text on screen, '\n' places cursor on the beginning of next line, stdio.h header file contains declaration of printf function. The code will work on all operating systems may be its Linux, Mac or any other and compilers. To learn a programming language you must start writing programs in it and may be your first c code while learning programming.
Hello world in C language
//C hello world example
#include <stdio.h>
int main()
{
printf("Hello world\n");
return 0;
}
Purpose of Hello world program may be to say hello to people or the users of your software or application.
C hello world program output
Add caption
Output of program:
Hello world program in c
We may store "hello world" in a character array as a string constant and then print it.
#include <stdio.h>
int main()
{
char string[] = "Hello World";
printf("%s\n", string);
return 0;
}
Don't worry if you didn't understand above code as you may not be familiar with arrays yet.
Printing hello world indefinitely
Using loop we can print "Hello World" a desired number of time or indefinitely.
#include <stdio.h>
#define TRUE 1
int main()
{
while (TRUE)
{
printf("Hello World\n");
}
return 0;
}
While loop will execute forever until it is terminated, to terminate press (Ctrl + C) in windows operating system.
C program print integer
This c program first inputs an integer and then prints it. Input is done using scanf function and number is printed on screen using printf.
C programming code
#include <stdio.h>
int main()
{
int a;
printf("Enter an integer\n");
scanf("%d", &a);
printf("Integer that you have entered is %d\n", a);
return 0;
}
Download integer program.
Output of program:
input number
In c language we have data type for different types of data, for integer data it is int, for character date char, for floating point data it's float and so on.
C program to add two numbers
C program to add two numbers: This c language program perform the basic arithmetic operation of addition on two numbers and then prints the sum on the screen. For example if the user entered two numbers as 5, 6 then 11 (5 + 6) will be printed on the screen.
C programming code
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d",&a,&b);
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
Download Add numbers program executable.
Output of program:
add numbers
Addition without using third variable
#include<stdio.h>
main()
{
int a = 1, b = 2;
/* Storing result of addition in variable a */
a = a + b;
/* Not recommended because original value of a is lost
* and you may be using it somewhere in code considering it
* as it was entered by the user.
*/
printf("Sum of a and b = %d\n", a);
return 0;
}
C program to add two numbers repeatedly
#include<stdio.h>
main()
{
int a, b, c;
char ch;
while(1)
{
printf("Enter values of a and b\n");
scanf("%d%d",&a,&b);
c = a + b;
printf("a + b = %d\n", c);
printf("Do you wish to add more numbers(y/n)\n");
scanf(" %c",&ch);
if ( ch == 'y' || ch == 'Y' )
continue;
else
break;
}
return 0;
}
Adding numbers in c using function
#include<stdio.h>
long addition(long, long);
main()
{
long first, second, sum;
scanf("%ld%ld", &first, &second);
sum = addition(first, second);
printf("%ld\n", sum);
return 0;
}
long addition(long a, long b)
{
long result;
result = a + b;
return result;
}
We have used long data type as it can handle large numbers, if you want to add still larger numbers which doesn't fit in long range then use array, string or other data structure.
c program to check odd or even
c program to check odd or even: We will determine whether a number is odd or even by using different methods all are provided with a code in c language. As you have study in mathematics that in decimal number system even numbers are divisible by 2 while odd are not so we may use modulus operator(%) which returns remainder, For example 4%3 gives 1 ( remainder when four is divided by three). Even numbers are of the form 2*p and odd are of the form (2*p+1) where p is is an integer.
C program to check odd or even using modulus operator
#include<stdio.h>
main()
{
int n;
printf("Enter an integer\n");
scanf("%d",&n);
if ( n%2 == 0 )
printf("Even\n");
else
printf("Odd\n");
return 0;
}
We can use bitwise AND (&) operator to check odd or even, as an example consider binary of 7 (0111) when we perform 7 & 1 the result will be one and you may observe that the least significant bit of every odd number is 1, so ( odd_number & 1 ) will be one always and also ( even_number & 1 ) is zero.
C program to check odd or even using bitwise operator
#include<stdio.h>
main()
{
int n;
printf("Enter an integer\n");
scanf("%d",&n);
if ( n & 1 == 1 )
printf("Odd\n");
else
printf("Even\n");
return 0;
}
Find odd or even using conditional operator
#include<stdio.h>
main()
{
int n;
printf("Input an integer\n");
scanf("%d",&n);
n%2 == 0 ? printf("Even\n") : printf("Odd\n");
return 0;
}
C program to check odd or even without using bitwise or modulus operator
#include<stdio.h>
main()
{
int n;
printf("Enter an integer\n");
scanf("%d",&n);
if ( (n/2)*2 == n )
printf("Even\n");
else
printf("Odd\n");
return 0;
}
In c programming language when we divide two integers we get an integer result, For example the result of 7/3 will be 2.So we can take advantage of this and may use it to find whether the number is odd or even. Consider an integer n we can first divide by 2 and then multiply it by 2 if the result is the original number then the number is even otherwise the number is odd. For example 11/2 = 5, 5*2 = 10 ( which is not equal to eleven), now consider 12/2 = 6 and 6 *2 = 12 ( same as original number). These are some logic which may help you in finding if a number is odd or not.
C program to perform addition, subtraction, multiplication and division
C program to perform basic arithmetic operations which are addition, subtraction, multiplication and division of two numbers. Numbers are assumed to be integers and will be entered by the user.
C programming code
#include <stdio.h>
int main()
{
int first, second, add, subtract, multiply;
float divide;
printf("Enter two integers\n");
scanf("%d%d", &first, &second);
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / (float)second; //typecasting
printf("Sum = %d\n",add);
printf("Difference = %d\n",subtract);
printf("Multiplication = %d\n",multiply);
printf("Division = %.2f\n",divide);
return 0;
}
Output of program:
arithmetic operations program
In c language when we divide two integers we get integer result for example 5/2 evaluates to 2. As a general rule integer/integer = integer and float/integer = float or integer/float = float. So we convert denominator to float in our program, you may also write float in numerator. This explicit conversion is known as typecasting.
C program to check whether input alphabet is a vowel or not
This code checks whether an input alphabet is a vowel or not. Both lower-case and upper-case are checked.
C programming code
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U')
printf("%c is a vowel.\n", ch);
else
printf("%c is not a vowel.\n", ch);
return 0;
}
Output of program:
check vowel
Check vowel using switch statement
#include <stdio.h>
int main()
{
char ch;
printf("Input a character\n");
scanf("%c", &ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("%c is a vowel.\n", ch);
break;
default:
printf("%c is not a vowel.\n", ch);
}
return 0;
}
Function to check vowel
int check_vowel(char a)
{
if (a >= 'A' && a <= 'Z')
a = a + 'a' - 'A'; /* Converting to lower case or use a = a + 32 */
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
return 1;
return 0;
}
This function can also be used to check if a character is a consonant or not, if it's not a vowel then it will be a consonant, but make sure that the character is an alphabet not a special character.
C program to check leap year
C program to check leap year: c code to check leap year, year will be entered by the user.
C programming code
#include <stdio.h>
int main()
{
int year;
printf("Enter a year to check if it is a leap year\n");
scanf("%d", &year);
if ( year%400 == 0)
printf("%d is a leap year.\n", year);
else if ( year%100 == 0)
printf("%d is not a leap year.\n", year);
else if ( year%4 == 0 )
printf("%d is a leap year.\n", year);
else
printf("%d is not a leap year.\n", year);
return 0;
}
.
Output of program:
leap year program
Please read the leap year article at Wikipedia, it will help you to understand the program. This code is based on Gregorian Calendar.
c++
What is a compiler?
Computers understand only one language and that language consists of sets of instructions made of ones and zeros. This computer language is appropriately called machine language.A single instruction to a computer could look like this:
00000 | 10011110 |
A particular computer's machine language program that allows a user to input two numbers, adds the two numbers together, and displays the total could include these machine code instructions:
00000 | 10011110 |
00001 | 11110100 |
00010 | 10011110 |
00011 | 11010100 |
00100 | 10111111 |
00101 | 00000000 |
As you can imagine, programming a computer directly in machine language using only ones and zeros is very tedious and error prone. To make programming easier, high level languages have been developed. High level programs also make it easier for programmers to inspect and understand each other's programs easier.
This is a portion of code written in C++ that accomplishes the exact same purpose:
|
|
Even if you cannot really understand the code above, you should be able to appreciate how much easier it will be to program in the C++ language as opposed to machine language.
Because a computer can only understand machine language and humans wish to write in high level languages high level languages have to be re-written (translated) into machine language at some point. This is done by special programs called compilers, interpreters, or assemblers that are built into the various programming applications.
C++ is designed to be a compiled language, meaning that it is generally translated into machine language that can be understood directly by the system, making the generated program highly efficient. For that, a set of tools are needed, known as the development toolchain, whose core are a compiler and its linker.
Console programs
Console programs are programs that use text to communicate with the user and the environment, such as printing text to the screen or reading input from a keyboard.Console programs are easy to interact with, and generally have a predictable behavior that is identical across all platforms. They are also simple to implement and thus are very useful to learn the basics of a programming language: The examples in these tutorials are all console programs.
The way to compile console programs depends on the particular tool you are using.
The easiest way for beginners to compile C++ programs is by using an Integrated Development Environment (IDE). An IDE generally integrates several development tools, including a text editor and tools to compile programs directly from it.
Here you have instructions on how to compile and run console programs using different free Integrated Development Interfaces (IDEs):
IDE | Platform | Console programs |
---|---|---|
Code::blocks | Windows/Linux/MacOS | Compile console programs using Code::blocks |
Visual Studio Express | Windows | Compile console programs using VS Express 2013 |
Dev-C++ | Windows | Compile console programs using Dev-C++ |
If you happen to have a Linux or Mac environment with development features, you should be able to compile any of the examples directly from a terminal just by including C++11 flags in the command for the compiler:
Compiler | Platform | Command |
---|---|---|
GCC | Linux, among others... | g++ -std=c++0x example.cpp -o example_program |
Clang | OS X, among others... | clang++ -std=c++11 -stdlib=libc++ example.cpp -o example_program |
Structure of a program
|
| Hello World!
|
The left panel above shows the C++ code for this program. The right panel shows the result when the program is executed by a computer. The grey numbers to the left of the panels are line numbers to make discussing programs and researching errors easier. They are not part of the program.
Let's examine this program line by line:
- Line 1:
// my first program in C++
- Two slash signs indicate that the rest of the line is a comment inserted by the programmer but which has no effect on the behavior of the program. Programmers use them to include short explanations or observations concerning the code or program. In this case, it is a brief introductory description of the program.
- Line 2:
#include <iostream>
- Lines beginning with a hash sign (
#
) are directives read and interpreted by what is known as the preprocessor. They are special lines interpreted before the compilation of the program itself begins. In this case, the directive#include <iostream>
, instructs the preprocessor to include a section of standard C++ code, known as header iostream, that allows to perform standard input and output operations, such as writing the output of this program (Hello World) to the screen. - Line 3: A blank line.
- Blank lines have no effect on a program. They simply improve readability of the code.
- Line 4:
int main ()
- This line initiates the declaration of a function. Essentially, a function is a group of code statements which are given a name: in this case, this gives the name "main" to the group of code statements that follow. Functions will be discussed in detail in a later chapter, but essentially, their definition is introduced with a succession of a type (
int
), a name (main
) and a pair of parentheses (()
), optionally including parameters.
The function namedmain
is a special function in all C++ programs; it is the function called when the program is run. The execution of all C++ programs begins with themain
function, regardless of where the function is actually located within the code. - Lines 5 and 7:
{
and}
- The open brace (
{
) at line 5 indicates the beginning ofmain
's function definition, and the closing brace (}
) at line 7, indicates its end. Everything between these braces is the function's body that defines what happens whenmain
is called. All functions use braces to indicate the beginning and end of their definitions. - Line 6:
std::cout << "Hello World!";
- This line is a C++ statement. A statement is an expression that can actually produce some effect. It is the meat of a program, specifying its actual behavior. Statements are executed in the same order that they appear within a function's body.
This statement has three parts: First,std::cout
, which identifies the standard character output device (usually, this is the computer screen). Second, the insertion operator (<<
), which indicates that what follows is inserted intostd::cout
. Finally, a sentence within quotes ("Hello world!"), is the content inserted into the standard output.
Notice that the statement ends with a semicolon (;
). This character marks the end of the statement, just as the period ends a sentence in English. All C++ statements must end with a semicolon character. One of the most common syntax errors in C++ is forgetting to end a statement with a semicolon.
You may have noticed that not all the lines of this program perform actions when the code is executed. There is a line containing a comment (beginning with
//
). There is a line with a directive for the preprocessor (beginning with #
). There is a line that defines a function (in this case, the main
function). And, finally, a line with a statements ending with a semicolon (the insertion into cout
), which was within the block delimited by the braces ( { }
) of the main
function.The program has been structured in different lines and properly indented, in order to make it easier to understand for the humans reading it. But C++ does not have strict rules on indentation or on how to split instructions in different lines. For example, instead of
|
|
We could have written:
|
|
all in a single line, and this would have had exactly the same meaning as the preceding code.
In C++, the separation between statements is specified with an ending semicolon (
;
), with the separation into different lines not mattering at all for this purpose. Many statements can be written in a single line, or each statement can be in its own line. The division of code in different lines serves only to make it more legible and schematic for the humans that may read it, but has no effect on the actual behavior of the program.Now, let's add an additional statement to our first program:
|
| Hello World! I'm a C++ program
|
In this case, the program performed two insertions into
std::cout
in two different statements. Once again, the separation in different lines of code simply gives greater readability to the program, since main
could have been perfectly valid defined in this way:
|
|
The source code could have also been divided into more code lines instead:
|
|
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by
#
) are out of this general rule since they are not statements. They are lines read and processed by the preprocessor before proper compilation begins. Preprocessor directives must be specified in their own line and, because they are not statements, do not have to end with a semicolon (;
).
Subscribe to:
Posts (Atom)
Comments
As noted above, comments do not affect the operation of the program; however, they provide an important tool to document directly within the source code what the program does and how it operates.C++ supports two ways of commenting code:
The first of them, known as line comment, discards everything from where the pair of slash signs (
//
) are found up to the end of that same line. The second one, known as block comment, discards everything between the/*
characters and the first appearance of the*/
characters, with the possibility of including multiple lines.Let's add comments to our second program:
Hello World! I'm a C++ program
If comments are included within the source code of a program without using the comment characters combinations
//
,/*
or*/
, the compiler takes them as if they were C++ expressions, most likely causing the compilation to fail with one, or several, error messages.