#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에서는 초기화되지 않은 지역 변수에 가비지 값이 포함되어 있는 반면, 전역 변수와 정적 변수는 기본적으로 0으로 초기화됩니다.
예:
#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 |