C Programming Variables Data Types Sizes and Operators Study Guide

General Structure of a C Program

A C program follows a specific hierarchical structure consisting of several specialized sections. Organizing code in this manner ensures readability and proper compilation.

  • Documentation Section: Contains comments that provide information about the program, such as its name, author, and purpose.
  • Link Section: Provides instructions to the compiler to link functions from the system library.
  • Definition Section: Where all symbolic constants are defined.
  • Global Declaration Section: Used to declare variables that are accessible throughout the entire program and all functions.
  • main() Function Section: Every C program must have one main() function. It contains two parts:
    • Declaration Part: Declares all variables used in the executable part.
    • Executable Part: Contains at least one statement.
    • Note: The main function logic is enclosed within curly braces { }.
  • Subprogram Section: Contains all user-defined functions that are called in the main() function. This can include:
    • Function 1
    • Function 2
    • Function n

Code Examples: Basic Operations

Reading and Displaying a Number
//Program to read and display a number
#include<stdio.h>
int main()
{
 int num;
 printf("\nEnter the number: ");
 scanf("%d", &num);
 printf("The number read is: %d", num);
 return(0);
}
Adding Two Integers
#include <stdio.h>
int main( void ) {/* start of function main */
 int sum; /* variable in which sum will be stored */
 int integer1; /* first number to be input by user */
 int integer2; /* second number to be input by user */
 printf( "Enter first integer\n" );
 scanf( "%d", &integer1 ); /* read an integer */
 printf( "Enter second integer\n" );
 scanf( "%d", &integer2 ); /* read an integer */
 sum = integer1 + integer2; /* assign total to sum */
 printf( "Sum is %d\n", sum ); /* print sum */
 return 0; /* indicate that program ended successfully */
} /* end of function main */

C Character Set and Tokens

C Character Set

A language's character set is the collection of valid characters it can recognize. The C character set includes:

  • Letters: Lowercase ‘a’ through ‘z’ and uppercase ‘A’ through ‘Z’.
  • Digits: Numerals 0 through 9.
  • Special Characters: Symbols such as ;, ?, >, <, &, {, }, [, ], etc.
  • White Spaces: Characters like New line (\n), Tab (\t), and Vertical Tab (\v).
C Tokens

A token is a group of characters that logically belong together and serve as the basic building blocks for a program. C utilizes several types of tokens:

  • Keywords: Reserved words with predefined meanings (e.g., break, int, float).
  • Identifiers: Symbolic names used for various data items (e.g., Variable names, Function names, Array names).
  • Operators: Symbols that trigger actions (e.g., +, *, %).
  • Special Symbols: Punctuation and grouping symbols (e.g., ;, ?, >, &, {, }).
  • Strings: Sequences of characters enclosed in double quotes (e.g., "hello", "123", "s").
  • Constants: Fixed values (e.g., 124, 21.3, 'A', '9').

Keywords and Variables

Keywords
  • Keywords are reserved words in C with predefined meanings for the compiler.
  • They cannot be used as variable or constant names.
  • All keywords have fixed meanings that cannot be altered by the programmer.
Variables
  • Variables are symbolic names for data storage locations in the computer's memory.
  • They represent memory locations where computational data is stored.
  • A variable can take different values at different times during program execution.
  • Values are assigned to variables via initialization or assignment.
Rules for Valid Identifiers (Variable Names)
  • Names must begin with a letter or an underscore (_).
  • Initial characters can be followed by any combination of letters, underscores, or digits.
  • Keywords cannot be used as variable names.
  • C is case-sensitive: sum, Sum, and SUM are three distinct variables.
  • Variable names can be very long, though typically only the first 31 or 63 characters are significant.
  • Meaningful names should be chosen to improve program readability.
  • Valid Examples: Sum, _difference, a, J5x7, Number_of_moves.
  • Invalid Examples: sum$value (contains illegal symbol $), 3val (starts with a digit), int (reserved keyword).

Data Types and Memory Sizes

C uses several primary or built-in data types grouped by category.

Basic Data Types
  • int: Stores integer numbers (values without decimal places).
  • float: Stores floating-point numbers (values with decimal places).
  • double: Floating-point type with roughly twice the size and precision of a float.
  • char: Stores a single character, such as 'a', '6', or ';'.
  • void: Denotes an empty or non-existent value.
Integer Type Modifiers and Sizes (16-bit Machine)
  • short: Uses fewer bits.
  • long: Uses more bits.
  • signed: Handles both positive and negative numbers.
  • unsigned: Handles only positive numbers.
TypeSize (Bits)Range
short, short int, or signed short int88128-128 to 127127
unsigned short int8800 to 255255
int or signed int161632,768-32,768 to 32,76732,767
unsigned int161600 to 65,53565,535
long int or signed long int32322,147,483,648-2,147,483,648 to 2,147,483,6472,147,483,647
unsigned long int323200 to 4,294,967,2954,294,967,295
Floating-Point Types and Sizes (16-bit Machine)

Floating-point numbers consist of an integer part and a fractional part (e.g., 108.1517108.1517).

  • Scientific Notation: Expressed as mantissa e exponent (e.g., 1.7e41.7e4 is 1.7×1041.7 \times 10^4).
TypeSize (Bits)Size (Bytes)
float (Single Precision)323244
double (Double Precision)646488
long double (Long Double Precision)80801010
Character Types and Encoding
  • A char is internally stored as a numeric value using American Standard Code for Information Interchange (ASCII).
  • char / signed char: 11 byte, range 128-128 to 127127.
  • unsigned char: 11 byte, range 00 to 255255.
  • ASCII Examples:
    • ' ' (space): 3232
    • '0' to '9': 4848 to 5757
    • 'A' to 'Z': 6565 to 9090
    • 'a' to 'z': 9797 to 122122
  • Escape characters: Special sequences like \n (newline), \t (tab), \v (vertical tab).

Best Practices: Naming Standards

Programmers often use prefixes to identify data types at a glance:

  • i: int and unsigned int (e.g., iTotalMarks)
  • f: float (e.g., fAverageMarks)
  • d: double (e.g., dSalary)
  • l: long and unsigned long (e.g., lFactorial)
  • c: signed/unsigned char (e.g., cChoice)
  • ai, af, ad, al, ac: Arrays of integer, float, double, long, and char respectively.

Operators in C

Arithmetic Operators
  • Binary Operators: +, -, *, /, %.
  • Integer Division: The / operator truncates any fractional part when used with integers (e.g., 5/2=25/2 = 2).
  • Modulus Operator: The % operator produces the remainder of integer division (e.g., 5%2=15 \% 2 = 1). It cannot be applied to float or double.
  • Unary Minus: Negates the value of an operand (e.g., if a = 25, -a is 25-25).
Relational Operators

Used to compare values. Relational expressions return 11 (TRUE) or 00 (FALSE).

  • ==: Is equal to
  • !=: Is not equal to
  • <: Is less than
  • <=: Is less or equal
  • >: Is greater than
  • >=: Is greater or equal
  • Precedence: Relational operators have lower precedence than arithmetic operators. a<b+ca < b + c is evaluated as a<(b+c)a < (b + c).
Logical Operators

Used to combine or negate logical expressions.

  • && (AND): Returns TRUE if both operands are true.
  • || (OR): Returns TRUE if at least one operand is true.
  • ! (NOT): Inverts the logical state (e.g., !(FALSE) is TRUE).
Increment and Decrement Operators

Unary operators used to increase or decrease the value of a variable by one.

  • Prefix Mode (++i, --i): The value is changed first, then used in the expression.
  • Postfix Mode (i++, i--): The original value is used in the expression first, then the variable is changed.
  • Constraint: Cannot be used on expressions. ++(5) or ++(x+1) are syntax errors.
Bitwise Operators

Operate on integer bits starting from the Least Significant Bit (LSB).

  • &: Bitwise AND
  • |: Bitwise OR
  • ^: Bitwise EXOR (Exclusive OR)
  • ~: Ones Complement (Unary; inverts all bits)
  • <<: Bitwise Shift Left. Shifting op by n positions moves bits left, vacating bits filled with 00. Equivalent to multiplication by 2n2^n.
  • >>: Bitwise Shift Right. Shifting op by n positions moves bits right, vacating bits filled with 00 (for unsigned integers). Equivalent to division by 2n2^n.
  • Requirements for n (shift amount): Must not be negative and must not exceed the number of bits representing the operand.
Assignment and Conditional Operators
  • Compound Assignment: op= combines an operation and assignment (e.g., count += 10 is count = count + 10).
  • Conditional (Ternary) Operator: condition ? expression1 : expression2. If the condition is TRUE, expression1 is the result; otherwise, expression2 is the result.
  • Comma (,) Operator: Used to separate expressions. Expressions are evaluated left-to-right, and the value of the sequence is the value of the rightmost expression.

Type Conversions

Implicit Conversion (Automatic)

C automatically converts types during evaluation to avoid loss of significance.

  • Short or Char \rightarrow int.
  • Lower precedence types are promoted to higher types present in the expression (e.g., float promoted to double, int to long double).
  • Final Assignment Rules:
    • float to int causes truncation of the fractional part.
    • double to float causes rounding of digits.
    • long int to int causes dropping of excess higher-order bits.
Explicit Conversion (Type Casting)

Forces a local conversion of a variable or expression for a specific calculation.

  • Format: (type-name) expression (e.g., (float) 57/67 ensures the division retains fractional points).
  • Note: Type casting does not permanently change the variable's original type or value.

Operator Precedence and Associativity Summary

RankCategoryOperatorsAssociativity
1Suffix/Postfix( ) [ ] -> . ++ --Left-to-Right
2Unary+ - ! ~ ++ -- (type) * & sizeofRight-to-Left
3Multiplication* / %Left-to-Right
4Addition+ -Left-to-Right
5Shifts<< >>Left-to-Right
6Relational< <= > >=Left-to-Right
7Equality== !=Left-to-Right
8Bitwise AND&Left-to-Right
9Bitwise XOR^Left-to-Right
10Bitwise OR|Left-to-Right
11Logical AND&&Left-to-Right
12Logical OR||Left-to-Right
13Ternary?:Right-to-Left
14Assignment= += -= *= /= %= <<= >>= &= ^= |=Right-to-Left
15Comma,Left-to-Right

Tutorial Problems and Evaluated Expressions

Evaluation Example

Expression: 2*((i/5)+(4*(j-3))%(i+j-2)) where i=8, j=5.

  1. Substitute: 2*((8/5)+(4*(5-3))%(8+5-2))
  2. Solve Parentheses: 2*(1+(4*2)%(11))Note: 8/5 is 1 in integer division.
  3. Multiply/Mod: 2*(1+8%11)
  4. Mod Result: 2*(1+8)
  5. Final Addition: 2*9
  6. Result: 18
Evaluation Logic Proofs

Assume a=2, b=3, c=6, d=5, num=30.

  • (a == 5): Returns 00 (False).
  • (a * b >= c): 6>=66 >= 6 returns 11 (True).
  • (b + 4 > a * c): 7>127 > 12 returns 00 (False).
  • ((b = 2) == a): b becomes 22, then 2==22 == 2 returns 11 (True).
  • ((5 == 5) && (3 > 6)): True && False returns 00.
  • ((5 == 5) || (3 > 6)): True || False returns 11.
  • 7 == 5 ? 4 : 3: returns 33.
  • 7 == 5 + 2 ? 4 : 3: returns 44.
  • K = (num > 5 ? (num <= 10 ? 100 : 200) : 500): 30>530 > 5 is True; 30<=1030 <= 10 is False; returns 200200.
  • a = 5/2: returns 22 if a is an integer.
  • a = 7/22*(3.14+2)*3/5: 7/22 is 00 in integer division, so the entire expression evaluates to 00.