Writing First C++ Program - Hello World Example - GeeksforGeeks (2024)

Last Updated : 26 Dec, 2023

Comments

Improve

C++ is a widely used Object Oriented Programming language and is relatively easy to understand. The “Hello World” program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn.

The Hello World Program in C++ is the basic program that is used to demonstrate how the coding process works. All you have to do is display the message “Hello World” on the console screen.

To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

C++ Hello World Program

Below is the C++ program to print Hello World.

C++

// C++ program to display "Hello World"

// Header file for input output functions

#include <iostream>

using namespace std;

// Main() function: where the execution of

// program begins

int main()

{

// Prints hello world

cout << "Hello World";

return 0;

}

Output

Hello World

Working of Hello World Program in C++

Let us now understand every line and the terminologies of the above program.

1. // C++ program to display “Hello World”

This line is a comment line. A comment is used to display additional information about the program. A comment does not contain any programming logic.

When a comment is encountered by a compiler, the compiler simply skips that line of code. Any line beginning with ‘//’ without quotes OR in between /*…*/ in C++ is a comment.Click to know More about Comments.

2. #include

This is a preprocessor directive. The #include directive tells the compiler to include the content of a file in the source code.

For example, #include<iostream> tells the compiler to include the standard iostream filewhich contains declarations of all the standard input/output library functions.Click to Know More on Preprocessors.

3. using namespace std

This is used to import the entity of the std namespace into the current namespace of the program. The statement using namespace std is generally considered a bad practice. When we import a namespace we are essentially pulling all type definitions into the current scope.

The std namespace is huge. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type. For example, std::cout.Click to know More about using namespace std.

4. int main() { }

A function is a group of statements that are designed to perform a specific task. The main() function is the entry point of every C++ program, no matter where the function is located in the program.

The opening braces ‘{‘ indicates the beginning of the main function and the closing braces ‘}’ indicates the ending of the main function. Click to know More about the main() function.

5. cout<<“Hello World”;

std::cout is an instance of the std::ostream class, that is used to display output on the screen. Everything followed by the character << in double quotes ” ” is displayed on theoutput device. The semi-colon character at the end of the statement is used to indicate that the statement is ending there.Click to know More on Input/Output.

6. return 0

This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function.

7. Indentation

As you can see the cout and the return statement have been indented or moved to the right side. This is done to make the code more readable. We must always use indentations and comments to make the code more readable.Must read the FAQ on the style of writing programs.

Important Points

  1. Always include the necessary header files for the smooth execution of functions. For example, <iostream> must be included to use std::cin and std::cout.
  2. The execution of code begins from the main() function.
  3. It is a good practice to use Indentation and comments in programs for easy understanding.
  4. cout is used to print statements and cin is used to take inputs.


`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } document.getElementById('article-video-tab-content').style.display = 'block'; } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); // error handling for no compatible source player.on('error', function() { var error = player.error(); console.log("Video Error: ", error); if (error && error.code === 4) { console.log("No compatible source was found for this media."); hideVideoPlayer(); } }); }, function(err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); hideVideoPlayer(); // hiding video in case of timeout (requirejs) console.log(err); }); // function to hide the video player function hideVideoPlayer() { var videoPlayer = document.getElementById('article-video'); if (videoPlayer) { videoPlayer.parentNode.removeChild(videoPlayer); } } /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content // element = document.getElementById('article-video-tab-content'); // element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Writing First C++ Program - Hello World Example - GeeksforGeeks (2024)

References

Top Articles
Singapore Toto Results & Winning Numbers Today
Live updates: Singapore Airlines turbulence incident
PBC: News & Top Stories
The Machine 2023 Showtimes Near Habersham Hills Cinemas
5 Fastest Ways To Become Rich by Investing in the Stock Market
Nambe Flatware Discontinued
Transfer and Pay with Wells Fargo Online®
Rs3 Bring Leela To The Tomb
Salon Armandeus Nona Park
Log in or sign up to view
Savannah Rae Demers Fanfix
The Front Porch Self Service
Seafood Bucket Cajun Style Seafood Restaurant South Salt Lake Menu
2013 Chevy Sonic Freon Capacity
Craigslist Sfbay
888-490-1703
Stolen Touches Neva Altaj Read Online Free
Kind Farms Reserve Medical And Recreational Cannabis Photos
Nerdwallet American Express Gold
Xiom Vega X Review & Playtesting • Racket Insight
Syracuse Deadline
Emma D'arcy Deepfake
Python Regex Space
Alloyed Trident Spear
Hinzufügen Ihrer Konten zu Microsoft Authenticator
Hca Florida Middleburg Emergency Reviews
Jesus Revolution (2023)
Mega Millions Lottery - Winning Numbers & Results
The Quiet Girl Showtimes Near Landmark Plaza Frontenac
Goodwill Winter Springs 434
Walgreens On Nacogdoches And O'connor
Mcdonald Hours Near Me
Herdis Eriksson Obituary
Hondros Student Portal
Jami Lafay Gofundme
Free Stuff Craigslist Roanoke Va
ACMG - American College of Medical Genetics and Genomics on LinkedIn: #medicalgenetics #genomics
Hanging Hyena 4X4
Osceola County Addresses Growth with Updated Mobility Fees
Az610 Flight Status
Imagemate Orange County
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Ap Bio Unit 2 Progress Check Mcq
The Nun 2 Ending Explained, Summary, Cast, Plot, Review, and More
Heatinghelp The Wall
Promiseb Discontinued
5 Pros & Cons of Massage Envy (VS Independent Massage Therapists)
Transactions on Computational Social Systems - IEEE SMC
Stock Hill Restaurant Week Menu
102Km To Mph
Barber Gym Quantico Hours
Sam Smith Lpsg
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 5936

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.