Unit 1-2
Unit 1-2
C PROGRAMMING BASICS
1. Documentation section
2. Link section
3. Definition section
4. Global definition section
5. Main () function section
{
Declaration part
Execution part
}
6. Sub program section
{
Function-1
Function-2
….
…. User defined functions
….
Function-n
}
1.4 TOKENS
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions
they are used to perform. The types of C tokens are as follows
✓ Keywords
✓ Identifiers
✓ Constants
✓ Strings
✓ Special Symbols
✓ Operators
1.4.1 Keyword
➢ Since keywords are referred names for a compiler, they cannot be used as variable
names. C language supports 32 keywords which are given below
1.4.2 Identifiers
✓ Identifiers are used as the general terminology for the naming of variables,
functions, and arrays.
✓ Once declared, you can use the identifier in later program statements to refer to the
associated value.
Rules for Naming Identifiers
Certain rules should be followed while naming C identifiers which are as follows:
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.
1.4.3 Constants
Integer Constant
Numeric
Constant
Real Constant
CONSTANT
Single Constant
Character
Constant
String Constant
INTEGER CONSTANT
An integer constant refers to a sequence of digits. There are three types of integer
namely;
Decimal Integer Constant
Octal Integer Constant
Hexadecimal Integer Constant
Examples
• ‘123’ is a decimal integer constant representing the value 123.
• ‘-456’ is a decimal integer constant representing the value -456.
• ‘0’ is a decimal integer constant representing the value 0.
• ‘2147483647’ is the largest value a 32-bit signed integer constant can represent.
Suffixes
Suffixes can be added to decimal integer constants to specify their type explicitly:
• ‘U’ or ‘u’ for unsigned int (e.g., 123U).
• ‘L’ or ‘l’ for long int (e.g., 123L).
• ‘UL’, ‘Ul’, ‘uL’, ‘ul’, ‘LU’, ‘Lu’, ‘lU’, or ‘lu’ for unsigned long int (e.g., 123UL).
NOTE: Using decimal integer constants correctly ensures that the program behaves
as expected and avoids issues related to type conversions and overflows.
Usage in C
Octal constants are commonly used in scenarios like setting file permissions or working
with hardware registers.
OUTPUT:
In this example, the octal number 012 is assigned to the variable octalNumber, and when
printed, it shows the decimal equivalent, which is 10.
Note: Avoid using digits 8 and 9 in octal constants since they are not valid in base-8
and will result in a compile-time error.
Syntax:
A hexadecimal integer constant in C is prefixed with ‘0x’ or ‘0X’.
For example
‘0x1A3F’
‘0X7B’
Examples
Usage:
Hexadecimal constants are commonly used for:
Representing memory addresses.
Defining bit masks.
Working with hardware registers.
Representing colors in graphics programming.
Note on Suffixes
Just like decimal integer constants, hexadecimal integer constants can also have suffixes
to indicate their type:
‘U’ or ‘u’ for unsigned int ‘UL’, ‘ul’, ‘LU’, or ‘lu’ for unsigned long int
‘L’or ‘l’ for long int ‘LL’ or ‘ll’ for long long int
By using hexadecimal integer constants, you can make your code more readable and
concise, especially when dealing with low-level programming tasks.
REAL CONSTANTS
Syntax
Real constants can be expressed in decimal form (e.g., 3.14, 0.001, -123.456).
They can also be expressed in exponential (scientific) notation (e.g., 1.23e4,
6.022e23, -2.5e-3), where e or E denotes the exponent part.
Examples
Usage:
STRING CONSTANTS
A string constant is a sequence of character enclosed in a double quotes. The
characters may be letters, numbers, special chracters and blank spaces.
A character constant cannot be a string character.
Example:
1.4.4 OPERATORS
✓ Operators are special symbols that trigger an action when applied to C variables
and other objects.
✓ The data items on which operators act are called operands.
✓ Depending on the number of operands that an operator can act upon, operators can
be classified as follows:
Unary operator
Binary operator
Ternary operator
Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
• Arithmetic operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Bitwise Operator
Arithmetic operator:
Arithmetic operators are the symbols that are used to perform mathematical
operations on operands.
Relational operators
Relational operators are the symbols that are used for comparison between two
values to understand the type of relationship
Logical operator
Logical operators in C are used to combine multiple conditions/constraints.
Logical Operators returns either 0 or 1, it depends on whether the expression result is
true or false. In C programming for decision-making, we use logical operators.
Operator Operation Examples
The logical AND combines two different relational expressions
&& Logical AND in to one. It returns 1 (True), if both expression are true,
otherwise it returns 0 (false).
Assignment operator
Assignment operators are used for assigning value to a variable. The left side
operand of the assignment operator is a variable and right side operand of the
assignment operator is a value. The value on the right side must be of the same data-
type of the variable on the left side otherwise the compiler will raise an error.
Bitwise operator
Bitwise operators also known as bit operators as they work at the bit-level. They
are used to perform bitwise operations in C.
➢ The & (bitwise AND) in C takes two numbers as operands and does AND on
every bit of two numbers. The result of AND is 1 only if both bits are 1.
➢ The | (bitwise OR) in C takes two numbers as operands and does OR on every
bit of two numbers. The result of OR is 1 if any of the two bits is 1.
➢ The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on
every bit of two numbers. The result of XOR is 1 if the two bits are different.
➢ The << (left shift) in C takes two numbers, the left shifts the bits of the first
operand, and the second operand decides the number of places to shift.
➢ The >> (right shift) in C takes two numbers, right shifts the bits of the first
operand, and the second operand decides the number of places to shift.
➢ The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
The operator that requires three operands to act upon is called the ternary
operator.
The conditional operator in C is kind of similar to the if-else statement as it
follows the same algorithm as of if else statement but the conditional operator
takes less space and helps to write the if-else statements in the shortest way
possible.
Syntax :
The conditional operator can be in any on of the following form
variable = Expression1 ? Expression2 : Expression3;
variable = (condition) ? Expression2 : Expression3;
(condition) ? (variable = Expression2) : (variable = Expression3);
The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose. Some of these are listed below:
Brackets []: Opening and closing brackets are used as array element
references. These indicate single and multidimensional subscripts.
Parentheses (): These special symbols are used to indicate function calls and
function parameters.
Braces {}: These opening and ending curly braces mark the start and end of a
block of code containing more than one executable statement.
Comma (,): It is used to separate more than one statement like for separating
parameters in function calls.
Colon (:): It is an operator that essentially invokes something called an
initialization list.
Semicolon (;): It is known as a statement terminator. It indicates the end of
one logical entity. That is why each individual statement must be ended with
a semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication
of variables.
Assignment operator (=): It is used to assign values and for logical
operation validation.
Constants are fixed values that do not Variables are storage locations that
change during the execution of a hold data values which can change
program.In mathematics, they during program execution. In
represent a value that remains the same mathematics, variables represent
throughout a given context. quantities that can vary within a given
problem or equation.
Constants are used when a value is Variables are used to store information
known ahead of time and is not that can change as the program runs,
supposed to be altered. such as user inputs, counters, or
intermediate results of computations.
Constants are immutable (cannot Variables are mutable (can change value
change once defined). throughout the program).
Constants are used for fixed values Variables are used for values that need to
that provide consistency and clarity in change and be manipulated as the program
the code. executes.
Understanding the difference between constants and variables is crucial for writing clear,
maintainable, and efficient code.
1.6 MANAGING INPUT AND OUTPUT OPERATIONS
Input Operations
#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num); // Reads an integer from standard input
printf("You entered: %d\n", num);
return 0;
}
scanf() reads formatted input based on the specified format string. It stops reading when
encountering whitespace (space, tab, newline)
char name[50];
printf("Enter your name: ");
scanf("%s", name); // Reads a string (stops at whitespace)
char sentence[100];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin); // Reads a line of text
2. File Input:
Files can be opened using fopen() and read using fscanf() or fgets():
#include <stdio.h>
int main() {
FILE *fp;
char str[100];
fp = fopen("file.txt", "r"); // Open file for reading
if (fp == NULL) {
perror("Error opening file");
return -1;
}
fscanf(fp, "%s", str); // Read a word from the file
printf("Read from file: %s\n", str);
fclose(fp); // Close the file
return 0;
}
Output Operations
1. Standard Output (stdout):
Output to the console is done using printf():
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
2. File Output:
Files can be opened using fopen() for writing ("w") or appending ("a"), and
data is written using fprintf() or fputs():
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("output.txt", "w"); // Open file for writing
if (fp == NULL) {
perror("Error opening file");
return -1;
}
fprintf(fp, "This is written to the file.\n");
fclose(fp); // Close the file
return 0;
}
Decision-Making in C
Decision-making in C involves evaluating conditions (usually Boolean
expressions) and executing code blocks based on whether the condition is true or false.
The main decision-making statements in C are:
if Statement
if-else Statement
else-if Ladder
switch Statement
if Statement
The if statement evaluates a condition. If the condition is true, it executes the
block of code inside the if statement.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example of if statement:
#include<iostream.h>
int a=18;
void main() {
if (a>=18){
printf(“You are eligible for voting”); }
}
if-else Statement
The if-else statement provides an alternative block of code that executes if the
condition is false.
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
else-if Ladder
The else-if ladder allows for multiple conditions to be checked in sequence. The
first condition that evaluates to true will have its corresponding block executed.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if all conditions are false
}
switch Statement
The switch statement is used for selecting one of many code blocks to execute. It
is particularly useful when you have a variable that can take on multiple discrete values.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases
default:
// Code to execute if expression does not match any case
}
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
Branching in C
Branching allows the program to jump to different parts of the code based on
certain conditions. The primary statements used for branching are goto, break, and
continue.
➢ goto Statement
The goto statement is used to transfer control to the labeled statement. It can make
the program logic hard to follow, so it is generally avoided in structured programming.
Syntax:
goto label;
// Some code
label:
// Code to execute after goto
#include<iostream.h>
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
goto even; // jump to even
else
goto odd; // jump to odd
even:
printf("%d is even", num);
return; // return if even
odd:
printf("%d is odd", num);
}
int main()
{
int num = 26;
checkEvenOrNot(num);
return 0;
}
➢ break Statement
The break statement is used to exit from loops or switch statements prematurely.
Syntax:
break;
➢ continue Statement
The continue statement skips the remaining code in the current iteration of a loop
and proceeds to the next iteration.
Syntax:
continue;
Example of continue Statement in a Loop
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip the even numbers
}
printf("%d\n", i);
}
return 0;
}
These constructs are essential for controlling the flow of a program and making decisions
based on different conditions
One-Dimensional Arrays
Two-Dimensional Arrays
Multi-Dimensional Array
One-Dimensional Arrays:
✓ A one-dimensional array, also known as a linear array, is the simplest
form of an array in C.
✓ It is a list of elements that can be accessed sequentially using an index.
Syntax:
data_type array_name[array_size];
Examples:
int numbers[5] = {1, 2, 3, 4, 5};
Two-Dimensional Arrays:
✓ Two-dimensional arrays can be thought of as an array of arrays, forming a
matrix or a table-like structure.
✓ They are commonly used for representing mathematical matrices or tables
of data.
Syntax:
data_type array_name[rows][columns];
Examples:
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8},{9, 10, 11, 12}};
Multi-Dimensional Arrays:
✓ Arrays with more than two dimensions are called multi-dimensional
arrays.
✓ They are an extension of two-dimensional arrays and can be used to
represent data in multiple dimensions.
Syntax:
data_type array_name[size1][size2][size3]...[sizeN];
Examples:
int threeD[2][3][4]; // 3D array with dimensions 2x3x4
USES OF ARRAY
The size of an array must be specified at compile time, and it cannot be changed
dynamically.
Arrays in C are zero-indexed, meaning the first element is at index 0.
The name of an array acts as a pointer to the first element of the array.
Multi-dimensional arrays are stored in row-major order in memory, meaning the
last index changes the fastest.
String Length
Function: strlen()
Definition: Returns the length of a string (excluding the null
terminator).
Example
#include <string.h>
int len = strlen(str1); // len is 5
String Copy
Function: strcpy()
Definition: Copies one string into another.
Example
#include <string.h>
char dest[10];
strcpy(dest, str1); // dest contains "Hello"
String Concatenation
Function: strcat()
Definition: Appends one string to the end of another.
Example
#include <string.h>
char str3[20] = "Hello";
strcat(str3, " World"); // str3 contains "Hello World"
String Tokenization
Function: strtok()
Definition: Splits a string into tokens based on a delimiter.
Example
#include <stdio.h>
#include <string.h>
char str[] = "Hello,World";
char *token = strtok(str, ",");
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, ",");
}
// Output:
// Hello
// World
String Comparison
Function: strcmp()
Definition: Compares two strings lexicographically.
Example
#include <string.h>
int result = strcmp(str1, str2); // result is 0 if str1 and str2 are equal