Introduccion A La Programacion
Introduccion A La Programacion
Introduccion A La Programacion
Examples of Programs
in C, C++, and Java
Example F.1
Program F-1 is the simplest program written in the C language that prints the message
‘Hello World!’. It is an example that uses only the sequence construct, which means that
the code is executed line by line without branching or repeating some sections.
Run:
Hello World
Example F.2
Program F-2 is an example o a simple program in C that uses both sequence and branch-
ing construct. I a condition is met, the program executes some lines; i not, other lines are
executed. We run the program twice to show the two di erent cases.
Example F.3
Program F-3 shows the combination o sequence and repetition construct. We use a loop
to repeatedly print a number, but the number is changing in each repetition. We run the
program twice: the frst time, the limit is 6; the second time the limit is 9.
Example F.4
Program F-4 accomplishes the same purpose as Program F-1, but it is written in C++
instead o C. We can see the main di erence in line 14. To print data in C++, we need to
use an object. The term cout defnes an object that is responsible to output data.
Example F.5
Program F-5 accomplishes the same purpose as Program F-2, but it is written in C++
instead o C. The main di erence between this program and its C version is in lines 16,
17, 21, 22, 26, and 27 in which we need to use input object (cin) and output objects (cout)
or input and output.
Example F.6
Program F-6 accomplishes the same purpose as Program F-3, but it is written in C++
instead o C. The main di erence between this program and its C version is in lines 17,
18, and 23 in which we need to use input object (cin) and output objects (cout) or input
and output.
Example F.7
Program F-7 accomplishes the same purpose as Program F-4, but it is written in Java
instead o C++. We need a class to host the main method. Another di erence is in line10
where we use a predefned object (System.out) or output.
588 Examples of Programs in C, C++, and Java
Example F.8
Program F-8 accomplishes the same purpose as Program F-5, but it is written in Java
instead o C++. We need a class to host the main method. Other di erences are in lines
13, 14, 15, 20, 21, 26, and 27 where we use an object o class Scanner or input and a
predefned object (System.out) or output.
Example F.9
Program F-9 accomplishes the same purpose as Program F-6, but it is written in Java
instead o C++. We need a class to host the main method. Other di erences are in lines
13, 14, 15, and 20 where we use an object o class Scanner or input and a predefned
object (System.out) or output.