#include <stdio.h> int main() { printf("Hello, World!\n"); return 0; }
En C, les variables sont utilisées pour stocker des données qui peuvent être manipulées au sein d'un programme. Voici un guide complet sur la création et l'utilisation de variables en C :
Déclaration :
type variable_name;
Exemple :
int number; char letter; float salary;
Initialisation :
variable_name = value;
Exemple :
number = 10; letter = 'A'; salary = 50000.0;
Déclaration et initialisation combinées :
type variable_name = value;
Exemple :
int age = 25; double pi = 3.14159; char grade = 'A';
Exemples :
int age; char _grade; float salary_2024;
La portée d'une variable est la partie du programme où la variable est accessible. Les variables en C peuvent être :
Variables locales : Déclarées à l'intérieur d'une fonction ou d'un bloc et accessibles uniquement à l'intérieur de cette fonction ou de ce bloc.
void myFunction() { int localVar = 5; printf("%d", localVar); }
Variables globales : Déclarées en dehors de toutes les fonctions et accessibles depuis n'importe quelle fonction du programme.
int globalVar = 10; void myFunction() { printf("%d", globalVar); } int main() { myFunction(); // Outputs: 10 return 0; }
Les constantes sont des variables dont les valeurs ne peuvent pas être modifiées une fois attribuées. Ils sont déclarés à l'aide du mot clé const.
Exemple :
const int DAYS_IN_WEEK = 7; const float PI = 3.14159;
En C, les variables locales non initialisées contiennent des valeurs inutiles, tandis que les variables globales et statiques sont initialisées à zéro par défaut.
Exemple :
#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; }
Vous pouvez déclarer plusieurs variables du même type sur une seule ligne, en les séparant par des virgules. Vous pouvez également les initialiser soit au moment de la déclaration, soit ultérieurement.
Exemples :
// Declaring multiple variables without values int a, b, c; // Declaring and initializing some variables int x = 10, y, z = 30;
Vous pouvez attribuer la même valeur à plusieurs variables en chaînant l'opérateur d'affectation.
Exemple :
int m, n, o; m = n = o = 50;
Les commentaires en C sont des instructions non exécutables qui sont utilisées pour décrire et expliquer le code. Ils sont essentiels pour rendre le code plus lisible et maintenable. C prend en charge deux types de commentaires :
Les commentaires sur une seule ligne commencent par deux barres obliques (//). Tout ce qui suit // sur cette ligne est considéré comme un commentaire.
Syntaxe :
// This is a single-line comment int x = 10; // x is initialized to 10
Les commentaires sur plusieurs lignes commencent par /* et se terminent par */. Tout ce qui se trouve entre /* et */ est considéré comme un commentaire, quel que soit le nombre de lignes qu'il s'étend.
Syntaxe :
/* This is a multi-line comment. It can span multiple lines. */ int y = 20; /* y is initialized to 20 */
Exemple de commentaire sur une seule ligne :
#include <stdio.h> int main() { // Print Hello, World! printf("Hello, World!\n"); // This prints the string to the console return 0; }
Exemple de commentaire sur plusieurs lignes :
#include <stdio.h> int main() { /* This is a simple C program that prints Hello, World! to the console. */ printf("Hello, World!\n"); return 0; }
Ces exemples illustrent comment utiliser les commentaires sur une seule ligne et sur plusieurs lignes en C pour rendre le code plus lisible et maintenable.
En C, les opérations d'entrée et de sortie sont effectuées à l'aide des fonctions de bibliothèque standard. Les fonctions les plus couramment utilisées pour les entrées et sorties de base sont printf et scanf.
La fonction printf est utilisée pour imprimer du texte et des variables sur la console.
Syntaxe :
printf("format string", variable1, variable2, ...);
Spécificateurs de format :
Exemple :
#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; }
La fonction scanf est utilisée pour lire les entrées formatées depuis la console.
Syntaxe :
scanf("format string", &variable1, &variable2, ...);
Exemple :
#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; }
Lecture d'une ligne de texte avec fgets :
Syntaxe :
fgets(buffer, size, stdin);
Exemple :
#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 Exemple :
#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 |