#include <stdio.h> int main() { printf("Hello, World!\n"); return 0; }
在 C 語言中,變數用於儲存可在程式中操作的資料。這是有關在 C:
中建立和使用變數的綜合指南聲明:
type variable_name;
範例:
int number; char letter; float salary;
初始化:
variable_name = value;
範例:
number = 10; letter = 'A'; salary = 50000.0;
宣告與初始化組合:
type variable_name = value;
範例:
int age = 25; double pi = 3.14159; char grade = 'A';
範例:
int age; char _grade; float salary_2024;
變數的作用域是程式中可以存取該變數的部分。 C 中的變數可以是:
局部變數:在函數或區塊內聲明,並且只能在該函數或區塊內存取。
void myFunction() { int localVar = 5; printf("%d", localVar); }
全域變數:在所有函數之外聲明,並可從程式內的任何函數存取。
int globalVar = 10; void myFunction() { printf("%d", globalVar); } int main() { myFunction(); // Outputs: 10 return 0; }
常數是指一旦賦值就無法改變其值的變數。它們是使用 const 關鍵字聲明的。
範例:
const int DAYS_IN_WEEK = 7; const float PI = 3.14159;
在 C 中,未初始化的局部變數包含垃圾值,而全域變數和靜態變數預設為零。
範例:
#include <stdio.h> int globalVar; // default value 0 int main() { int localVar; // contains garbage value printf("Global Variable: %d\n", globalVar); printf("Local Variable: %d\n", localVar); return 0; }
您可以在一行中聲明多個相同類型的變量,並用逗號分隔它們。您也可以在聲明時或稍後初始化它們。
範例:
// Declaring multiple variables without values int a, b, c; // Declaring and initializing some variables int x = 10, y, z = 30;
您可以透過連結賦值運算子將相同的值指派給多個變數。
範例:
int m, n, o; m = n = o = 50;
C 中的註解是不可執行的語句,用來描述和解釋程式碼。它們對於使程式碼更具可讀性和可維護性至關重要。 C 支援兩種類型的註解:
單行註解以兩個正斜線 (//) 開頭。該行 // 後面的所有內容都被視為註解。
文法:
// This is a single-line comment int x = 10; // x is initialized to 10
多行註解以/*開始,以*/結束。 /* 和 */ 之間的所有內容都被視為註釋,無論它跨越多少行。
文法:
/* This is a multi-line comment. It can span multiple lines. */ int y = 20; /* y is initialized to 20 */
單行註解範例:
#include <stdio.h> int main() { // Print Hello, World! printf("Hello, World!\n"); // This prints the string to the console return 0; }
多行註解範例:
#include <stdio.h> int main() { /* This is a simple C program that prints Hello, World! to the console. */ printf("Hello, World!\n"); return 0; }
這些範例說明如何在 C 語言中使用單行和多行註解來使程式碼更具可讀性和可維護性。
在C中,輸入和輸出運算是使用標準函式庫函數執行的。基本輸入和輸出最常用的函數是 printf 和 scanf。
printf 函數用於將文字和變數列印到控制台。
文法:
printf("format string", variable1, variable2, ...);
格式說明符:
範例:
#include <stdio.h> int main() { int age = 25; float salary = 50000.0; double pi = 3.141592653589793; char grade = 'A'; char name[] = "John"; printf("Age: %d\n", age); printf("Salary: %.2f\n", salary); printf("Pi: %.15lf\n", pi); printf("Grade: %c\n", grade); printf("Name: %s\n", name); return 0; }
scanf 函數用於從控制台讀取格式化輸入。
文法:
scanf("format string", &variable1, &variable2, ...);
範例:
#include <stdio.h> int main() { int age; float salary; double pi; char grade; char name[50]; printf("Enter age: "); scanf("%d", &age); printf("Enter salary: "); scanf("%f", &salary); printf("Enter pi value: "); scanf("%lf", &pi); printf("Enter grade: "); scanf(" %c", &grade); // Note the space before %c to consume any leftover newline character printf("Enter name: "); scanf("%s", name); // Reads a single word, stops at whitespace printf("\nYou entered:\n"); printf("Age: %d\n", age); printf("Salary: %.2f\n", salary); printf("Pi: %.15lf\n", pi); printf("Grade: %c\n", grade); printf("Name: %s\n", name); return 0; }
使用 fgets 讀取一行文字:
文法:
fgets(buffer, size, stdin);
範例:
#include <stdio.h> int main() { char name[50]; printf("Enter your full name: "); fgets(name, sizeof(name), stdin); // Reads a line of text including spaces printf("Your name is: %s", name); return 0; }
getchar 範例:
#include <stdio.h> int main() { char ch; printf("Enter a character: "); ch = getchar(); printf("You entered: "); putchar(ch); printf("\n"); return 0; }
putchar Example:
#include <stdio.h> int main() { char ch = 'A'; printf("The character is: "); putchar(ch); printf("\n"); return 0; }
In C programming, data types specify the type of data that variables can store. C supports several basic and derived data types, each with specific properties. Here's a comprehensive guide to data types in C:
Example:
int numInt = 100000;
Example:
short numShort = 1000;
Example:
long numLong = 10000000000L;
Example:
long long bigNumber = 123456789012345LL;
Example:
float numFloat = 3.14f;
Example:
double numDouble = 3.14159;
Example:
long double extendedPi = 3.14159265358979323846L;
Example:
char letter = 'A';
Example:
#include <stdbool.h> bool isValid = true;
Example:
int numbers[5] = {1, 2, 3, 4, 5};
Example:
int *ptr;
struct structure_name { type member1; type member2; // ... };
Example:
struct Person { char name[50]; int age; float salary; };
In C, booleans are typically represented using integer types, where 0 represents false and any non-zero value represents true. Let's explore how booleans are handled in C programming:
In C, there is no dedicated boolean type like in some other languages. Instead, integers (int) are commonly used to represent boolean values.
Example:
#include <stdio.h> int main() { _Bool b1 = 1; // true _Bool b2 = 0; // false printf("b1: %d\n", b1); // Output: 1 (true) printf("b2: %d\n", b2); // Output: 0 (false) return 0; }
Example:
#include <stdio.h> #include <stdbool.h> int main() { bool isValid = true; bool isReady = false; printf("isValid: %d\n", isValid); // Output: 1 (true) printf("isReady: %d\n", isReady); // Output: 0 (false) return 0; }
In C, expressions are evaluated to true (1) or false (0). Here are some examples of expressions and their boolean evaluations:
Example:
#include <stdio.h> int main() { int num = 10; float salary = 0.0; if (num) { printf("num is true\n"); } else { printf("num is false\n"); } if (salary) { printf("salary is true\n"); } else { printf("salary is false\n"); } return 0; }
Output:
num is true salary is false
In C, a null pointer is evaluated as false in boolean context. A null pointer is typically represented as (type *)0.
Example:
#include <stdio.h> int main() { int *ptr = NULL; if (ptr) { printf("ptr is not NULL\n"); } else { printf("ptr is NULL\n"); } return 0; }
Output:
ptr is NULL
In C programming, type casting refers to converting a value from one data type to another. There are two types of type casting: implicit and explicit. Let's explore each in detail:
Implicit type casting occurs automatically by the compiler when compatible types are mixed in expressions. It promotes smaller data types to larger data types to avoid loss of data. It's also known as automatic type conversion.
Example:
#include <stdio.h> int main() { int numInt = 10; double numDouble = 3.5; double result = numInt + numDouble; // Implicitly converts numInt to double printf("Result: %.2lf\n", result); // Output: 13.50 return 0; }
In this example, numInt (an integer) is implicitly converted to a double before performing the addition with numDouble.
Explicit type casting is performed by the programmer using casting operators to convert a value from one data type to another. It allows for precise control over the type conversion process but can lead to data loss if not used carefully.
Syntax:
(type) expression
Example:
#include <stdio.h> int main() { double numDouble = 3.5; int numInt; numInt = (int)numDouble; // Explicitly casts numDouble to int printf("numInt: %d\n", numInt); // Output: 3 return 0; }
In this example, numDouble (a double) is explicitly cast to an int. The decimal part is truncated, resulting in numInt being 3.
Arrays in C are collections of variables of the same type that are accessed by indexing. They provide a way to store multiple elements under a single name.
To declare an array in C, specify the type of elements it will hold and the number of elements enclosed in square brackets [].
type arrayName[arraySize];
int numbers[5]; // Array of 5 integers
Arrays can be initialized either during declaration or after declaration using assignment statements.
int numbers[5] = {1, 2, 3, 4, 5}; // Initializing during declaration // Initializing after declaration int moreNumbers[3]; moreNumbers[0] = 10; moreNumbers[1] = 20; moreNumbers[2] = 30;
Array elements are accessed using zero-based indexing, where the first element is at index 0.
int numbers[5] = {1, 2, 3, 4, 5}; printf("First element: %d\n", numbers[0]); // Output: 1 printf("Second element: %d\n", numbers[1]); // Output: 2
Array elements can be modified by assigning new values to specific indices.
int numbers[5] = {1, 2, 3, 4, 5}; numbers[2] = 10; // Modify the third element printf("Modified third element: %d\n", numbers[2]); // Output: 10
C supports multidimensional arrays, which are arrays of arrays. They are useful for storing tabular data or matrices.
int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; printf("Element at row 2, column 3: %d\n", matrix[1][2]); // Output: 6
When passing arrays to functions, C passes them by reference. This means any modifications made to the array within the function affect the original array.
#include <stdio.h> void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int numbers[5] = {1, 2, 3, 4, 5}; printArray(numbers, 5); // Pass array and its size to function return 0; }
In C programming, strings are arrays of characters terminated by a null ('\0') character. Let's explore how to work with strings, including input, output, and manipulation:
Strings in C are arrays of characters. They can be declared and initialized in several ways:
Syntax:
char strName[size];
Example:
#include <stdio.h> int main() { // Declaring and initializing a string char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Alternatively, using string literal (implicitly adds '\0') char message[] = "Welcome"; printf("Greeting: %s\n", greeting); // Output: Hello printf("Message: %s\n", message); // Output: Welcome return 0; }
To input a string with spaces in C, fgets() from
Example:
#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); fgets(name, sizeof(name), stdin); // Read input including spaces printf("Hello, %s!\n", name); return 0; }
C provides several library functions for manipulating strings, declared in
Example:
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello"; int len = strlen(str); printf("Length of '%s' is %d\n", str, len); // Output: Length of 'Hello' is 5 return 0; }
Example:
#include <stdio.h> #include <string.h> int main() { char src[] = "Hello"; char dest[20]; strcpy(dest, src); printf("Copied string: %s\n", dest); // Output: Copied string: Hello return 0; }
Example:
#include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello"; char str2[] = " World"; strcat(str1, str2); printf("Concatenated string: %s\n", str1); // Output: Concatenated string: Hello World return 0; }
Example:
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello"; char str2[] = "Hello"; if (strcmp(str1, str2) == 0) { printf("Strings are equal\n"); } else { printf("Strings are not equal\n"); } return 0; }
When using fgets() for string input, ensure buffer overflow doesn't occur by specifying the maximum length of input to read.
Example:
#include <stdio.h> int main() { char sentence[100]; printf("Enter a sentence: "); fgets(sentence, sizeof(sentence), stdin); // Read up to 99 characters plus '\0' printf("You entered: %s\n", sentence); return 0; }
C strings are null-terminated, meaning they end with a null character '\0'. This character indicates the end of the string and is automatically added when using string literals.
Example:
#include <stdio.h> int main() { char message[] = "Hello"; // Automatically includes '\0' // Printing characters until '\0' is encountered for (int i = 0; message[i] != '\0'; ++i) { printf("%c ", message[i]); } printf("\n"); return 0; }
Operators in C are symbols used to perform operations on variables and values. They are categorized into several types based on their functionality.
Arithmetic operators are used for basic mathematical operations.
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds two operands | x + y |
- | Subtraction | Subtracts the right operand from the left | x - y |
* | Multiplication | Multiplies two operands | x * y |
/ | Division | Divides the left operand by the right operand | x / y |
% | Modulus | Returns the remainder of the division | x % y |
++ | Increment | Increases the value of operand by 1 | x++ or ++x |
-- | Decrement | Decreases the value of operand by 1 | x-- or --x |
#include <stdio.h> int main() { int a = 10, b = 3; printf("a + b = %d\n", a + b); // Output: 13 printf("a / b = %d\n", a / b); // Output: 3 printf("a %% b = %d\n", a % b); // Output: 1 (Modulus operation) int x = 5; x++; printf("x++ = %d\n", x); // Output: 6 int y = 8; y--; printf("y-- = %d\n", y); // Output: 7 return 0; }
Assignment operators are used to assign values to variables and perform operations.
Operator | Name | Description | Example |
---|---|---|---|
= | Assignment | Assigns the value on the right to the variable on the left | x = 5 |
+= | Addition | Adds right operand to the left operand and assigns the result to the left | x += 3 |
-= | Subtraction | Subtracts right operand from the left operand and assigns the result to the left | x -= 3 |
*= | Multiplication | Multiplies right operand with the left operand and assigns the result to the left | x *= 3 |
/= | Division | Divides left operand by right operand and assigns the result to the left | x /= 3 |
%= | Modulus | Computes modulus of left operand with right operand and assigns the result to the left | x %= 3 |
#include <stdio.h> int main() { int x = 10; x += 5; printf("x += 5: %d\n", x); // Output: 15 return 0; }
Comparison operators are used to compare values.
Operator | Name | Description | Example |
---|---|---|---|
== | Equal | Checks if two operands are equal | x == y |
!= | Not Equal | Checks if two operands are not equal | x != y |
> | Greater Than | Checks if left operand is greater than right | x > y |
< | Less Than | Checks if left operand is less than right | x < y |
>= | Greater Than or Equal | Checks if left operand is greater than or equal to right | x >= y |
<= | Less Than or Equal | Checks if left operand is less than or equal to right | x <= y |
#include <stdio.h> int main() { int a = 5, b = 10; printf("a == b: %d\n", a == b); // Output: 0 (false) printf("a < b: %d\n", a < b); // Output: 1 (true) return 0; }
Logical operators combine Boolean expressions.
Operator | Description | Example |
---|---|---|
&& | Logical AND | x < 5 && x < 10 |
|| | Logical OR | x < 5 || x < 4 |
! | Logical NOT | !(x < 5 && x < 10) |
#include <stdio.h> int main() { int x = 3; printf("x < 5 && x < 10: %d\n", x < 5 && x < 10); // Output: 1 (true) printf("x < 5 || x < 2: %d\n", x < 5 || x < 2); // Output: 1 (true) return 0; }
Bitwise operators perform operations on bits of integers.
Operator | Name | Description | Example |
---|---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 | x & y |
| | OR | Sets each bit to 1 if one of two bits is 1 | x | y |
^ | XOR | Sets each bit to 1 if only one of two bits is 1 | x ^ y |
~ | NOT | Inverts all the bits | ~x |
<< | Left Shift | Shifts bits to the left | x << 2 |
>> | Right Shift | Shifts bits to the right | x >> 2 |