LEARNING OBJECTIVES
- To introduce the structure of simple C programs through the presentation of small sample programs.
- To identify the simple data types: int, float, double, and char.
- To introduce the basic usage of input and output (I/O).
- To introduce the assignment statement along with the basic arithmetic operators and writing simple arithmetic expressions.
BRIEF HISTORY
- A high-level language (e.g., C, FORTRAN, Pascal) enables a programmer to write programs that are more or less independent of a particular type of computer.
- High-level languages are closer to human languages and farther from machine languages; they require a compiler/interpreter to be translated into machine code.
- Examples of high-level languages include C, C++, Java, Python; C is a high-level language.
BRIEF HISTORY (continued)
- Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories.
- Uses simple English-like statements for commands; easy to understand.
- Requires following certain syntax rules (grammatical rules).
BRIEF HISTORY: LEVELS OF LANGUAGE
- Low level: Machine language, Assembly Language.
- Middle level: C language (bridges gap between machine language and high-level languages).
- High level: COBOL, FORTRAN, PASCAL, C#, PROLOG, JAVA, .NET, etc.
WHY C IS CALLED A MIDDLE-LEVEL LANGUAGE
- C bridges the gap between machine-language and high-level languages.
- It supports system programming (e.g., writing an operating system) and application programming (e.g., menu-driven customer billing systems).
BASIC STRUCTURE OF A C PROGRAM
- A C program has two parts: pre-processor directives and the main function.
- Pre-processor directives start with a # symbol and are processed before compilation.
- Common pre-processor directives include #include (to include header files), #define (to define macros), and #ifdef (for conditional compilation).
- Example: #include
- Every C program must have one, and only one, main function; this is the entry point of execution.
A. DEFINITION SECTION
- Defines the data used in the function.
- This is the section at the beginning of the function where you declare all variables and data structures used in that function.
- It is crucial to declare variables here before use.
B. LOCAL DEFINITIONS
- Local definitions are variables or constants defined within a function and are accessible only within that function (local scope).
- Typically placed at the start of the function, right after the opening brace {.
- EXAMPLE:
int main(void) {
int num1, num2; // Local variables
float result; // Another local variable
// Function code here
}
C. GLOBAL DEFINITIONS
- Global variables are defined outside of any function, typically at the top of the program, before main.
- They can be accessed by any function.
- Global variables hold their values throughout the lifetime of the program; they are initialized when the program starts and destroyed when the program terminates.
GLOBAL DEFINITIONS: EXAMPLE
#include <stdio.h>
int globalVar = 10; // Global variable
void func1() {
printf("Global variable in func1: %d\n", globalVar);
}
int main(void) {
printf("Global variable in main: %d\n", globalVar);
func1(); // This function can also access globalVar
return 0;
}
D. THE STATEMENT SECTION
- Contains the actual instructions that tell the computer what to do.
- It is where the logic of the program is implemented.
STATEMENT SECTION: EXAMPLE
int main(void) {
int a = 5, b = 10; // Local variables
int sum;
sum = a + b; // Statement that adds two numbers
printf("Sum: %d\n", sum); // Statement that outputs the result
return 0;
}
PREPROCESSOR DIRECTIVES (DETAILED)
- Preprocessor directives are lines in a C program that start with the # symbol.
- They are not executable statements but instructions for the preprocessor, a part of the compilation process that runs before the main compilation starts.
- They manage file inclusions, constant definitions, macro expansions, and conditional compilations before the code is actually compiled.
- The preprocessor examines the code before the actual compilation begins.
- Examples include #include, #define, #ifdef, etc.
PREPROCESSOR DIRECTIVE EXAMPLES
#include <stdio.h> // Includes standard I/O library
#define PI 3.142 // Macro for constant
#ifdef DEBUG
// conditional code
#endif
PREPROCESSOR DIRECTIVE: EXAMPLE AND EXPLANATION
- #include notifies the preprocessor that printf and scanf are found in the standard header file .
- The header file stdio.h contains information about standard input/output functions such as scanf and printf.
- #define PI 3.142 defines a macro named PI with the value 3.142.
- Macros are pieces of code replaced by their definitions during compilation.
PREPROCESSOR DIRECTIVE: MORE ON MACROS
- Macro example: #define PI 3.142
- Macro substitution occurs wherever the macro name is encountered.
- This does not allocate memory; it simply replaces text before compilation.
- A memory constant can be created using const as described later.
MORE ON PREPROCESSOR DIRECTIONS: INCLUDE AND HEADER FILES
- #include indicates identifiers used (e.g., printf) are in the standard header file .
- Header files contain declarations for standard I/O functions like scanf and printf.
MAIN FUNCTION AND CASE SENSITIVITY
- A program may contain one or more functions, but exactly one function must be called main.
- The body of the function is enclosed in curly braces { }.
- C is case-sensitive; for example, Printf is a syntax error (must use printf).
- Each statement ends with a semicolon (;).
- Curly brackets must be paired properly; every opening brace has a corresponding closing brace.
RESERVED WORDS
- A reserved word has a special meaning in C and cannot be used as an identifier.
- Examples: for, while, if, else, float, switch, case, default, etc.
IDENTIFIERS
- Standard identifiers: e.g., scanf, printf (defined in standard I/O library).
- User-defined identifiers: programmer-defined names for variables, constants, functions, arrays, pointers, etc.
- Examples of identifiers: total_price, price, quantity.
- Can begin with a letter or underscore (_).
- Cannot begin with a digit.
- Must not contain special symbols or punctuation such as &, !, %, *, or spaces.
- Cannot be a reserved word.
INVALID IDENTIFIERS (EXAMPLES)
- 123quantity (cannot begin with a digit)
- float (reserved word)
- int (reserved word)
- TWO*TRIp (character * not allowed)
- Ally’s (character ’ not allowed)
VALID IDENTIFIERS (EXAMPLES)
- student_name
- totalMark
- number3
IDENTIFIERS: FURTHER NOTES
- Case sensitivity: Number, number, and NUMBER are different identifiers.
- Meaningful names: Names should reflect the value or purpose.
- Readability: Use underscores to separate words, e.g., dollarsperhour rather than dollarsperhour.
VARIABLES
- Memory cells used for storing input data are called variables.
- They store input data and computational results.
- Declare a variable before use; specify the type of data to store; allocate space for the value; values can change during execution.
- Variables can be initialized during declaration.
DATA TYPES
- Data types define how data is stored and what operations are allowed.
- The three most common data types: Integer types, float/double, and char.
- Integer types include int, char, short, long, etc.; sizes vary (e.g., 1, 2, 4, or 8 bytes).
- Floating types: float, double, long double; typical sizes are 4, 8, 8 bytes respectively.
DATA TYPES: CHAR
- char represents an individual character value; can be a letter, digit, or symbol.
- Character constants are enclosed in single quotes: 'A', 'z', '2', '*'.
IDENTIFIERS: TYPING AND VALUES (EXAMPLES)
- int quantity;
- float price;
- double pi;
- char ans;
- total_price is an example of a valid identifier.
CONSTANTS
- Constants are values that do not change.
- Ways to define constants:
- Literal constants: unnamed constants used to specify data (e.g., a = b + 5;).
- Defined constants (preprocessor): use #define to create a constant (e.g., #define PI 3.142).
- Memory constants: use the const qualifier to declare a constant (e.g., const double PI = 3.142;).
- Preprocessor constants replace every occurrence of the defined constant with its value; cannot be modified at runtime.
- A constant defined with const must be initialized and cannot be reassigned.
- Naming convention: use all capital letters for constants to distinguish from variables.
CONSTANTS: EXAMPLES
#define PI 3.142
const double PI = 3.142; // memory constant (if allowed by language rules)
CONSTANTS: CIRCLE AREA EXAMPLE
#include <stdio.h>
#define PI 3.142
int main(void) {
float radius, area;
printf("Enter a value for radius ");
scanf("%f", &radius);
area = radius * radius * PI;
printf("\nThe Area is %.3f\n", area);
return 0;
}
ASSIGNMENT STATEMENTS
- Stores a value or computational result in a variable using the assignment operator '='.
- Syntax: VARIABLE = EXPRESSION;
- Examples:
- x = 1;
- a = b + c;
- x = y = z = 0;
- counter = counter + 1;
- result = 3 + 2 * 3 / 1 + 4;
ARITHMETIC OPERATION BASICS
- An arithmetic operation has a left operand, an operator, and a right operand.
- Example: x = 10; x += 5; // compound assignment expands to x = x + 5
- Binary operators require two operands (which may be numbers, constants, variables, or other expressions).
- Operators include +, -, *, /, % (modulus).
- Example mapping:
- 5 + 2 is 7
- 5 - 2 is 3
- 5 * 2 is 10
- 5 / 2 is 2.5 (in floating context) or 2 (integer division)
- 5 % 2 is 1
COMPOUND ASSIGNMENT OPERATORS
- +=, -=, *=, /=, %= abbreviations:
- sum += number // sum = sum + number
- x -= 1 // x = x - 1
- a *= b + c // a = a * (b + c)
- x /= y // x = x / y
- c %= 2 // c = c % 2
OUTPUT USING printf()
- printf is used to display output to the screen; "printf" means print formatted.
- Syntax (format string): printf(formatstring, listof_values);
- Example: printf("Welcome to C Programming");
- Example: printf("The number is %d", num);
printf: STRUCTURE AND EXAMPLES
#include <stdio.h>
int main() {
int number1 = 10, number2 = 20, sum;
sum = number1 + number2;
printf("Sum : %d", sum);
return 0;
}
PLACEHOLDER AND CONVERSION CHARACTER
- A placeholder begins with a percent sign (%) and specifies the data type to be printed.
- Placeholders:
- %c char
- %d int
- %f float
- %lf double
- %s string
- These are used in the format string of printf to format output values.
- You can control field width and alignment using placeholders like %d with width specifiers such as %1d, %3d, %03d, etc.
- Examples show how width affects display (e.g., leading spaces or leading zeros).
- For floating values, specify both field width and precision: e.g., %f, %.2f, %6.2f, %010.4f.
- Examples illustrate alignment, padding, and decimal precision.
- scanf() copies data entered from the keyboard into variables.
- It uses the same set of placeholders as printf depending on expected data types.
- Each variable in the input list must be preceded by the address operator & (i.e., the ampersand).
- The order of placeholders must match the order of the variables in the input list.
scanf() SYNTAX AND EXAMPLES
scanf("%d %f", &age, &weight);
ARITHMETIC EXPRESSIONS (USAGE)
- Write arithmetic expressions to manipulate data; operators operate on two operands (which may be constants, variables, or other expressions).
- Example: 2 + 1; 2 + 1 is an expression with + as the operator and 2, 1 as operands.
- Binary operators require two operands.
ARITHMETIC OPERATOR SUMMARY
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Modulus: %
- Examples (as shown in typical outputs):
- 5 + 2 is 7
- 5.0 + 2.0 is 7.0
- 5 * 2 is 10
- 5 / 2 is 2.5 (float) or 2 (int)
- 5 % 2 is 1
INCREMENT AND DECREMENT OPERATORS
- C provides ++ (increment) and -- (decrement).
- n++ is equivalent to n = n + 1; n-- is equivalent to n = n - 1.
- They can be used in prefix (before) or postfix (after) form, with different evaluation orders.
INCREMENT/DECREMENT: EXAMPLE
#include <stdio.h>
int main() {
int k = 5; int x, y;
x = k++;
y = ++k;
printf("%d\n", x);
printf("%d\n", y);
printf("%d\n", k);
return 0;
}
- Translating common formulas into C expressions:
- b² – 4ac → b2−4ac
- a + b - c → a+b−c
- a + b → a+b
- (a + b) / (c + d) → c+da+b
- 1/(1 + x * x) → 1+x21
- -a(b + c) → −a(b+c)
- The material covers foundational concepts for variables, data types, constants, I/O, and basic expressions in C.
- Review the examples provided and practice writing and reading C programs to reinforce syntax rules, data types, and I/O operations.