Introduction to Programming
Programming is the process of creating instructions for computers to execute. In this, you'll learn about programming languages, how to write your first program, and the fundamental concepts that form the foundation of all programming.
What is Programming?
Programming is solving problems by writing step-by-step instructions that a computer can understand and execute. These instructions, called code, tell the computer exactly what to do to accomplish a specific task.
Key Programming Concepts:
- Algorithm: A sequence of steps to solve a problem
- Syntax: The rules and structure of a programming language
- Logic: The reasoning behind solving problems
- Debugging: Finding and fixing errors in code
Your First Program
Let's start with the base program in C++:
#include
using namespace std;
int main() {
...
Code
...
...
// This is a comment (not executed by the program, it starts with // or /* and ends with */ in case of multi-line comments)
return 0;
}
Understanding the Code:
#include <iostream>
- Includes input/output functionalityusing namespace std;
- īAllows us to use standard library functionsint main()
- The main function where program execution beginscode
- This is where you write your program logic. The functions (like code snippet outsite main() is called from here either indirectly or directly to be executed)return 0;
- Indicates successful program execution
Input and Output
Most programs need to interact with users by taking input and producing output:
#include
using namespace std;
int main() {
string name;
int age;
cin >> name;
cout << "Hello " << name << endl;
string s;
getline(cin, s);
return 0;
}
Understanding the Code:
cin
- function to take inputcout
- function to output datagetline(cin, s)
- Reads an entire line of input including spaces
Working with Numbers
Programming often involves mathematical calculations:
#include
using namespace std;
int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "Sum: " << num1 + num2 << endl;
cout << "Difference: " << num1 - num2 << endl;
cout << "Product: " << num1 * num2 << endl;
cout << "Division: " << (double)num1 / num2 << endl;
return 0;
}
Common Beginner Mistakes:
- Forgetting semicolons at the end of statements
- Mismatching parentheses or brackets
- Case sensitivity errors (C++ is case-sensitive)
- Integer division truncating decimal results