Basic Program Structure
October 17, 2024
C Programming Language
• It is a general-purpose programming language.
• It is mainly associated with systems programming,
but theoretically it can be used for programming
different domains including scientific, and business
applications.
• It was developed by Dennis Ritchie (one of the
authors of “The C Programing Language” book).
• It is an expansion of B Language.
• C added something B did not have, which is data type.
Key Terms in C Language
Syntax
• It refers to the set of rules and guidelines that dictate the
structure and format of valid statements or instructions in C.
• These rules define how programs should be written so that the C
compiler can correctly interpret and execute the code.
• Syntax ensures that each statement is understood by the
compiler and the program behaves as expected.
Statement
• A statement is a single line or command that the program
executes.
• Each statement performs a specific action, such as assigning a
value to a variable, calling a function, or controlling the flow of
the program with loops or conditional statements.
• C statements are the building blocks of a program, and each
statement must end with a semicolon (;) to indicate the end of
that instruction.
Types of Statements in C
Expression Statements
• These evaluate expressions and usually perform assignments, function
calls, or arithmetic operations.
Control Flow Statements
• These control the flow of the program such as if, else, while, for.
Compound Statements
• A block of code enclosed in curly braces ({ }) containing multiple
statements.
Expression
• An expression is a combination of variables, constants,
operators, and function calls that are evaluated to produce a
value.
• Expressions can be simple or complex and are evaluated based
on the rules of operator precedence and associativity.
• An expression can serve various purposes, such as assigning
values to variables, performing arithmetic operations, or
evaluating conditions in control statements like if or
while.
• Expressions are fundamental components of most C statements.
Types of Expression in C
Arithmetic Expressions
• Perform arithmetic operations like addition, subtraction, multiplication,
division, etc.
• For example: a + b, x * y - z
Relational Expressions
• Compare values and produce a result of either true (1) or false (0).
• For example: a > b, x == y
Logical Expressions
• Combine multiple conditions using logical operators (&&, ||, !).
• For example: (a > b) && (x < y)
Types of Expression in C
Assignment Expressions
• Assign a value to a variable.
• For example: a = 10, sum = x + y
Conditional Expressions
• Evaluate a condition and return one of two values using the ternary
operator.
• For example: result = (a > b) ? a : b; (This assigns the larger value of a
or b to result).
Compilation
• It is the process by which the source code (written by a
programmer) is translated into machine code (binary code) that
can be executed by a computer’s processor.
• This translation is done by a program called compiler.
Constant
• A constant is a value that cannot be changed during the
execution of a program.
• Once defined, the value of a constant remains fixed.
• Constants are used to represent fixed values such as number,
characters, or strings in the code making it easier to read and
maintain.
• They are typically used when you need to ensure that a value
remains unchanged throughout the program.
• Use the #define preprocessor directive or the const keyword to
define named constants.
Example of Constants in C
Literals
• Literals are values assigned
to variables and constants.
Escape Sequences
• These are special character combinations that are used to
represent characters that cannot be easily typed or printed, such
as newlines, tabs, and backslashes.
• These sequences begin with a backslash (\), followed by a
character that represents a specific control character.
• Escape sequences are commonly used in string and character
literals to perform formatting or represent non-printable
characters.
Common Escape Sequences in c
Escape Description
Sequence
\n Newline (moves to the next line)
\t Tab (inserts a horizontal tab)
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\r Carriage return
\b Backspace
\f Form feed
\0 Null character
Library
• A library in C is a collection of precompiled functions and
routines that programmers can use to simplify complex or
repetitive tasks.
• These libraries contain common code that can be reused across
various programs, eliminating the need to write code from scratch.
• Libraries in C are essential for input/output operations,
mathematical calculations, string manipulations, memory
allocation, and many other tasks.
• Example: stdio.h, math.h, string.h, stdlib.h
• To use a library, you must include its header file in your program
using the #include directive.
Preprocessor Directive
• A preprocessor directive in C is a command that instructs the
compiler to perform specific actions before the actual compilation
of the program begins.
• These directives are processed by the C preprocessor, which runs
before the compiler processes the source code.
• Preprocessor directives are used to manage files, define
constants, and control conditional compilation among other
tasks.
• Preprocessor directives start with the # symbol and are not
terminated by a semicolon.
• Example: #define, #include
#define
• In C Programming Language, the #define is a preprocessor
directive which allows the definition of macros within your source
code.
• The macro definitions allow constant values to be declared for use
throughout your code.
• Macro definitions are not variables and cannot be changed by
your program code like variables.
• You generally use this syntax when creating constants that
represent numbers, strings or expressions.
Syntax:
Note: Do NOT put a semicolon character at the end of #define
Comment
• Comments are non-executable statements used to add
explanatory notes within the code.
• They help make the code more readable and understandable but
are ignored by the compiler during execution.
• Why comments are useful:
• Documentation: Explain what the code does, especially for
complex sections.
• Collaboration: Helps others understand your code.
• Debugging: You can use comments to disable code sections
temporarily during debugging.
Two Types of Comments
• Single-line comments starts with //.
• Multi-line comment starts with /* and ends with */.
Data Types
Data Types
• Data types are essential in programming as they define the kind
of data a variable can hold, influencing how much memory is
allocated and what operations can be performed on that data.
• Understanding data types is crucial for effective programing, as it
ensures that the data is used correctly and efficiently.
Basic Data Types
• C provides several basic data types, each designed for specific kinds of data.
• These include:
Integer Types
• int : Used to store integers (whole number).
• Typically, 4 bytes (varies with system architecture).
Floating-Point Types
• float : Used to store single-precision floating-point numbers (decimals).
• Typically, 4 bytes.
• About 6-7 decimal digits.
• double: Used for double-precision floating-point numbers
• Typically, 8 bytes.
• About 15 decimal digits.
Basic Data Types
Character Type
• char : Used to store single character.
• Typically, 1 byte.
Modifiers for Data Types
• C provides type modifiers that can alter the properties of the basic
data types.
• These modifiers help specify the size and sign of the data type.
Sign Modifiers
• signed: Indicates that a variable can hold both positive and
negative values.
• unsigned: Indicates that a variable can only hold non-negative
values.
Size Modifiers
• short: Used with int to reduce the size (e.g., short int).
• long: Used with int and double to increase the size (e.g., long int,
long double).
Derived Data Types
• C also includes derived data types that allow for more complex data
management:
Array
• An array is a collection of variables of the same type, stored in
contiguous
memory location.
Structures
• A structure is a user-defined data type that groups variables of
different data types under a single name.
Pointers
• A pointer is a variable that stores the memory address of another
variable.
Derived Data Types
Unions
• A union is similar to a structure, but it allows storing different data
types in the same memory location.
• Only one member can be accessed at a time.
Enumerations
• An enumeration (enum) is a user-defined type consisting of a set of
named integer constants.
Commonly
Used Data
Types in C
Variables
Variables
• A variable is a symbolic name associated with a memory location
that holds data.
• The data stored in a variable can be modified during program
execution.
• Variables are used to store data values, allowing programs to
manipulate and work with data dynamically.
Variable Declaration
• A variable must be declared before it can be used.
• The declaration specifies the variable’s name and its data type,
informing the compiler of the variable’s intended use.
Syntax:
datatype varialbeName;
Examples:
int age;
float salary;
char grade;
Variable Initialization
• Initialization is the process of assigning a value to a variable at the
time of declaration.
• If a variable is not initialized, it may contain a garbage value (an
unpredictable value).
Syntax:
datatype varialbeName = value;
Examples:
int age = 29;
float salary = 50.24;
char grade = ‘A’;
Rules for Naming Identifiers (Variable)
1. A valid identifiers can have letters (both uppercase and lowercase),
digits and underscores ( _ ).
2. Names are case-sensitive (age and Age are different variables).
3. The first character of an identifier should be either a letter or an
underscore.
4. You cannot use keywords like int, while, for, if , long etc., as identifiers.
5. No whitespace is allowed within the variable name.
Best Practices
• Use meaningful names that indicate the purpose of the variable (e.g.,
totalMarks, userAge).
• Follow a consistent naming convention (e.g., camelCase, snake_case).
• Keep names concise but descriptive.
C Identifiers
• Identifiers refers to name given to entities such as variables,
functions, structures etc.
• Identifiers must be unique.
• They are created to give unique name to an entity to identify it
during the execution of the program.
• For example:
• Here, money and accountBalance are identifiers.
• Also remember, identifier names must be different from
keywords.
• You cannot use int as an identifier because int is a keyword.
C Reserved Keywords
• As C is a case sensitive
language, all keywords must
be written in lower case.
• All these keywords, their
syntax and application will
be discussed in their respective
topics.
Scope of Variables
• The scope of variable determines its visibility and lifetime
within a program.
• There are two primary types of scopes:
• Local Variables
• Global Variables
Local Variables
• Variables declared inside a function or a block.
• They are only accessible within that function or block.
• Exist only during the execution of that function/block.
• Example:
void function() {
int localVar = 10; // localVar is accessible only within function
}
Global Variables
• Variables declared outside of any function.
• They are accessible from any function within the same file or
across files if declared with extern.
• Exists for the duration of the program.
• Example:
int globalVar = 20; // Accessible in any function
void function() {
print(“%d”, globalVar); // Accessing global variable
{
Operators
What is an Operator?
• An operator is a symbol that operates on a value or
variable.
• For example: + is an operator to perform addition.
• C has a wide range of operators to perform various
operations.
• Arithmetic
• Assignment
• Relational
• Logical
Arithmetic Operators in C
• An arithmetic operator performs mathematical operations
such as addition, subtraction, multiplication, division
etc., on numerical values (literals and variables).
Example: Arithmetic Operators
• The operators +, -, * computes addition,
subtraction and multiplication
respectively as you might have expected.
• In normal calculation, 9/4 = 2.25,
however the output is 2 in the program.
• It is because both the variables a and b
are integer, hence the output is also
an integer.
• The compiler neglects that term after the
decimal point and shows answer 2
instead 2.25.
• The modulo operator % computes the
remainder.
• The modulo operator can only be used
with integers.
Assignment Operators in C
• An assignment operator is used for assigning a value to a
variable.
• The most common assignment operator is = .
Example: Assignment Operators
OUTPUT:
c=5
c = 10
c=5
c = 25
c=5
c=0
Relational Operators in C
• A relational operator
checks the relationship
between two operands.
• If the relation is true it
returns 1; if the
relationship is false, it
returns value 0.
• Relational operators are
used in decision making
and loops.
Relational Operators in C
• A relational operator
checks the relationship
between two operands.
• If the relation is true it
returns 1; if the
relationship is false, it
returns value 0.
• Relational operators are
used in decision making
and loops.
Relational Operators in C
• A relational operator
checks the relationship
between two operands.
• If the relation is true it
returns 1; if the
relationship is false, it
returns value 0.
• Relational operators are
used in decision making
and loops.
Relational Operators in C
• A relational operator
checks the relationship
between two operands.
• If the relation is true it
returns 1; if the
relationship is false, it
returns value 0.
• Relational operators are
used in decision making
and loops.
Relational Operators in C
• A relational operator
checks the relationship
between two operands.
• If the relation is true it
returns 1; if the
relationship is false, it
returns value 0.
• Relational operators are
used in decision making
and loops.
Relational Operators in C
• A relational operator
checks the relationship
between two operands.
• If the relation is true it
returns 1; if the
relationship is false, it
returns value 0.
• Relational operators are
used in decision making
and loops.
Relational Operators in C
• A relational operator
checks the relationship
between two operands.
• If the relation is true it
returns 1; if the
relationship is false, it
returns value 0.
• Relational operators are
used in decision making
and loops.
Example: Relational Operators
Logical Operators in C
• An expression
containing logical
operator returns either
0 or 1 depending
whether expression
results is true or false.
• Logical operators are
commonly used in
decision making.
Example: Logical Operators
Output & Input
C Output
• In C programming, printf() is one of the main output
function.
• The function sends formatted output to the screen.
• For example:
How does a Program Work?
• All valid C programs must contain the main() function.
• The code execution begins from the start of the main()
function.
• The printf() is a library function to send formatted output
to the screen.
• The printf() function prints the string inside the “double
quotation mark”.
• To use printf() in our program, we need to use stdio.h
(header file) using the #include <stdio.h> statement.
• The return 0; statement inside the main function is the Exit
Status of the program, and it is OPTIONAL.
Output int (Integer)
• We use %d format
specifier to print int types.
• Here, the %d inside the
quotations will be replaced
by the value of
testInteger.
Output float & double
• To print float, we use %f
format specifier.
• Similarly, we use %lf to print
double.
Output char (Character)
• To print char, we use %c
format specifier.
C Input
• In C programming, scanf() is one of the commonly
used function to take input from the user.
• The scanf() function reads formatted input from the
standard input (keyboard).
Input int (Integer)
• Here, we have used %d format
specifier inside the scanf() function
to take integer input from the user.
• When the user enters an integer, it is
stored in the testInteger variable.
• Notice, that we have used
&testInteger inside scanf().
• It is because &testInteger gets
the address of testInteger, and the
value entered by the user is stored
in that address.
Input char (Character)
• When character is entered by
the user, the character itself is
not stored, instead an integer
value (ASCII value) is stored.
• And when we display that
value using %c, the entered
character is displayed.
• If we use %d to display the
character, its ASCII value is
printed.
Input float & double
• We %f and %lf format
specifier for float and double
respectively.
Input/Output Multiple Values
• Here’s how you can take
multiple inputs from the
user and display them..
Format
Specifiers in
C
Common Format Specifiers
• As you can see from the
examples, we used the following
format specifiers.
Supplementary Materials
• [Link] – Int, Float, and Double
Data Types
• [Link] – short, long, long long
variables (Integers)
• [Link] – Constants in C
Thank you and stay
safe!
Do you have any questions?