chtp02
Introduction to C Programming
Objectives
Write simple programs in C.
Use simple input/output statements.
Understand fundamental data types.
Learn computer memory concepts.
Use arithmetic operators and learn their precedence.
Write simple decision-making statements.
Program Structure
Basic Components of a C Program
Comments: Labeled with
//for single-line or/*...*/for multi-line; improve code readability without affecting execution.Preprocessor Directive:
#include <stdio.h>includes standard input/output functions such asprintf.Main Function:
int main(void)is where C programs begin execution. It returns an integer value.
Printing Output
Printing a Simple Message: Using
printfto display text.Example:
printf("Welcome to C!\n");\nis an escape sequence for newline.
Basic Input and Output
Variables and Data Types
Variable Definition: Every variable must be defined with a type before use. Example:
int integer1, integer2;Types:
intfor integers.
Input Using scanf
Example:
scanf("%d", &integer1);reads an integer input by the user.Address Operator:
&indicates the memory location where the data should be stored.
Arithmetic Operators
C uses operators like
+,-,*,/for operations. The remainder operator%finds out division remainders, e.g.,7 % 4results in3.Integer Division: E.g.,
7 / 4yields1.
Operator Precedence
Parentheses
()Multiplication
*, Division/, Remainder%Addition
+, Subtraction-Assignment
=
Decision Making in C
If Statement: Executes a block of code based on a condition.
Syntax:
if (condition) { /* statements */ }Example: Checks equality with operators:
==,!=,<,>,<=,>=.
Programming Best Practices
Indentation and Comments: Enhance code readability. Every function should have a comment describing its purpose.
Variable Naming: Use meaningful names for clarity.
Avoid Confusing Operators: Distinguish between the assignment operator
=and equality operator==.