C Language Notes - Target Computer Exams
C Language Notes - Target Computer Exams
Computer programming is a medium for us to communicate with computers, just like we use
Hindi or English to communicate with each other. Programming is a way for us to deliver our
instructions to the computer.
What is C?
C is a procedural programming language initially developed by Dennis Ritchie in the
year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system
programming language to write the UNIX operating system.
C Compiler
C compiler is a software that translates human-readable C language code into machine code or an
intermediate code that can be executed by a computer’s central processing unit (CPU).
There are many C compilers available in the market, such as GNU Compiler Collection (GCC), Microsoft
Visual C++ Compiler, Clang, Intel C++ Compiler, and TinyCC (TCC)
The basic structure of a C program
All c programs have to follow a basic structure. A c program starts with the main function and
executes instructions presents inside it. Each instruction terminated with a semicolon(;)
There are some basic rules which are applicable to all the c programs:
[Link] program's execution starts from the main function.
[Link] the statements are terminated with a semi-colon.
[Link] are case-sensitive.
[Link] are executed in the same order in which they are written.
Comments
Comments are used to clarify something about the program in plain language. It is a way for us to
add notes to our program. There are two types of comments in c:
[Link] line comment: //This is a comment.
[Link]-line comment : /*This is multi-line comment*/
Comments in a C program are not executed and ignored.
Preprocessors are programs that process the source code before compilation. Several
steps are involved between writing a program and executing a program in C
Compilation and execution
A compiler is a computer program that converts a c program into machine language so that it can be
easily understood by the computer.
A program is written in plain text. This plain text is a combination of instructions in a particular sequence.
The compiler performs some basic checks and finally converts the program into an executable.
Tokens in C
A token in C can be defined as the smallest individual element of the C programming language
that is meaningful to the compiler. It is the basic component of a C program.
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
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names because by doing so,
we are trying to assign a new meaning to the keyword which is not allowed. You cannot
redefine keywords. However, you can specify the text to be substituted for keywords
before compilation by using C preprocessor directives. C language supports 32 keywords
which are given below:
Identifiers
Identifiers are used as the general terminology for the naming of variables, functions,
and arrays. These are user-defined names consisting of an arbitrarily long sequence
of letters and digits with either a letter or the underscore(_) as a first character.
Identifier names must differ in spelling and case from any keywords. You cannot use
keywords as identifiers; they are reserved for special use. Once declared, you can use
the identifier in later program statements to refer to the associated value. A special
identifier called a statement label can be used in goto statements.
Rules for Naming Identifiers int var1; // it is correct
Certain rules should be followed while naming c int 1var; // it is incorrect – the name of the
identifiers which are as follows: variable should not start using a number
int my_var1; // it is correct
•They must begin with a letter or underscore(_).
int my$var // it is incorrect – no special
•They must consist of only letters, digits, or characters should be in the name of the varia
underscore. No other special character is allowed. char else; // there must be no keywords in the
•It should not be a keyword. name of the variable
•It must not contain white space. int my var; // it is incorrect – there must be no
•It should be up to 31 characters long as only the first spaces in the name of the variable
31 characters are significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.
Constants
The constants refer to the variables with fixed values. They are like normal variables but with
the difference that their values can not be modified in the program once they are defined.
Constants may belong to any of the data types.
const int c_var = 20;
Operators
Operators are 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 Operators: Those operators that require only a single operand to act upon are known as
unary [Link] Example increment and decrement operators
•Binary Operators: 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
•Ternary Operator: The operator that requires three operands to act upon is called the ternary
operator. Conditional Operator(?) is also called the ternary operator.
Types of Primary/ Primitive Data Types in C Language
Basic Input and Output in C
C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and output.
scanf()
The scanf() method, in C, reads the value from the console as per the type specified and store
it in the given address.
Syntax:
scanf("%X", & variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable
and & is the address operator in C, which tells the compiler to change the real value of variableOfXType,
stored at this address in the memory.
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed
or scanned in input and output operations. They always start with a % symbol and are
used in the formatted string in functions like printf(), scanf,
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the
console screen.
Syntax:
printf("%X", variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of
data is in a variable and variableOfXType is the variable to be printed.
int a = 10;
int b = -a; // b = -10
Unary minus is different from the subtraction operator, as subtraction requires two operands.
sizeof()
This operator returns the size of its operand, in bytes. The sizeof() operator always
precedes its operand. The operand is an expression, or it may be a cast.
Note: The `sizeof()` operator in C++ is machine dependent. For example, the size of an ‘int’
in C++ may be 4 bytes in a 32-bit machine but it may be 8 bytes in a 64-bit machine.
#include <stdio.h>
int main()
{
// printing the size of double and int using sizeof
printf("Size of double: %d\n", sizeof(double)); Size of double: 8
printf("Size of int: %d\n", sizeof(int)); Size of int: 4
return 0;
}
Arithmetic Operations in C
a is 10 and b is 4
a + b is 14
a - b is 6
a * b is 40
a / b is 2
a % b is 2
Relational Operators in C
The relational operators in C are used for the comparison of the two operands. All these
operators are binary operators that return true or false values as the result of comparison.
Result either 0 or 1. Here, 0 means false and 1 means true.
These are a total of 6 relational operators in C:
S. No. Symbol Operator Description Syntax
Returns true if
both the
1 && Logical AND
operands are
a && b
true.
Returns true if
both or any of
2 || Logical OR
the operand is
a || b
true.
Returns true if
3 ! Logical NOT the operand is !a
false.
Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands. Mathematical operations such as addition, subtraction, multiplication, etc. can be
performed at the bit level for faster processing.
S. No. Symbol Operator Description Syntax
Performs bit-by-bit AND operation and returns
1 & Bitwise AND a&b
the result.
Performs bit-by-bit OR operation and returns
2 | Bitwise OR a|b
the result.
Performs bit-by-bit XOR operation and returns
3 ^ Bitwise XOR a^b
the result.
4 ~ Bitwise First Complement Flips all the set and unset bits on the number. ~a
Explanation:
•#include <stdio.h> – This line includes the standard input-output library in the program.
•int main() – The main function where the execution of the program begins.
•printf(“Hello, World!\n”); – This function call prints “Hello, World!” followed by a new line.
•return 0; -This statement indicates that the program ended successfully.
What will be the output of the following C code?
Decision Making in C
The conditional statements (also known as decision control structures) such as if, if else,
switch, etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or
more conditions and make the decision whether to execute a set of statements or not.
These decision-making statements in programming languages decide the direction of the
flow of program execution.
if in C
The if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statements is executed otherwise not.
i is greater than 15
i is smaller than 15
i is smaller than 12
too
if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options. The C if
statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the C else-if ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed. if-else-if
ladder is similar to the switch statement.
i is 20
switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement. The switch
block consists of cases to be executed based on the value of the switch variable.
Case 2 is executed
Case 1 is executedCase 2 is executedDefault Case is executed
Jump Statements in C
These statements are used in C for the unconditional flow of control throughout the
functions in a program. They support four types of jump statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break statement
is encountered from within a loop, the loop iterations stop there, and control returns from
the loop immediately to the first statement after the loop.
Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs,
and continues with the next iteration in the loop.
This example skips the value of 4:
What is goto Statement in C?
The goto statement is used to transfer the program's control to a defined label within the
same function. It is an unconditional jump statement that can transfer control forward or backward.
The goto keyword is followed by a label. When executed, the program control is redirected to the
statement following the [Link] the label points to any of the earlier statements in a code, it
constitutes a loop. On the other hand, if the label refers to a further step, it is equivalent to a
Jump.
End of program
Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar to the if-
else statement. It is also known as the ternary operator as it works on three operands.
(condition) ? [true_statements] : [false_statements];
[Link] Controlled loops: In Exit controlled loops the test condition is evaluated at the
end of the loop body. The loop body will execute at least once, irrespective of whether
the condition is true or false. do-while Loop is Exit Controlled loop.
for Loop
for loop in C programming is a repetition control structure that allows programmers to write
a loop that will be executed a specific number of times. for loop enables programmers to
perform n number of steps together in a single line.
Hello World
Name Description
the break statement is used to terminate the switch and loop
break statement statement. It transfers the execution to the statement
immediately following the loop or switch.
goto statement goto statement transfers the control to the labeled statement.
Infinite Loop
An infinite loop is executed when the test expression never becomes false and the body of the
loop is executed repeatedly. A program is stuck in an Infinite loop when the condition is always
true. Mostly this is an error that can be resolved by using Loop Control statements.
Loop Type Description
first Initializes, then condition check, then executes the body
for loop
and at last, the update is done.
do-while first executes the body and then the condition check
do-while loop
is done.
The C code ‘for( ; ; )’ represents an infinite loop. It can be terminated by ___________
a) break
b) exit(0)
c) abort()
d) terminate
View Answer
Answer: a
Function prototype:
Function prototype is a way to tell the compiler about the function we are going to define in the program.
Here void indicates that the function returns nothing.
Function call:
Function call is a way to tell the compiler to execute the function body at the time the call is made.
Note that the program execution starts from the main function in the sequence the instructions are written.
Function definition:
This part contains the exact set of instructions that are executed during the function call. When a function is
called from main(), the main function falls asleep and gets temporarily suspended. During this time, the
control goes to the function being called when the function body is done executing main() resumes.
Function Declarations
In a function declaration, we must provide the function name, its return type, and the number and
type of its parameters. A function declaration tells the compiler that there is a function with the
given name defined somewhere else in the program.
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside the function.
Only one value can be returned from a C function. To return multiple values, we have to use pointers or structures.
Function Arguments
Function Arguments (also known as Function Parameters) are the data that is passed to a function.
int function_name(int var1, int var2);
factorial(n) = 1x 2 x 3...........x n
factorial(n)= 1 x 2 x 3...........n-1 x n
It is very important to
note that the array index
starts with 0.
C Array Declaration
In C, we have to declare the array like any other variable before using it. We can declare an array
by specifying its name, the type of its elements, and the size of its dimensions. When we declare
an array in C, the compiler allocates the memory block of the specified size to the array name.
The size of the above arrays is 5 which is automatically deduced by the compiler
Access Array Elements
We can access any element of an array in C using the array subscript operator [ ] and the
index value i of the element.
array_name [index];
array_name[i] = new_value;
marks[0]=33;
marks[1]=12;
C Array Traversal
Traversal is the process in which we visit every
element of the data structure. For C array
traversal, we use loops to iterate through each
element of the array.
return 0;
}
Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as follows:
[Link]-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They can be
visualized in the form of rows and columns organized in a two-dimensional plane.
array_name[size1] [size2];
int arr [3][2] ={
{1,4}
{7,9}
{11,22}
};
We can access the elements of this array as arr [0] [0], arr [0] [1] & so on...
At arr [0] [0] value would be 1 and at arr [0] [1] value would be 4.
Strings in C
A String in C programming is a sequence of characters terminated with a null character ‘\0’. The
C String is stored as an array of characters. The difference between a character array and a C
string is that the string in C is terminated with a unique character ‘\0’.
A string is a 1-d character array terminated by a null(‘\0’) => {this is null character}
The null character is used to denote string termination, characters are stored in contiguous
memory locations
Initializing Strings
Since string is an array of characters, it can be initialized as follows:
You can see in the above program that the string can also
be read using a single scanf statement. Also, you might
be thinking that why we have not used the ‘&’ sign with
the string name ‘str’ in scanf statement! To understand
this you will have to recall your knowledge of scanf.
We know that the ‘&’ sign is used to provide the address
of the variable to the scanf() function to store the value
read in memory. As str[] is a character array so using str
without braces ‘[‘ and ‘]’ will give the base address of this
string. That’s why we have not used ‘&’ in this case as we
are already providing the base address of the string to
scanf.
We can’t read a string value with
spaces, we can use
either gets() or fgets() in the C
programming language.
puts() Function
The puts() function is used to write a string to the console and it automatically adds a new line character
‘\n’ at the end.
puts("str");
Compares the first string with the second string. If strings are
strcmp(str1, str2)
the same it returns 0.
Concat s1 string with s2 string and the result is stored in the first
strcat(s1, s2)
string.
j is a pointer
j points to i.
*(&i) = 72
*(&j) = 87994
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing
operator in the pointer declaration.
datatype * ptr;
•ptr is the name of the pointer.
•datatype is the type of data it is pointing to.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the pointer variable.
We generally use the ( &: ampersand ) addressof operator to get the memory address of a
variable and then store it in the pointer variable.
int **k;
k= &j;
We can even go further one level and create a variable l of type int*** to store the address of k. We
mostly use int* and int** sometimes in real-world programs.
•Dangling pointer: A pointer pointing to a memory location that has been deleted (or
freed) is called a dangling pointer.
Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet. These types of C-
pointers can cause problems in our programs and can eventually cause them to crash. If values is
updated using wild pointers, they could cause data abort or data corruption.
int *ptr;
char *str;
In the above code, we are copying first the content of array a into
array b. So, “hell” gets copied to array b. After that we are copying
the content of array b into array a. Since, array b contained the string
“hell” now, it gets copied to array a. Hence, the final answer will be
“hell, hell”.
In C, you cannot directly assign one array to another using the
assignment operator. Instead, you need to copy the elements
individually
#include <stdio.h>
int main() {
int source[4] = {1, 2, 3, 4};
int destination[4];
return 0;
}
Comment on the following pointer declaration.
int *ptr, p;
a) ptr is a pointer to integer, p is not
b) ptr and p, both are pointers to integer
c) ptr is a pointer to integer, p may or may not be
d) ptr and p both are not pointers to integer
View Answer
Answer: a
A union is a special data type available in C that allows to store different data types in the
same memory location. You can define a union with many members, but only one member
can contain a value at any given time. Unions provide an efficient way of using the same
memory location for multiple purpose.
All the members of a union share the same memory location. Therefore, if we need to
use the same memory location for two or more members, then union is the best data type
for that. The largest union member defines the size of the union.
Enumeration (or enum) in C
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain.
An enum is a special type that represents a group of constants (unchangeable values).
Garbage Value
Memory allocation
Memory allocation refers to assigning a particular space in a computer's memory for a computer program or code.
There are two types of memory allocations.
[Link] Memory allocation
[Link] Memory allocation
The key difference between Static and Dynamic memory allocation is that Static memory allocation allows
fixed memory size after allocation while Dynamic memory allocation allows changes in the memory size
after allocation.
What is Static Memory allocation?
Static memory allocation is also known as Compile-time memory allocation because the memory is
allocated during compile time. In this type of memory allocation, the memory that the program can use is
fixed i.e. we can not allocate or deallocate memory during the program's execution. In many applications, it
is not possible to predict how much memory will be needed by the program at run time.
Properties of Static Memory allocation
[Link] allocation is done during compile time.
[Link] Memory is used here.
[Link] cannot be changed while executing a program.
[Link] static memory allocation is fast and saves running time.
[Link] is less efficient as compared to Dynamic memory allocation.
What is Dynamic Memory allocation?
Dynamic memory allocation is also known as Runtime memory allocation because the memory is allocated
during runtime or program execution. The allocation and release of the memory space can be done using the
library functions of stdlib.h header file. These functions allocate memory from a memory area called heap and
deallocate this memory whenever not required so that it can be used for some other purpose.
malloc()
This function is used to allocate the single block of requested memory. On Success, the malloc() function
returns a pointer to the first byte of the allocated memory. The malloc() function gives a NULL output
when the memory is not enough.
calloc()
The calloc() function is used to allocate the memory as a number of elements of a given size. The calloc()
function is similar to malloc() function. The only difference is that it takes two argument values. The first
argument specifies the number of data items for which space is required, and the second argument
specifies the size of each data item.
realloc()
The realloc() function is used to increase the memory allocated by malloc() or calloc() function. This
function alters the size of the memory block without losing the old data. The realloc() function takes
two argument values. The first argument is a pointer variable to the block of memory that was
previously allocated by calloc() or malloc(), and the second argument is the new size for that memory
block.
free()
When memory is allocated dynamically by the malloc() and calloc() function, it should always be
released when it is no longer required. Otherwise, it will consume memory until the program exit.
The free() function is used to release this allocated memory space.
Static Memory Allocation Dynamic Memory Allocation
It occurs at the time of compilation. It occurs dynamically at the run time.
Here, the compiler allocates the Here, the programmer allocates and
memory. deallocates the memory.
The memory allocation is in the stack. The memory allocation is in the heap.
Here, we can access the memory by Here, we can access the memory with
the variable names. the use of pointers.
Higher risk of memory leaks since the
Lower risk of memory leaks since the
programmer may forget to deallocate
compiler takes care of it.
the memory.
•Static Arrays: Fixed size, allocated at
compile time, faster access, limited
flexibility, and managed automatically
by the compiler.