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, andSUMare 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.
| Type | Size (Bits) | Range |
|---|---|---|
short, short int, or signed short int | to | |
unsigned short int | to | |
int or signed int | to | |
unsigned int | to | |
long int or signed long int | to | |
unsigned long int | to |
Floating-Point Types and Sizes (16-bit Machine)
Floating-point numbers consist of an integer part and a fractional part (e.g., ).
- Scientific Notation: Expressed as
mantissa e exponent(e.g., is ).
| Type | Size (Bits) | Size (Bytes) |
|---|---|---|
float (Single Precision) | ||
double (Double Precision) | ||
long double (Long Double Precision) |
Character Types and Encoding
- A
charis internally stored as a numeric value using American Standard Code for Information Interchange (ASCII). char/signed char: byte, range to .unsigned char: byte, range to .- ASCII Examples:
' '(space):'0'to'9': to'A'to'Z': to'a'to'z': to
- 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:intandunsigned int(e.g.,iTotalMarks)f:float(e.g.,fAverageMarks)d:double(e.g.,dSalary)l:longandunsigned 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., ). - Modulus Operator: The
%operator produces the remainder of integer division (e.g., ). It cannot be applied tofloatordouble. - Unary Minus: Negates the value of an operand (e.g., if
a = 25,-ais ).
Relational Operators
Used to compare values. Relational expressions return (TRUE) or (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. is evaluated as .
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)isTRUE).
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. Shiftingopbynpositions moves bits left, vacating bits filled with . Equivalent to multiplication by .>>: Bitwise Shift Right. Shiftingopbynpositions moves bits right, vacating bits filled with (for unsigned integers). Equivalent to division by .- 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 += 10iscount = count + 10). - Conditional (Ternary) Operator:
condition ? expression1 : expression2. If the condition is TRUE,expression1is the result; otherwise,expression2is 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.
ShortorCharint.- Lower precedence types are promoted to higher types present in the expression (e.g.,
floatpromoted todouble,inttolong double). - Final Assignment Rules:
floattointcauses truncation of the fractional part.doubletofloatcauses rounding of digits.long inttointcauses 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/67ensures the division retains fractional points). - Note: Type casting does not permanently change the variable's original type or value.
Operator Precedence and Associativity Summary
| Rank | Category | Operators | Associativity |
|---|---|---|---|
| 1 | Suffix/Postfix | ( ) [ ] -> . ++ -- | Left-to-Right |
| 2 | Unary | + - ! ~ ++ -- (type) * & sizeof | Right-to-Left |
| 3 | Multiplication | * / % | Left-to-Right |
| 4 | Addition | + - | Left-to-Right |
| 5 | Shifts | << >> | Left-to-Right |
| 6 | Relational | < <= > >= | Left-to-Right |
| 7 | Equality | == != | Left-to-Right |
| 8 | Bitwise AND | & | Left-to-Right |
| 9 | Bitwise XOR | ^ | Left-to-Right |
| 10 | Bitwise OR | | | Left-to-Right |
| 11 | Logical AND | && | Left-to-Right |
| 12 | Logical OR | || | Left-to-Right |
| 13 | Ternary | ?: | Right-to-Left |
| 14 | Assignment | = += -= *= /= %= <<= >>= &= ^= |= | Right-to-Left |
| 15 | Comma | , | 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.
- Substitute:
2*((8/5)+(4*(5-3))%(8+5-2)) - Solve Parentheses:
2*(1+(4*2)%(11))Note: 8/5 is 1 in integer division. - Multiply/Mod:
2*(1+8%11) - Mod Result:
2*(1+8) - Final Addition:
2*9 - Result:
18
Evaluation Logic Proofs
Assume a=2, b=3, c=6, d=5, num=30.
(a == 5): Returns (False).(a * b >= c): returns (True).(b + 4 > a * c): returns (False).((b = 2) == a):bbecomes , then returns (True).((5 == 5) && (3 > 6)):True && Falsereturns .((5 == 5) || (3 > 6)):True || Falsereturns .7 == 5 ? 4 : 3: returns .7 == 5 + 2 ? 4 : 3: returns .K = (num > 5 ? (num <= 10 ? 100 : 200) : 500): is True; is False; returns .a = 5/2: returns ifais an integer.a = 7/22*(3.14+2)*3/5:7/22is in integer division, so the entire expression evaluates to .