Всякий начинающиий программист после изучения некоторых основ языка программирования, будь то C++, Pascal, Assembler, обязательно хочет написать свою первую программу. По устоявшейся традиции этой программой в большинстве случаев является приложение, выводяшее на экране монитора надпись "Hello world!" Итак, приступим к написанию первой программы! Первым шагом в написании программы является запуск самой среды программирования C++ Builder (Исходный текст программы приведен для версии 6.0). Затем выберем FileNewOther... Вы попадете в окно выбора типа вашего проекта (Это может быть как приложение под платформы DOSWindows, либо DLL библиотеки или иные компоненты). Внешний вид открывшегося окна показан на рисунке ниже:
Все объекты орбъединены в следующие группы:
New - встроенные базовые объекты, используемые при разработке приложений.
ActiveX - объекты COM и OLE, элементы ActiveX, активные серверные страницы (ASP).
Multiter - объекты многопоточного приложения (CORBA и др.)
Project1 - формы создаваемого приложения.
Forms - формы.
Dialogs - диалоговые окна (открытие файла, диалог печати, сохранение и т.д.)
Projects - проекты одно- и многодокументных приложений.
Data Modules - модули данных.
Business - Мастера форм баз данных и Web-приложений.
Web Documents - Web-документы (HTML, XHTML, WML, XSL).
WebSnap - WebSnap-приложения и модули.
WebServices - приложение, модуль и интерфейс для SOAP.
IntraWeb - приложения и формы Web.
Corba - CORBA-приложения. Взглянув на рисунок окна, сразу понимаешь, что среда имеет богатейшие возможности выбора для разработки приложений. Итак, для создания консольного приложения необходимо выбрать в открывшемся окне Console Wizard и даблкликнуть на нем. Появится окно:
В окне все необходимые галочки уже стоят, однако поясню их назначение: Source Typy обозначает язык, на котором вы собираетесь создавать приложение. Use VCLCLX позваляет установить тип библиотеки, которую используем. Жмем Ok и получаем код, автоматически сгенерированный системой:
Разберемся, что-же автоматически сгенерировала нам среда:
#include <vcl.h> - директива, с помощью которой выполшняется включение текстовых фаилов (*.h, *.cpp и т.д.) в текст программы.
#pragma hdrstop - указывает компилятору, что в данном месте нужно прекратить генерацию предварительно вкомпилированных заголовочных файлов. Расположенные после директивы заголовочные файлы будут компилироваться при каждой компиляции данного модуля, а те что расположены выше - не будут. Перед этой директивой рекомендуется располагать те заголовочные файлы, которые являются общими для двух и более модулей, чтобы избежать их повторной компиляции. Включение данной директивы в коды больших проектов способствует уменьшению времени компиляции.
int main() - функция которая должна присутствовать во всех консольных приложениях.
Итак, все основные моменты данного кода мы разобрали, теперь перейдем к продолжению написания программы. Нам осталось добавить всего пару строк (добавленные строки выделены):
#include <iostream.h> - директива, необходимая для работы комманд ввода/вывода на экран.
cout<<"Hello world!"; - собственно сам вывод на экран строки Hello world!
Ну вот и все! Программа готова. Но: при запуске программы на компиляцию (кнопка F9) вы увидите, что на экране только мигнуло какое-то окно и все, поэтому добавим еще строку Sleep(1000); между cout и return 0; Sleep - задержка выполнения программы, в скобках указано время в милисекундах.
Список литературы
Программирование на С++. Учебное пособие под ред. А.Д.Хомоненко
Другие работы по теме:
Текст программы. 7 Используемые переменные. 7. Структура узла бинарного дерева. 7. Функция создания дерева. 7
Написать программу, читающую текст алгебраической формулы в инфиксной форме, включающей операции сложения, вычитания, умножения и деления, операнды (a, b, c, …, X, y, z) и круглые скобки
Программа для оценки шахматной ситуации
Разработка программы для оценки шахматной ситуации на доске с использованием графического интерфейса. Способы вывода результатов. Библиотека визуальных компонентов. Модульная структура приложения, его внешний вид. Последовательность работы с приложением.
Построение компоненты в Builder C++
Разработка компоненты C++ Builder, состоящей из двух окружностей, одна из которых движется по периметру другой. Создание установочного пакета и тестового приложения с использованием разработанного компонента. Инсталляция и проверка готовой компоненты.
Алгоритм, написание и отладка программы "Текстовый редактор"
Редактирование текста как очень важная часть оформления документов. Разработка программы по работе с текстом "Текстовый редактор" в среде разработки C++Builder 6 как приложения, использующегося в качестве замены встроенного редактора "WordPad".
Разработка электронного органайзера средствами C++ Builder 6
Реализация программного кода "Organizer 1.0". Разработка приложений баз данных с помощью Borland C++ Builder 6. Компоненты системы программирования для работы по технологии InterBase. Программный код и интерфейс "Organizer 1.0", структура приложения.
Разработка программы на четырех языках программирования
Этапы написания программы на четырех языках программирования (Turbo Pascal 7.0, Borland C++ 3.11, Delphi 7, Builder C++ 6.0), которая выводит на экран имя и фамилию студента, используя стандартные средства графики и простейшие геометрические фигуры.
Разработка визуальных компонентов для среды С++ Builder
C++ Builder - SDI-приложение, главное окно которого содержит настраиваемую инструментальную панель и палитру компонентов. Свойства атрибутов компонента, определяющие его внешний вид и поведение. События, методы и VCL компоненты в среде C++ Builder.
C++ Builder. Введение в структурное программирование
Создание консольных приложений с использованием графического интерфейса пользователя. Содержание палитры компонентов программы С++ Builder. Использование возможностей объектно-ориентированного программирования, особенности редактора кода и форм в С++.
Система обработки научных данных
Міністерство освіти і науки України ФАКУЛЬТЕТ ІНФОРМАТИКИ КАФЕДРА ІНФОРМАЦІЙНИХ УПРАВЛЯЮЧИХ СИСТЕМ ТА ТЕХНОЛОГІЙ Реєстраційний №________ Дата ___________________
Arnold
& Samson Essay, Research Paper Arnold Schwarzenegger: A Real Life Samson Heroes have been around since the beginning of time. The first hero that I can think of is David, from the biblical story David and Goliath. Heroes have not really evolved that much since the early days, they are still basically the same strong men with unhumanlike powers that the normal mortal man cannot even comprehend.
Arnold Schwarzenegger A Real Essay Research
Paper Bible as Literature Arnold Schwarzenegger: A Real Life Samson Heroes have been around since the beginning of time. The first hero that I can think of is David, from the biblical story David and Goliath. Heroes have not really evolved that much since the early days, they are still basically the same strong characters with inhuman like powers normal mortals can’t even comprehend.
James Jarome Hill Essay Research Paper James
James Jarome Hill Essay, Research Paper James Jarome Hill was born near Rockwood, Ontario in 1838. A boyhood accident that blinded him in one eye dashed his early dreams of becoming a doctor. He was forced to go to work at an early age due to the death of his father. At the age of 16, Hill went to St. Paul, Minnesota and took a job with a steamboat company.
Model Train Building And Computers Essay Research
Paper The world of Model Train Building has grown greatly with the aid of computers and technology to enhance the fun of building. Technology has long been a part of Model Train building with the adding of lights, bells, and whistles to capture your interest and imagination. But with the latest generation of building comes the influx of technology and the computer.
King Ramses II Essay Research Paper Ramses
King Ramses II Essay, Research Paper Ramses II Usermaatre Setepenre,third ruler of the 19th Dynasty,was born about 1303 B.C in the Eastern Nile Delta, following the death of his grandfather King Ramses I and Father Sethi I, was one of the longest reigning pharaohs of ancient Egypt.He reigned 67 years (roughly from 1290 to 1224 B.C), during the early part of his reign, Ramses fought to regain the territory in Africa and Western Asia that Egypt had held during the 15th and 16th centuries B.C in the beginning as coregent with his father, and lived for more than 80 years, which was very rare in those days.During his life he made quite a reputation as a builder and a warrior, but also as a ladies man.He had 5 or 6 main wives, mostly of all being Nefertari, but is known to have over 100 children with all of his wives.In Ancient Egypt people seems to have made fun of this fact.
The Convergence Of The Twain Essay Research
Paper The Titanic set sail for it’s maiden voyage on April 12,1912 . This beautiful ship was made of the strongest iron available to man during this time. The Titanic was believed to be the ship that even God could not sink. However, on April 14 tragedy stuck. Over 1,000 people were lost at sea when the titanic sank.
The Roles Of I330 And O90 Essay
, Research Paper The Roles of I-330 and O-90 Zamyatin s We is a story set far into the future. There is only one country, OneState, and the government controls everything. The story is actually a diary written by the main character, D-503, that is to be sent aboard a space shuttle to other planets in order to describe the greatness of OneState.
Hamlet Essay Research Paper Hamlet Leartes and
Hamlet Essay, Research Paper Hamlet, Leartes and Fortinbras all had some huge issues to work out in their lives. The way they worked out these problems is how we see the action behind the men and are able to recognize the traits that influenced all characters in the play, not just the ones discussed here. All three of these men avenge in very different ways.
Surviving Treblinka Essay Research Paper Surviving Treblinka
Surviving Treblinka Essay, Research Paper Surviving Treblinka The book, Surviving Treblinka, describes a miraculous story of one man s struggle to remain alive through each coming day and his escape from Germany s killing machine. Samuel Willenberg is one of a very small group of people, who have lived to tell about their horrific experiences in the concentration camps, but what made these people so different from all the others who never saw liberty again? Perhaps some individuals survived the Holocaust while others didn t because they received help from old acquaintances, had a very strong will to live and were in a close group of helpful friends during their imprisonment.
Notre Dame Essay Research Paper Notre Dame
Notre Dame Essay, Research Paper Notre Dame Notre Dame is a cathedral. The word cathedral comes from the Latin word cathedra, which is the name that was given to the throne was called where the
Untitled Essay Research Paper here ya go
Untitled Essay, Research Paper here ya go…have fun History Compare and Contrast the writings of Confucius, Hammurabi, and the book of the dead Three of the most famous writings from ancient civilizations are the writings of Confucius, Hammurabi’s code of laws, and Egypt’s Book of the Dead. At first, they seem very different, they’re from different times, regions, and religions, but they all offer a peek into what values ancient people considered important.
Gentle Ben Essay Research Paper A brown
Gentle Ben Essay, Research Paper A brown bear is the largest most dangerous big-game animal in North America. Even so ,Mark Anderson?s only friend is Ben, the
OnLine Recruitment Essay Research Paper Online recruiting
On-Line Recruitment Essay, Research Paper On-line recruiting is the process of attracting and hiring applicants for positions within an organization through use of the internet. In this paper I will assess an on-line recruitment service, identify the advantages and disadvantages of this vehicle as a recruiting technique for an organization, evaluate the pros and cons of dealing with virtual resumes, and develop criteria an organization can use for selecting an on-line recruiting service.
Birth Control
–Abstinence Essay, Research Paper Reminiscing about my high school days I can remember the pressure there was to have sex. Within the male high school community, having sex was a “right of passage”. As we all know this attitude was very wrong. There are many issues that affect young people these days. One of these one in three sexually active people will have contracted an STD.
Steriods 2 Essay Research Paper Are steroids
Steriods 2 Essay, Research Paper Are steroids a drug? Yes, they are considered drugs and some types are illegal. These types of steroids are very controversial because they help body builders to bulk up fast and they make the body builder gain weight and loose fat in a short period of time. But on the other hand steroids also destroy the body.
Eiffel Tower Essay Research Paper My report
Eiffel Tower Essay, Research Paper My report is on the Eiffel Tower. The Eiffel was built in 1889, for the celebration of the centennial of The French Revolution. Which was in 1789. The Eiffel Tower was named for the builder, Gustave Alexandre Eiffel.u7
The Code Of Hammurabi Essay Research Paper
The Code of Hammurabi Of the many law codes surviving from the ancient Middle East, perhaps the most famous is the Code of Hammurabi, sixth King of the Amorite Dynasty of Old Babylon. Today, the code, engraved in stone takes on a unique form as a piece of art. However, decoded it is clear that this stone was obeyed and served as a sort of political propaganda.
Titanic Outlinepaper
&bibliography Essay, Research Paper Outline In retrospect, blame for the sinking of the Titanic can be placed on the inferior materials used by the ship builder, the misled motivation of Captain Smith and the White Star Line, and the poor emergency provisions and procedures.
Master Builder Freudian Symbols Essay Research Paper
Freudian Symbols in The Master Builder The Master Builder, by Henrik Ibsen, is a play about individuality, morality, and self. But beneath those very ambiguous descriptions lies a play with symbols that clearly