Comp Computer Science

Computer ScienceUnit 713 min read

C Basics: Data, Types, Operators & Syntax

Unit 7 of Computer Science teaches the foundation of C programming—how to write simple programs, declare variables, use data types, and apply operators to perform calculations. Learn syntax rules, memory allocation, and how C processes instructions step-by-step with examples.

TAKEAWAYS:

  • C programs follow a strict structure: #include, main(), and statements ending with ;.
  • Data types (like int, float, char) define what kind of data a variable can hold and how much memory it uses.
  • Operators (+, -, *, /, %, =) perform arithmetic, assignment, and comparison tasks.
  • Variables must be declared before use (e.g., int age = 20;).
  • Keywords (like if, for, return) have special meanings in C and cannot be used as variable names.
  • Comments (// or /* */) help explain code but are ignored by the compiler.

1. Introduction to C Programming

C is a procedural programming language used to write efficient and fast programs. It is the foundation for many modern languages like C++, Java, and Python. C programs are compiled (converted to machine code) before execution.

08162431Preprocessor Directive24 bitsReserved8 bitsFunction Declaration32 bitsAlignmentStatement32 bitsSemicolon1 bitsTermination32 bitsClosing Brace1 bits
Logical breakdown of a minimal C program's structure (32-bit conceptual view)

Structure of a C Program

Every C program must have:

  1. Preprocessor directives (e.g., #include <stdio.h>)
  2. main() function (the starting point of execution)
  3. Statements (instructions ending with ;)
Preprocessor Directivesmain() FunctionStatementsreturn 0;Execution Flow
Simplified structure of a C program showing execution order

Example:

#include <stdio.h>
int main() {
    printf("Hello, World!");
    return 0;
}
  • #include <stdio.h>: Includes the standard input/output library.
  • int main(): The program starts here.
  • printf("Hello, World!");: Prints text to the screen.
  • return 0;: Indicates successful program termination.

2. Variables and Data Types

Variables store data in memory. Before using a variable, you must declare it with a data type and optionally assign a value.

classDiagram
    class int {
        +size: 2 or 4 bytes
        +range: -32768 to 32767 (2B) or -2B to 2B (4B)
        +example: 42, -10
    }
    class float {
        +size: 4 bytes
        +precision: ~6-9 digits
        +example: 3.14, -0.5
    }
    class double {
        +size: 8 bytes
        +precision: ~15-17 digits
        +example: 3.1415926535
    }
    class char {
        +size: 1 byte
        +range: 0 to 255 (ASCII)
        +example: 'A', '7'
    }
    int --> "stores" float : can hold
    int --> "stores" double : can hold (truncated)
    float --> "stores" char : can hold (via casting)
Memory size and precision hierarchy of C's fundamental data types

Common Data Types in C

Data Type Size (bytes) Description Example Values
int 2 or 4 Integer numbers 5, -10, 0
float 4 Decimal numbers (single precision) 3.14, -0.5
double 8 Decimal numbers (double precision) 3.14159
char 1 Single character 'A', 'a', '$'
bool 1 true or false (C99+) 1 (true), 0 (false)

Example:

int age = 20;          // Integer variable
float height = 5.6;    // Floating-point variable
char grade = 'A';      // Character variable

Rules for Variable Names

  • Must start with a letter or underscore (_).
  • Can contain letters, digits, and underscores.
  • Cannot be a keyword (e.g., int, if, return).
  • Case-sensitive (Age ≠ age).

Example of Invalid Names:

int 123age;    // Starts with a digit → Error
int my-var;    // Contains '-' → Error
int if;        // 'if' is a keyword → Error

3. Constants and Literals

  • Constants are fixed values that do not change.
  • Literals are direct values assigned to variables or used in code.
Type Example Description
Integer 5, -10 Whole numbers
Float 3.14, -0.5 Decimal numbers
Character 'A', '$' Single character in single quotes
String "Hello" Text in double quotes (requires char[])
Boolean true, false Logical values (C99+)

Example:

const float PI = 3.14159;  // Constant (cannot be changed)
printf("Value of PI: %f", PI);

4. Operators in C

Operators perform operations on variables and values.

sequenceDiagram
    participant: a as int = 10
    participant: b as int = 3
    participant: result
    a->>result: a + b (13)
    a->>result: a - b (7)
    a->>result: a * b (30)
    a->>result: a / b (3)
    a->>result: a % b (1)
    a->>result: a += b (a becomes 13)
    a->>result: a > b (true)
    a->>result: a && b > 0 (true)
    Note right of result: Operators in action with a=10, b=3
Arithmetic and relational operators demonstrated with sample values

A. Arithmetic Operators

Used for mathematical calculations.

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 3 * 4 12
/ Division 10 / 2 5
% Modulus 10 % 3 1

Example:

int a = 10, b = 3;
printf("Sum: %d\n", a + b);      // 13
printf("Remainder: %d\n", a % b); // 1

B. Assignment Operators

Used to assign values to variables.

Operator Example Equivalent To
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 1 x = x - 1
*= x *= 2 x = x * 2
/= x /= 2 x = x / 2
%= x %= 3 x = x % 3

Example:

int x = 5;
x += 3;  // x = x + 3 → x = 8
printf("x = %d", x);

C. Relational Operators

Used in conditions (e.g., if statements).

Operator Name Example Result (if a=5, b=3)
== Equal to a == b false
!= Not equal to a != b true
> Greater than a > b true
< Less than a < b false
>= Greater or equal a >= b true
<= Less or equal a <= b false

Example:

int a = 5, b = 3;
printf("%d > %d is %d\n", a, b, a > b);  // 1 (true)

D. Logical Operators

Used to combine conditions.

Operator Name Example (a=true, b=false) Result
&& AND a && b false
|| OR a || b true
! NOT !a false

Example:

int x = 10, y = 20;
if (x > 5 && y < 30) {
    printf("Condition is true");
}

5. Input and Output in C

A. printf() Function

Used to print output to the screen.

Syntax:

printf("format_string", variable1, variable2, ...);

Format Specifiers:

Specifier Data Type Example
%d Integer printf("%d", 10)
%f Float printf("%f", 3.14)
%c Character printf("%c", 'A')
%s String printf("%s", "Hello")
%% Print % printf("%%") → %

Example:

int num = 5;
float pi = 3.14159;
printf("Number: %d, PI: %.2f\n", num, pi);  // Number: 5, PI: 3.14

B. scanf() Function

Used to take input from the user.

Syntax:

scanf("format_string", &variable1, &variable2, ...);
  • The & (address-of) operator is required for variables.

Example:

int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d years old.", age);

6. Memory and Storage Classes

C provides different storage classes to control variable lifetime and scope.

Storage Class Scope Lifetime Example Use Case
auto Block-level Exists while block is executing Local variables in functions
register Block-level Fast access (hint to compiler) Frequently used variables
static Block/file-level Retains value between function calls Persistent local variables
extern File-level Global variable (shared across files) Variables used in multiple files

Example of static:

void count() {
    static int counter = 0;  // Retains value between calls
    counter++;
    printf("Counter: %d\n", counter);
}
count();  // 1
count();  // 2

7. Type Conversion

ImplicitImplicitExplicitImplicitImplicitintfloatdoublechar
Type conversion pathways in C (arrows show direction)

A. Implicit Conversion

Automatic conversion by the compiler (e.g., int to float).

Example:

int a = 5;
float b = a;  // a is converted to 5.0
printf("%f", b);  // 5.000000

B. Explicit Conversion (Casting)

Manual conversion using (type).

Example:

float x = 3.14;
int y = (int)x;  // x is cast to integer (3)
printf("%d", y);  // 3

8. Common Errors and Debugging

Error Type Example Fix
Syntax Error Missing ; or { Check for missing symbols
Type Mismatch scanf("%d", &name); (name is char[]) Use %s for strings
Uninitialized Variable printf("%d", age); (age not declared) Declare and initialize variables
Infinite Loop while(1) without break Add exit condition

Example Debugging:

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", num);  // Error: Missing &
    printf("You entered: %d", num);
    return 0;
}

Fix:

scanf("%d", &num);  // Correct

Exam Tip

  1. Syntax Matters: Always end statements with ;. Forgetting ; or } causes errors.
  2. Variable Declaration: Declare variables before using them. Example:
    int x;  // Correct
    x = 10;
    
    x = 10;  // Error (x not declared)
    int x;
    
  3. Operator Precedence: Remember PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction). Example: 5 + 3 * 2 → 5 + (3 * 2) = 11 (not 16).
  4. Input/Output: Use & with scanf() and correct format specifiers (%d, %f, %c).
  5. Constants vs Variables: Use const for values that should not change (e.g., const float PI = 3.14;).
  6. Common Questions in NEB Exams:
    • Write a program to add two numbers using scanf() and printf().
    • Explain the difference between = and ==.
    • Convert a decimal number to binary using arithmetic operations.
    • Write a program to check if a number is even or odd using the modulus operator.

NEB Board-Style Questions

Short Answer Questions

  1. What is the difference between = and == in C?

    • = is an assignment operator (assigns value to a variable).
    • == is a relational operator (checks equality).
  2. Write a C program to swap two numbers using a temporary variable.

    #include <stdio.h>
    int main() {
        int a = 5, b = 10, temp;
        temp = a;
        a = b;
        b = temp;
        printf("a = %d, b = %d", a, b);
        return 0;
    }
    
  3. What are the three main parts of a C program?

    • Preprocessor directives (#include), main() function, and statements.

Long Answer Questions

  1. Explain the following data types in C with examples:

    • int: Stores whole numbers (e.g., int age = 20;).
    • float: Stores decimal numbers (e.g., float height = 5.6;).
    • char: Stores single characters (e.g., char grade = 'A';).
    • double: Stores high-precision decimal numbers (e.g., double pi = 3.1415926535;).
  2. Write a program to calculate the area of a circle using scanf() for input and printf() for output.

    #include <stdio.h>
    int main() {
        float radius, area;
        const float PI = 3.14159;
        printf("Enter radius: ");
        scanf("%f", &radius);
        area = PI * radius * radius;
        printf("Area = %.2f", area);
        return 0;
    }
    
  3. What are the advantages and disadvantages of using static variables in C?

    • Advantages:
      • Retains value between function calls.
      • Limited scope (only within the file).
    • Disadvantages:
      • Can lead to unintended side effects if misused.
      • Increases memory usage if overused.

Practice Exercises

  1. Write a program to check if a number is positive, negative, or zero.
  2. Convert a temperature from Celsius to Fahrenheit using the formula: .
  3. Write a program to find the largest of three numbers using relational operators.
  4. Explain the difference between int, float, and double with examples.
  5. What will be the output of the following code?
    int x = 5, y = 2;
    printf("%d\n", x / y);  // Output: 2 (integer division)
    printf("%d\n", x % y);  // Output: 1 (remainder)
    

Based on the NEB +2 Management syllabus for Computer Science (Comp), unit 7.

Discussion

Loading…