Unit-1.2.pptx Removed
Unit-1.2.pptx Removed
Executing A C Program
Type Conversion
•Logical "and" and "or" are represented with && and ||.
‘C’
TOKENS
VARIOUS C TOKENS
In a passage of text, individual words and punctuation marks are called
tokens. This are the smallest individual units are known as C tokens. C has
SIX types of tokens,.
C TOKENS
i. Fractional Constant
ii. Exponential Constant
Datatypes
Data Types
in C
Enumeration
Basic Data Derived Data User-Defined
and Void
Types Types Data Types
Types
Basic Data Types
• int: Used to store integers (whole numbers). Size: 4 bytes.
• Example: int age = 25;
• union: Stores different data types in the same memory location (one at a
time).
• Example:
union Data
{
int i;
float f;
char str[20];
};
Size and Range
• Size: The size of a data type determines how much memory is allocated for
it in bytes.
• For example, `int` typically takes 4 bytes, `float` takes 4 bytes, and
`double` takes 8 bytes.
• The size can vary depending on the system architecture (32-bit vs
64-bit).
• Range: The range of a data type is the minimum and maximum values it
can hold. It is directly related to the size.
• For example, a 4-byte `int` can store values from -2,147,483,648 to
2,147,483,647, while a `float` can store decimal values between
approximately 3.4E-38 and 3.4E+38.
• Platform Dependency: The size and range of data types may vary slightly
depending on the platform and compiler being used.
• For example, `long int` may be 4 bytes on a 32-bit system but 8 bytes on
a 64-bit system.
Qualifiers
• Signed/Unsigned: These qualifiers modify the range of a data type.
• A signed type can hold both negative and positive values (e.g., `int` is
signed by default), while an unsigned type only holds positive values,
extending the upper limit of the range.
• For example, `unsigned int` can range from 0 to 4,294,967,295.
• Short/Long: These qualifiers adjust the size of the integer data type.
• A short integer uses less memory (typically 2 bytes), and a long integer
allows larger values (typically 8 bytes in a 64-bit system).
• For example, `long int` allows storing larger integers than `int`.
• Volatile/Const: The `volatile` qualifier tells the compiler that the variable's
value can change unexpectedly (e.g., in embedded systems).
• The `const` qualifier indicates that a variable's value cannot be modified
once initialized.
Rules for Constructing Integer Constants
• No decimal point: Integer constants are whole numbers without any decimal
point.
• Range limitations: Integer constants must lie within the range defined by the
data type (int, long, etc.), otherwise an overflow error occurs.
Rules for Constructing Real Constants
(Fractional Form)
• Contains a decimal point: A real constant must include a decimal point
(e.g., 3.14).
• Optional fractional part: The number can have a fractional part after
the decimal point (e.g., 10.0 is valid, as is 0.25).
• Optional leading digits: Leading digits before the decimal point can be
omitted if the number starts with 0. (e.g., .5 is valid and represents 0.5).
Rules for Constructing Real Constants
(Exponential Form)
• Exponential notation: Real constants in exponential form are written as mEp
where m is the mantissa and p is the exponent (e.g., 2.5E3 is 2.5 * 10^3).
• Decimal point in mantissa: The mantissa may or may not contain a decimal point
(e.g., 1E6 and 1.0E6 are both valid).
• No spaces: There must be no spaces between the mantissa, E, and exponent (e.g.,
1.23 E4 is invalid, but 1.23E4 is valid).
Rules for Constructing Character Constants
• Single character enclosed in single quotes: A character constant is
enclosed in single quotation marks (e.g., 'A’).
• Only one character: It can hold only one character (e.g., 'A' is valid, but
'AB' is invalid).
• ASCII value storage: The character constant stores the ASCII value of
the character, not the character itself.
• Unsigned type: Character constants are of type int, so their values are
stored as integers in the range of valid ASCII values (0-255).
Variables
• In C programming, a variable is a named storage location in the
computer’s memory that can hold a value, which can be modified during
program execution.
• Variables allow programs to store and manipulate data dynamically.
• Key Concepts of Variables:
• Variable Declaration: Before using a variable in a C program, it must
be declared.
• Declaring a variable means specifying its type (what kind of data it
can store) and its name (a unique identifier). For example:
•int age;
•float height;
•char grade;
Rule for creating variable name
• Starts with a letter or underscore: A variable name must start with
either a letter (uppercase or lowercase) or an underscore (_). It cannot
start with a digit. For example, int age; or int _count; are valid, but int
1stNumber; is invalid.
• Only letters, digits, and underscores: A variable name can only consist
of letters (uppercase or lowercase), digits, and underscores. Special
characters like @, #, &, or spaces are not allowed. For example,
total_amount is valid, but total-amount or total amount is invalid.
• Case-sensitive: Variable names are case-sensitive. This means that Sum,
sum, and SUM are considered three different variables.
• No reserved keywords: Variable names cannot be any of the C
language reserved keywords (like int, return, for, etc.). For example, int
return; is invalid because return is a reserved keyword in C.
• Length restrictions: While C allows variable names of any length,
some compilers may only recognize the first 31 characters of an
identifier. Keeping variable names concise yet descriptive is generally a
good practice.
Declaring Variables
A variable is a named memory location in which data of a certain type can be
stored. The contents of a variable can change, thus the name. User defined
variables must be declared before they can be used in a program.
• It is during the declaration phase that the actual memory for the variable is
reserved. All variables in C must be declared before use.
• Get into the habit of declaring variables using lowercase characters.
• Remember that C is case sensitive, so even though the two variables listed
below have the same name, they are considered different variables in C.
sum Sum
main()
{
int sum;
Initializing Variables
• C Variables may be initialized with a value when they are declared. Consider
the following declaration, which declares an integer variable count which is
• initialized to 10.
• int count = 10;
• In general, the user should not assume that variables are initialized to some
default value “automatically” by the compiler.
• Programmers must ensure that variables have proper values before they are
used in expressions.
Initializing Variables Example
}
Subprogram Section
Function 1
Function 2
(User Defined Functions)
----
----
Function n DEMO
Explanation of the Sections
• Documentation Section: Provides information about what the program does.
Typically, you write comments here to explain the functionality.
• Link Section: Includes necessary libraries using #include statements. In this
example, we include the stdio.h library for input/output functions like printf().
• Definition Section: Contains macro definitions or constants. Here, #define PI
3.14159 defines the value of PI.
• Global Declaration Section: Declares global variables that are accessible throughout
the program, such as global_var.
• Main Function Section: The entry point of the program where the program
execution starts. Inside the main() function, we declare local variables, perform
operations, and call subprograms.
• Subprogram Section: Defines additional functions that are used to modularize the
code. Here, we have a subprogram() function that calculates and prints the area of a
circle.
Canonical First Program
• • The following program is written in the C programming language:
• There are some exceptions however. This has to do with the \ and % characters.
These characters are modifiers, and for the present the \ followed by the n
character represents a newline character.
Escape sequences
•\n new line character
•\t horizontal tab
•\v vertical tab
•\a alarm
•\b backspace
•\” prints the double quote
•\’ prints the single quote.
•\\ prints the backslash character itself.
Format Specifiers Table
• The following table show what format specifiers should be used with what
data types:
OUTPUT & COMMENTS
• Thus the program prints
• Hello World!
And the cursor is set to the beginning of the next line. As we shall see later
on, what follows the \ character will determine what is printed (i.e., a tab,
clear screen, clear line, etc.)
• /* My first program */
• Comments can be inserted into C programs by bracketing text with the /* and
*/ delimiters. comments are useful for a variety of reasons.
• Primarily they serve as internal documentation for program structure
and functionality.
PROCESS OF COMPILING
&
RUNNING C PROGRAM
Compiling & Running A Program
Compiling & Running A Program - Explanation
• Write/Edit Source Code: The process starts with writing or editing the C source
code using an editor.The source code is written in plain text and saved with a .c
extension.
• Compile Source Code: The written source code is passed to the C Compiler, which
translates the high-level C code into object code (machine code).The compiler checks
for syntax errors in the code. Syntax errors occur if there is any mistake in the
language's grammar (e.g., missing semicolons or incorrect function names).
• Syntax Error Check: If syntax errors are found, the compiler provides error
messages, and the programmer needs to go back and fix the code. Once the errors are
corrected, the code is recompiled. If no syntax errors are found, the compilation
process continues to the next stage.
• Linker and Loader: The linker combines the object code with other code libraries
(from the System Library) that are required to create the final executable program.
The loader loads the program into memory so that it can be executed.
• Input Data: If the program requires input data, the input is provided at this stage. This
data is then used in the execution process.
• Execute Object Code: The object code is executed by the system. The program runs
using the provided input data.
• Logic/Data Error Check: During execution, if there are logic or data errors, the program
may not function as expected. These errors typically occur due to incorrect logic or
incorrect handling of input data. If errors occur, the program needs to be revised, and the
process may loop back to write/edit source code or further debugging.
• See Output: If there are no errors (syntax, logic, or data), the program successfully runs,
and the user can see the output.
• Error Loops-
• Syntax Errors: If syntax errors are encountered, the process loops back to the editing
stage.
• Logic Errors: If there are logic errors during execution, the process loops back to
correct the logic in the code.
Debugging: types of error
There are three basic errors:
❖Syntax/compilation error
❖Run-time exception error
❖logic error
🡪Syntax/compilation error
Error during compiling, prevents getting a compiled code. Modern compilers
indicate well the location of the error. Sometimes problems with delineators
such as semi-colons in C The difficulty is that compiler misses the error long
pass where the missing delineator is required.
🡪Run-time Exception error
When you get an error message while running the compiled code. such as C
seem to have only one type of error; Segmentation Fault,
🡺Logical Error:
Theses errors are the hardest to correct or detect. The program "runs" but the
output is not correct.
• Tools for Detecting and fixing logical error:
• Choose test cases well.
• Try to cover everything with small cases.
• Try one big case.
• Print intermediate value.
Type Conversion
• When it happens-
• In mixed-type expressions (e.g., adding int and float).
• When assigning a value of one type to a variable of another type.
• Promotion rules-
• In expressions involving different data types, the smaller data type is
promoted to the larger one (e.g., int to float, char to int).
• Example
• int x = 10;
• float y = 3.5;
• float result = x + y; // Here, `x` is automatically converted to `float`
• Syntax-
• (new_data_type) expression;
• Example-
• int x = 5; float y = (float)x; // Here, `x` is explicitly cast to `float`
• Use Cases-
• When assigning a larger data type to a smaller data type (e.g., double to
int).When precision or behavior needs to be controlled explicitly in
mixed-type expressions.
• int a = 10, b = 3;
• float result;
• result = (float)a / b; // Here, `a` is cast to float to ensure floating-point
division
Data Loss in Type Conversion
•Implicit conversions can lead to loss of precision or data
truncation, especially when converting from a larger to a
smaller data type:
•Example:
•double d = 10.5;
•int i = d; // `i` will be 10, and the decimal part will be
lost.
Operators
Logical Bitwise
Arithmetic Operators
Example –
int a = 10, b = 5;
int sum = a + b; // sum = 15
int difference = a - b; // difference = 5
Relational Operators
•Used to compare two values and return a boolean result (true or
false).
• == (Equal to)
• != (Not equal to)
• > (Greater than)
• < (Less than)
Example –
• >= (Greater than or equal to) int x = 5, y = 10;
if (x < y)
• <= (Less than or equal to)
{
// True: x is less than y
}
Logical Operators
Example –
if (a > 5 && b < 10)
{
// True if both conditions are true
}
Assignment Operators
• Used to assign values to variables.
• = (Simple assignment)
• += (Add and assign)
• -= (Subtract and assign)
• *= (Multiply and assign)
• /= (Divide and assign)
• %= (Modulus and assign)
Example-
int c = 10;
c += 5; // c = c + 5, now c is 15
Example-
int a = 5;
a++; // Now a is 6
Bitwise Operators
• Operate on bits and perform bit-level operations.
• & (AND)
• | (OR)
• ^ (XOR)
• ~ (NOT)
• << (Left shift)
• >> (Right shift)
• : Operate on bits and perform bit-level operations.
Conditional (Ternary) Operator
• A shorthand for an if-else condition.
• ? : - Conditional Operator
Example –
int a = 10, b = 20;
int max = (a > b) ? a : b; // max will be 20
Special Operators
• Sizeof: Returns the size of a variable or data type in bytes.
• Example - int a = 10; int *ptr = &a; // ptr holds the address of a
• Character Input/Output:
• Deals with reading or writing single characters. Commonly uses getchar() and
putchar().
• String Input/Output:
• Used to handle strings (multiple characters). Functions like gets() (deprecated)
and puts() are used.
• File Input/Output:
• Used for reading from or writing to files stored on disk. Functions like fopen(),
fclose(), fscanf(), fprintf(), etc., are used for file operations.
Formatted Input/Output
• printf() Function (Formatted Output)
• The printf() function is used to print formatted output to the screen. It
allows the formatting of variables using format specifiers.
• Syntax- int printf(const char *format, ...);
• Format Specifiers:
• Example-
• char ch;
• printf("Enter a character: ");
• ch = getchar(); // Reads a character from the keyboard
• printf("You entered: %c\n", ch); // Outputs the character
• Example
• char ch = 'A’;
• putchar(ch); // Outputs 'A' to the console
String Input/Output
• gets() and puts() (Deprecated)
• The gets() function reads an entire string (including spaces) until a
newline character is encountered.
• Note: gets() is deprecated due to security issues (buffer overflow). Use
fgets() instead.
• Example
• char name[50];
• fgets(name, 50, stdin); // Reads up to 50 characters or until a
newline
• printf("You entered: %s", name);
File Input/Output
• File I/O in C allows reading from or writing to files stored on the disk.
• File Modes:
• "w": Open a file for writing (creates a new file or truncates an existing one).
• Buffering: C uses a mechanism called buffering for efficiency. When reading or writing
large amounts of data, the system collects data in a buffer (a temporary memory area)
before committing it to input or output devices.
• Flushing the buffer: Use fflush() to flush the output buffer and force the immediate
writing of buffered data to the output stream.
• Example:
• fflush(stdout); // Flush the output buffer to ensure immediate output
• Error Handling in Input/Output-
• Functions like fopen() return a NULL pointer if the file cannot be opened.
• You should always check the return value of functions like scanf() to detect input errors.
• Example: