Site icon Embarcadero RAD Studio, Delphi, & C++Builder Blogs

#CodingResolutions: Programming Fundamentals – Functions

Author: Rebekah D

If you completed any of the String exercises from the past day, you probably already have a handle on what functions are and how they are used. You should skip this lesson and work on a challenge of your choice. 

Prerequisites: 

You should already have downloaded and installed either the RAD Studio 30 Day FREE Trial, Delphi Community Edition, or C++ Builder Community Edition.

If you did not install the Samples directory during installation, go install them now. 

Need help installing the product? Read the documentation or ask for assistance in the forums.

What Are Functions? 

Functions help programs complete repetitive tasks.  Here are a couple of reasons why functions are important: 

Coding a C++ Function with Windows Apps

This tutorial does a great job walking through a basic function that takes input from the user in a text box, then adds a specific value to it and displays the result. The video itself is dated by several years, but that’s okay because the fundamentals have not changed – a function still acts and behaves the same way. Let’s follow along with the tutorial’s steps using our new 10.3 version of C++Builder.

1. Open C++ Builder 

2. Create a new multi-device C++ app 

3. On the Form Designer, make sure your View is set to Windows Desktop to most closely align with the tutorial’s screen.  Follow along with the video to add 3 buttons, 3 edit fields, and 1 label.

4. Double-click Button1 to open the code view. The tutorial walks through adding code for each button that looks like this:

The point the tutorial makes is that the above code is very repetitive because the buttons all perform the same action: they add 5 to the user’s input and then update the label.  

5.   The tutorial will walk you through creating a function named SaveTime which performs the math for the button.  

Your code will look like this: 

Fullscreen
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int SaveTime(int x)
{
return(x + 5);
}
//—————————————————————————
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//—————————————————————————
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Label1->Text = SaveTime(Edit1->Text.ToInt());
}
//—————————————————————————
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Label1->Text = SaveTime(Edit2->Text.ToInt());
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

[crayon-676814b632877978049724/]


More Practice:  C++ Console App Functions

This tutorial has sample code and walks through creating different functions for a console application. 

Delphi Functions

Marco Cantu walks through Delphi Functions and Procedures in this FREE Course: https://www.embarcaderoacademy.com/courses/396722/lectures/6067596

Previous #CodingResolution posts: 

Exit mobile version