Getting started with programming
print("Hi")
public class Example{
public static void main(String[] args){
System.out.println("Hello world!");
}
}
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello word!!!";
return 0;
}
1.1. Reading input
java
import java.util.Scanner;
public class Program{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("What's your name?");
String name = scanner.nextLine();
String firt_name = "Huu Thang";
System.out.println("Hi" + name);
}
}
import java.util.Scanner;
public class Program{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.println("Write the first string:");
String first = reader.nextLine;
System.out.println("first");
}
}
C++
Dùng với cin
để đọc dữ liệu chuẩn
std::cin
để đọc dữ liệu từ bàn phím.int
, float
, char
, string
.// Nhập 1 số nguyên
#include(iostream)
using namespace std;
int main(){
int x;
cout<<"Nhap 1 so nguyen: \\n";
cin>>x;
cout<<"So ban vua nhap la: "<<x<<endl;
return 0;
}
Nhập nhiều lần liên tiếp
#include<iostream>
using namespace std;
int main(){
int a, b;
cout<<"Nhap ca a va b :\\n";
cin >> a >> b;
int sum = a + b;
Cout << "So a = " << a <<"\\n So b = " << b << endl;
cout<<sum;
return 0;
}
getline(cin, variable)
để đọc cả dòng.#include<iostream>
#include<string>
using namespace std;
int main(){
string full_name;
cout<<"Nhap ho ten cua ban day du : \\n";
getline(cin, full_name);
cout<<"Xin chao "<<full_name<<"!"<<endl;
return 0;
}
cin
#include<iostream>
using namespace std;
int main(){
int n, x, sum = 0;
cout<<"Hay nhap so luong so nguyen: ";
cin>>n;
cout<<"Nhap "<<n<<" so nguyen: \\n";
for(int i = 0; i < n ; i++){
cin>>x;
sum += x;
}
cout<<"Tong cac so vua nhap la: "<<sum <<endl;
return 0;
}
stringstream
Dùng sstream
để đọc và xử lý dữ liệu trên chuỗi.
//Tách các số từ 1 chuỗi
#include <iostream>
#include <sstream>
#include <string>
int main(){
int x, sum = 0;
string line = "10 20 30 40 50";
stringstream ss(line);
while(ss >> x){
sum += x;
}
cout<<"Tong cac so la: "<<sum <<endl;
return 0;
}
Python
input()
name = input("Enter your name: ")
print("Hello, ", name)
Chuyển đổi kiểu dữ liệu khi đọc input
int()
, float()
, bool()
để chuyển đổi dữ liệu từ chuỗi sang kiểu tương ứng.age = int(input("Enter your age: "))
print("You will be", age + 1, "years old next year.")
Đọc nhiều input trên cùng một dòng
split()
a, b = input("Enter two numbers separated by space: ").split()
a = int(a)
b = int(b)
print("Sum", a + b)
Đọc nhiều input trên nhiều dòng
# Nhap 3 so
number = []
for i in range(3):
num = int(input(f"Enter number {i + 1}:"))
numbers.append(num)
print("You entered", numbers)
Đọc input nâng cao bằng sys.stdin
sys.stdin
.import sys
data = sys.stdin.read()
print("You entered: ", data)
Đọc input bằng map()
map()
với input()
để chuyển đổi kiểu dữ liệu một cách nhanh chóng.numbers = list(map(int, input("Enter numbers separated by space: ").split()))
print("Numbers:", numbers)
Đọc input bằng input()
với xử lý ngoại lệ
Dùng try-except
để xử lý khi người dùng nhập sai kiểu dữ liệu.
while True:
try:
num = int(input("Enter an integer: "))
print("You entered", num)
break
except ValueError:
print("Invalid input! Please enter a valid integer.")
Compilation (Biên dịch)
C++ is a compiled language. That means that to get a program to run, you must first translate it from the human-readable form to something a machine can"understand." That translation is done by a program called a compiler. What you read and write is called .source code or program text, and what the computer executes is called executable, o�ject code, or 11UUhine code. Ty pically C++ source code ftles are given the suffix .cpp (e.g., hello_world.cpp) or .h (as in std_lib_facilities.h), and object code ftles arc given the sufTtx .obj (on Wmdows) or .o (Unix). The plain word cofle is therefore ambiguous and can cause confusion; use it with care only when it is obvious what's meant by it. Unless otherwise specified, we usc code to mean "source code" or even "the source code except the comments," because comments really are there just for us humans and are not seen by the compiler generating object code.
The compiler reads your source code and tries to make sense of what you wrote. It looks to see if your program is grammatically correct, if every word has a de fined meaning, and if there is anything obviously wrong that can be detected without trying to actually execute the program. Yo u'll find that computers arc rather picky about syntax. Leaving out any detail of our program, such as an #include ftle, a semicolon, or a curly brace, will cause errors. Similarly, the com piler has absolutely zero tolerance for spelling mistakes. Let us illustrate tlus with a series of examples that each have a single small error. Each error is an example of a kind of mistake we often make:
To make it possible for a program written in a higher-level language to run on different computer systems, there are two basic strategies. The classical approach is to use a program called a compiler to translate the programs that you write into the low-level machine language appropriate to the computer on which the program will run. Under this strategy, different platforms require different translators. For example, if you are writing C programs for a Macintosh, you need to run a special program that translates C into the machine language for the Macintosh. If you are using a Windows platform to run the same program, you need to use a different translator because the underlying hardware uses a different machine language.
The second approach is to translate the program into an intermediate language that is independent of the underlying platform. On each of these platforms, programs run in a system called an interpreter that executes the intermediate language for that machine. In a pure interpreter, the interpreter does not actually translate the intermediate language into machine language but simply implements the intended effect for each operation.
Modern implementations of Java use a hybrid approach. A Java compiler translates your programs into a common intermediate language. That language is then interpreted by a program called the Java Virtual Machine (or JVM for short) that executes the intermediate language for that machine. The program that runs the Java Virtual Machine, however, typically does compile pieces of the intermediate code into the underlying machine language. As a result, Java can often achieve a level of efficiency that is unattainable with traditional interpreters.
In classical compiler-based systems, the compiler translates the source file into a second file called an object file that contains the actual instructions appropriate for that computer system. This object file is then combined together with other object files to produce an executable file that can be run on the system. These other object files typically include predefined object files, called libraries, that contain the machine language instructions for various operations commonly required by programs. The process of combining all the individual object files into an executable file is called linking. The entire process is illustrated by the diagram shown in Figure 1-2. In Java, the process is slightly more elaborate. As noted earlier in this section, Java produces intermediate code that it stores in files called class files. Those class files are then combined with other class files and libraries to produce a complete version of the intermediate program with everything it needs linked together. The usual format for that version of the program is a compressed collection of individual files called a JAR archive. That archive file is then interpreted by the Java Virtual Machine in such a way that the output appears on your computer. This process is illustrated in Figure 1-3.
Linking
A program usually consists of several separate parts, often developed by different people. For example, the "Hello, World!" program consists of the part we wrote U plus parts of the C++ standard library. These separate parts (sometimes called lrmulttlion uni/.1) must be compiled and the resulting object code ftlcs must be linked together to form an executable program. The program that links such parts together is (unsurprisingly) called a linker:
Please note that object code and executablcs are no/ portable among systems. For example, when you compile for a Wmdows machine, you get object code for Wmdows that will not run on a Linux machine. A library is simply some code -usually written by others -that we access using declarations found in an #included ftle. A declaration is a program statement specifying how a piece of code can be used; we'll examine declarations in detail later (e.g., §4.5.2). Errors found by the compiler are called compile-lime errors, errors found by the linker are called link-limt• errors, and errors not found until the program is run arc called nm-time trmr.l or logic errors. Generally, compile-time errors are easier to un derstand and ftx than link-time errors, and link-time errors are often easier to ftnd and ftx than run-time errors and logic errors. In Chapter 5 we discuss errors and the ways of handling them in greater detail.
Java and the object-oriented paradigm
As noted earlier in this chapter, this text uses the programming language Java to illustrate the more general concepts of programming and computer science. But why Java? The answer lies primarily in the way that Java encourages programmers to think about the programming process.
Over the last decade, computer science and programming have gone through something of a revolution. Like most revolutions—whether political upheavals or the conceptual restructurings that Thomas Kuhn describes in his 1962 book The Structure of Scientific Revolutions—this change has been driven by the emergence of an idea that challenges an existing orthodoxy. Initially, the two ideas compete. For a while, the old order maintains its dominance. Over time, however, the strength and popularity of the new idea grows, until it begins to displace the older idea in what Kuhn calls a paradigm shift. In programming, the old order is represented by the procedural paradigm, in which programs consist of a collection of procedures and functions that operate on data. The challenger is the object-oriented paradigm, in which programs are viewed instead as a collection of “objects” for which the data and the operations acting on that data are encapsulated into integrated units. Most traditional languages, including Fortran, Pascal, and C, embody the procedural paradigm. The best-known representatives of the object oriented paradigm are Smalltalk, C++, and Java.
Although object-oriented languages are gaining popularity at the expense of procedural ones, it would be a mistake to regard the object-oriented and procedural paradigms as mutually exclusive. Programming paradigms are not so much competitive as they are complementary. The object-oriented and the procedural paradigm—along with other important paradigms such as the functional programming style embodied in LISP and Scheme—all have important applications in practice. Even within the context of a single application, you are likely to find a use for more than one approach. As a programmer, you must master many different paradigms, so that you can use the conceptual model that is most appropriate to the task at hand.
Imports
The second section of the program consists of the lines import acm.graphics.; import acm.program.;
These lines indicate that the program uses two additional library packages. A library package is a collection of tools written by other programmers that perform specific operations. The libraries used by the HelloProgram are a graphics library and a program library, each of which come from a collection of packages produced by the Association for Computing Machinery (ACM). The asterisk at the end of the package name is used to indicate that all components from the relevant package should be imported. Every program in this book will import at least the acm.program package, and any programs that use graphics will import acm.graphics, which means most of your programs will also need to include these lines immediately after the program comment. Some programs will use additional packages as well and must contain an import line for each one.
When you write your own programs, you can use the tools provided by these packages, which saves you the trouble of writing them yourself. Libraries are critical to programming, and you will quickly come to depend on several important packages as you begin to write more sophisticated programs.
Java Sử dụng System.out.print
và System.out.println
C++ sử dụng Cout<<””;
Python print(…)
System.out.print("Hello"); // In mà không xuống dòng
System.out.println("World"); // In và xuống dòng
print("World")
Cout<<"World"<<endl;
System.out.println(42); // In số nguyên
System.out.println(3.14); // In số thực
System.out.println('A'); // In ký tự
System.out.println(true); // In giá trị boolean
System.out.printf