C Program BASICS Revision

 

First C Program

Structure of a C Program

-----------------------

#include <stdio.h>  // Preprocessor directive

int main() {        // Main function

    printf("Hello, World!");  // Output statement

    return 0;       // Return statement

}

--------------------------

Tokens in C

Tokens are the smallest individual units in a C program.
Types of Tokens:

  1. Keywords → Predefined words (e.g., int, return, if, else, break)

  2. Identifiers → Names given to variables, functions (e.g., main, sum, total)

  3. Constants → Fixed values (e.g., 5, 10.5, 'A')

  4. Operators → Symbols for operations (e.g., + , - , * , /)

  5. Special Symbols → (e.g., { } , ; ( ) [ ])

  6. Strings → Sequence of characters in double quotes (e.g., "Hello")


Functions in C

Function is a block of code that performs a specific task.

Syntax:

#include <stdio.h> void greet() { // Function without return type printf("Welcome to C Programming!\n"); } int main() { greet(); // Function call return 0; }

----------------------------------------------------------------

Scope of Variables in C

Scope → Visibility or lifetime of a variable.

Types:

  1. Local Variable → Declared inside a function, accessible only within it.

  2. Global Variable → Declared outside all functions, accessible everywhere.

  3. Static Variable → Retains its value between function calls

  4. Register Variable → Stored in CPU register for faster access (rarely used now).

Example:

#include <stdio.h> int globalVar = 10; // Global Variable void func() { int localVar = 5; // Local Variable static int staticVar = 1; staticVar++; printf("Local: %d, Static: %d\n", localVar, staticVar); } int main() { func(); func(); printf("Global: %d\n", globalVar); return 0; }

----------------------------------------------------------------------

Conditional Statements in C

Used to perform decision-making in programs.

🔹 if Statement

int num = 10; if (num > 0) { printf("Positive Number"); }

-------------------------------------------

🔹 if-else Statement

int num = -5; if (num > 0) { printf("Positive"); } else { printf("Negative"); }

----------------------------------------------

🔹 else-if Ladder

int marks = 75; if (marks >= 90) { printf("Grade A"); } else if (marks >= 75) { printf("Grade B"); } else { printf("Grade C"); }

-------------------------------------------
Nested if and switch in C

int num = 5; if (num > 0) { if (num % 2 == 0) { printf("Even Positive"); } else { printf("Odd Positive"); } }


int choice = 2; switch (choice) { case 1: printf("Option 1"); break; case 2: printf("Option 2"); break; default: printf("Invalid Option"); }

------------------------------------------------------------------------------
✅ Increment and Decrement Operators in C These operators increase or decrease the value of a variable by 1.

int a = 5; printf("%d\n", a++); // Post-increment → prints 5, then a = 6 printf("%d\n", ++a); // Pre-increment → a = 7, then prints 7

_____________________________________________________________________________

Operators in C

Types of Operators:

  1. Arithmetic Operators+ , - , * , / , %, //

  2. Relational Operators== , != , > , < , >= , <=

  3. Logical Operators&& , || , !

  4. Assignment Operators= , += , -= , *= , /=

  5. Bitwise Operators& , | , ^ , ~ , << , >>

  6. Conditional (Ternary) Operatorcondition ? true : false

  7. Comma Operator, used to separate expressions.

  8. Sizeof Operator → Returns the size of a variable.

Example:

int a = 10, b = 20; printf("Sum = %d\n", a + b); // Arithmetic printf("%d\n", a > b); // Relational printf("%d\n", (a < b) && (b > 15)); // Logical a += 5; // Assignment printf("a = %d\n", a);

--------------------------------------------------------------------

✅ Loops in C

Loops are used to execute a block of code multiple times.

🔹 Types of Loops:

  1. for Loop

  2. while Loop

  3. do-while Loop

________________________________________________________

🔹 for Loop

#include <stdio.h>
int main() {
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    return 0;
}

Output: 1 2 3 4 5

___________________________________________________________________

🔹 while Loop

#include <stdio.h>
int main() {
    int i = 1;
    while (i <= 5) {
        printf("%d ", i);
        i++;
    }
    return 0;
}
___________________________________________________________________

🔹 do-while Loop

#include <stdio.h>
int main() {
    int i = 1;
    do {
        printf("%d ", i);
        i++;
    } while (i <= 5);
    return 0;
}

✅ Arrays in C

An array is a collection of similar data elements stored at contiguous memory locations.

🔹 Declaring an Array

int arr[5];  // Declares an array of size 5

🔹 Initializing an Array

int arr[5] = {1, 2, 3, 4, 5};

🔹 Accessing Elements

#include <stdio.h>
int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    printf("First element: %d", arr[0]);
    return 0;
}

🔹 Looping Through an Array

#include <stdio.h>
int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

✅ Working with 2-D Arrays in C

A 2D array is an array of arrays (matrix format).

🔹 Declaring a 2D Array

int matrix[3][3];

🔹 Initializing a 2D Array

int matrix[2][2] = {{1, 2}, {3, 4}};

🔹 Accessing 2D Array Elements

#include <stdio.h>
int main() {
    int matrix[2][2] = {{1, 2}, {3, 4}};
    printf("Element at (1,1): %d", matrix[1][1]);
    return 0;
}

🔹 Looping Through a 2D Array

#include <stdio.h>
int main() {
    int matrix[2][2] = {{1, 2}, {3, 4}};
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
    return 0;
}

✅ Strings in C

A string is a sequence of characters stored in a character array.

🔹 Declaring a String

char str[10];

🔹 Initializing a String

char str[] = "Hello";

🔹 Input and Output of Strings

#include <stdio.h>
int main() {
    char name[20];
    printf("Enter your name: ");
    scanf("%s", name);  // Reads string until space
    printf("Hello, %s", name);
    return 0;
}

✅ String Library Functions in C

C provides several built-in functions to work with strings (in string.h).

FunctionDescription
strlen(str)                       Returns length of string
strcpy(dest, src)Copies src to dest
strncpy(dest, src, n)Copies first n characters of src to dest
strcat(str1, str2)Concatenates str2 to str1
strncat(str1, str2, n)Appends first n characters of str2 to str1
strcmp(str1, str2)Compares two strings
strncmp(str1, str2, n)Compares first n characters of two strings
strchr(str, ch)Finds first occurrence of ch in str
strrchr(str, ch)Finds last occurrence of ch in str
strstr(str1, str2)Finds first occurrence of str2 in str1
strrev(str)Reverses the string

🔹 Example: Using String Functions

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    char str3[20];

    printf("Length of str1: %lu\n", strlen(str1));
    strcpy(str3, str1);
    printf("Copied string: %s\n", str3);
    strcat(str1, str2);
    printf("Concatenated string: %s\n", str1);
    printf("Comparison result: %d\n", strcmp("abc", "abd"));
    printf("First occurrence of 'l': %s\n", strchr(str1, 'l'));
    printf("Last occurrence of 'l': %s\n", strrchr(str1, 'l'));
    printf("Finding 'or' in 'World': %s\n", strstr(str2, "or"));


    return 0;
}
OUTPUT:

Length of str1: 5 Copied string: Hello Concatenated string: HelloWorld Comparison result: -1 First occurrence of 'l': llo Last occurrence of 'l': l Finding 'or' in 'World': or

Working with Structures in C A structure in C is a user-defined data type that allows grouping together variables of different data types into a single unit. Declaring a Structure: A structure is declared using the `struct` keyword followed by the structure name.

Example: ```c struct Student { char name[50]; int age; float marks; }; ``'

__________________________________________________

Accessing Structure Members: You can access structure members using the dot (.) operator.

Example: ```c #include struct Student { char name[50]; int age; float marks; }; int main() { struct Student student1; student1.age = 21; student1.marks = 85.5; strcpy(student1.name, "John Doe"); printf("Name: %s ", student1.name); printf("Age: %d ", student1.age); printf("Marks: %.2f ", student1.marks); return 0; } ```

Output: Name: John Doe Age: 21 Marks: 85.50

__________________________________________________


Understanding Pointers in C A pointer in C is a variable that stores the memory address of another variable. Declaring a Pointer: Pointers are declared by using the asterisk (*) symbol before the pointer variable.

Example: ```c int *ptr; ``` Pointer Example: ```c #include int main() { int num = 10; int *ptr; ptr = # printf("Value of num: %d ", num); printf("Value of ptr: %p ", ptr); printf("Value at ptr: %d ", *ptr); return 0; } ```

Output: Value of num: 10 Value of ptr: [memory address] Value at ptr: 10

__________________________________________________

Function Call in C A function in C is a block of code that performs a specific task and can be invoked by the function name.

Declaring and Defining a Function: A function is declared by specifying the return type, function name, and parameters (if any).

Example: ```c void greet() { printf("Hello, World! "); } ```

__________________________________________________

Function Call: You can call a function by using its name followed by parentheses.

Example: ```c #include void greet() { printf("Hello, World! "); } int main() { greet(); // Function call return 0; } ```

Output: Hello, World!

__________________________________________________

Files in C In C, files are used to store data permanently. The file handling is done using functions like `fopen`, `fclose`, `fread`, and `fwrite`.

Opening and Closing a File: Files are opened using `fopen()` and closed using `fclose()`.

Example: ```c FILE *fptr; fptr = fopen("file.txt", "w"); // Open file for writing if (fptr == NULL) { printf("Error opening file. "); return 1; } fprintf(fptr, "Hello, File! "); fclose(fptr); ```

__________________________________________________

Reading from a File: ```c #include int main() { FILE *fptr; char str[100]; fptr = fopen("file.txt", "r"); // Open file for reading if (fptr == NULL) { printf("Error opening file. "); return 1; } fgets(str, 100, fptr); // Read a line from the file printf("Read from file: %s ", str); fclose(fptr); return 0; } ```

Output (assuming file.txt exists with 'Hello, File!' written inside):

Read from file: Hello, File!

Comments

Popular Posts

WRITING GOALS CHALLENGE ♥️#MAY

THE ANGEL FROM GOD

A1 & A2 SPANISH COMPLETION #2-WEEK CHALLENGE

A Journey Beyond Borders

THE BROKEN WING

Basic Greetings & Phrases - es

Here there's one, who is much faithful than ourselves, and will lead you till the end...

JavaScript Basic Revision