C Programming: Important Code Syntax and Definitions
Basic Input and Output
1. Print to console: printf("Hello, World!\n");
2. Input from user: scanf("%d", &variable);
Variables and Constants
1. Variable Declaration: int x = 10; float pi = 3.14;
2. Constant Declaration: const int MAX = 100;
Operators
1. Arithmetic: +, -, *, /, %
2. Relational: ==, !=, >, <, >=, <=
3. Logical: &&, ||, !
4. Assignment: =, +=, -=, *=, /=, %=.
Control Structures
1. If Statement: if (condition) { /* code */ }
2. If-Else: if (condition) { /* code */ } else { /* code */ }
3. Switch: switch(variable) { case value: /* code */ break; default: /* code */ }
Loops
1. For Loop: for(initialization; condition; increment) { /* code */ }
2. While Loop: while(condition) { /* code */ }
3. Do-While Loop: do { /* code */ } while(condition);
Functions
1. Syntax: return_type function_name(parameters) { /* code */ }
2. Example: int sum(int a, int b) { return a + b; }
3. Function Call: result = sum(5, 3);
Arrays
1. Declaration: int arr[5];
2. Initialization: int arr[5] = {1, 2, 3, 4, 5};
3. Access: printf("%d", arr[2]);
Strings
1. Declaration: char str[20];
2. Initialization: char str[] = "Hello";
3. Access: printf("%c", str[1]); // prints 'e'
Pointers
1. Declaration: int *ptr;
2. Assignment: ptr = &var;
3. Dereference: printf("%d", *ptr);
File Handling
1. Open File: FILE *fp = fopen("file.txt", "r");
2. Read/Write: fscanf(fp, "%s", str); fprintf(fp, "%s", str);
3. Close File: fclose(fp);
Dynamic Memory Allocation
1. Allocate Memory: int *ptr = (int *)malloc(sizeof(int));
2. Free Memory: free(ptr);
Structures
1. Define: struct Person { char name[50]; int age; };
2. Access: struct Person p1; p1.age = 25;
Preprocessor Directives
1. Include Header: #include<stdio.h>
2. Define Constant: #define PI 3.14