0% found this document useful (0 votes)
1 views138 pages

C Language Notes - Target Computer Exams

Uploaded by

hemantsh003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views138 pages

C Language Notes - Target Computer Exams

Uploaded by

hemantsh003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is Programming?

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.

How to take input and output of basic types in C?


The basic type in C includes types like int, float, char, etc. Inorder to input or output
the specific type, the X in the above syntax is changed with the specific format
specifier of that type. The Syntax for input and output for these are:
•Integer: •Float:
Input: scanf("%d", &intVariable); Input: scanf("%f", &floatVariable);
Output: printf("%d", intVariable); Output: printf("%f", floatVariable);

•Character: Input: scanf("%c", &charVariable); Output: printf("%c", charVariable);


What is a C Operator?
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables. The values and variables used with operators are called operands. So we
can say that the operators are the symbols that perform operations on operands.
Unary operators in C
Unary operators are the operators that perform operations on a single operand to produce a new value.
Types of unary operators
Types of unary operators are mentioned below:
[Link] minus ( – )
[Link] ( ++ )
[Link] ( — )
[Link] ( ! )
[Link] operator ( & )
[Link]()
1. Unary Minus
The minus operator ( – ) changes the sign of its argument. A positive number becomes negative, and a
negative number becomes positive.

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 the left operand is less than the


1 < Less than right operand. Else false a<b
Returns true if the left operand is greater than
2 > Greater than the right operand. Else false a>b

Returns true if the left operand is less than or


3 <= Less than or equal to equal to the right operand. Else false a <= b

Greater than or Returns true if the left operand is greater than


4 >= equal to or equal to right operand. Else false a >= b

5 == Equal to Returns true if both the operands are equal. a == b


Returns true if both the operands are NOT
6 != Not equal to equal. a != b
Logical Operator in C
Logical Operators are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition in consideration. The result of the
operation of a logical operator is a Boolean value either true or false.

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

Shifts the number in binary form by one place


5 << Bitwise Left shift a << b
in the operation and returns the result.

Shifts the number in binary form by one place


6 >> Bitwise Right shift a >> b
in the operation and returns the result.
Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is
a value. The value on the right side must be of the same data type as the variable on the
left side otherwise the compiler will raise an error.
The assignment operators can be combined with some other operators in C to provide
multiple operations using single operator. These operators are called compound operators.
S. No. Symbol Operator Description Syntax

Assign the value of the right operand to the


1 = Simple Assignment
left operand.
a=b

Add the right operand and left operand and


2 += Plus and assign
assign this value to the left operand.
a += b

Subtract the right operand and left operand


3 -= Minus and assign
and assign this value to the left operand.
a -= b

Multiply the right operand and left operand


4 *= Multiply and assign
and assign this value to the left operand.
a *= b
Conditional Operator ( ? : )
•The conditional operator is the only ternary operator in C.
•Here, Expression1 is the condition to be evaluated. If the condition(Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of
Expression3.
•We may replace the use of if..else statements with conditional operators.
Syntax
operand1 ? operand2 : operand3;
Operator Precedence and Associativity in C
The concept of operator precedence and associativity in C helps in determining which
operators will be given priority when there are multiple operators in the expression. It is
very common to have multiple operators in C language and the compiler first evaluates the
operater with higher precedence. Category Operator Associativity
Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right
Shift << >> Left to right
Easy Trick to Remember the Relational < <= > >= Left to right
Operators Associtivity and Equality == != Left to right
Precedence: PUMA’S REBL TAC Bitwise AND & Left to right
where, P = Postfix, U = Unary, M = Bitwise XOR ^ Left to right
Multiplicative, A = Additive, S = Shift, Bitwise OR | Left to right
R = Relational, E = Equality, B = Logical AND && Left to right
Bitwise, L = Logical, T = Ternary, A = Logical OR || Left to right
Assignment and C = Comma Conditional ?: Right to left
= += -= *= /= %=>>= <<= &= ^=
Assignment Right to left
|=
Comma , Left to right
The 0x or 0X prefix, used in C and in
many languages influenced by C, was
chosen to differentiate hexadecimal
(base 16) constants from octal (base 8)
constants, which have a 0 prefix.
Which of the following is not a valid variable name declaration?
a) int _a3;
b) int a_3;
c) int 3_a;
d) int _3a;
View Answer
Answer: c
Explanation: Variable name cannot start with a digit.

All keywords in C are in ____________


a) LowerCase letters
b) UpperCase letters
c) CamelCase letters Which of the following is not a valid C variable name?
d) None of the mentioned a) int number;
View Answer b) float rate;
Answer: a c) int variable_count;
d) int $main;
View Answer
Answer: d
Explanation: Since only underscore and no other special character is
allowed in a variable name, it results in an error.
C Program to Print “Hello World”

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.

As the condition present in the if statement is false. So,


the block below the if statement is not executed.
I am Not in if
if-else in C
The if statement alone tells us that if a condition is true it will execute a block of statements and
if the condition is false it won’t. But what if we want to do something else when the condition is
false? Here comes the C else statement. We can use the else statement with the if statement to
execute a block of code when the condition is false. The if-else statement consists of two blocks,
one for false expression and one for true expression.

i is greater than 15

The block of code following the else statement is executed


as the condition present in the if statement is false.
Nested if-else in C
A nested if in C is an if statement that is the
target of another if statement. Nested if
statements mean an if statement inside another
if statement.

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];

Value of var when flag is 0: 25


Value of var when flag is NOT 0: -25
Loops
Loops in programming are used to repeat a block of code until the specified condition is met. A loop statement
allows programmers to execute a statement or group of statements multiple times without repetition of code.
There are mainly two types of loops in C Programming:
[Link] Controlled loops: In Entry controlled loops the test condition is checked before
entering the main body of the loop. For Loop and While Loop is Entry-controlled loops

[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.

•Initialization Expression: In this expression, we


assign a loop variable or loop counter to some value.
for example: int i=1;
•Test Expression: In this expression, test conditions
are performed. If the condition evaluates to true then
the loop body will be executed and then an update of
the loop variable is done. If the test expression
becomes false then the control will exit from the loop.
for example, i<=9;
•Update Expression: After execution of the loop body
loop variable is updated by some value it could be
incremented, decremented, multiplied, or divided by
any value.
While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations was
previously known to us but in the While loop, the execution is terminated on the basis of the test
condition. If the test condition will become false then it will break from the while loop else body will
be executed.
do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test
condition which is tested at the end of the body. In the do-while loop, the loop body will execute at
least once irrespective of the test condition.

Hello World

Above program will evaluate (i<1) as false since i = 2. But


still, as it is a do-while loop the body will be executed
once.
Loop Control Statements
Loop control statements in C programming are used to change execution from its normal sequence

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.

continue statement skips the remainder body and immediately


continue statement
resets its condition before reiterating it.

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.

first Initializes, then condition checks, and then executes the


while loop
body, and updating can be inside the body.

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

Which keyword is used to come out of a loop only for


that iteration?
a) break
b) continue
c) return
d) none of the mentioned
View Answer
Answer: b
Which loop is most suitable to first perform the
operation and then test the condition?
a) for loop
b) while loop
c) do-while loop
d) none of the mentioned
View Answer
Answer: c
Functions
A function in C is a set of statements that when called perform some specific task. It is the
basic building block of a C program that provides modularity and code reusability. A
function is a block of code that performs a particular task. A function can be reused by the
programmer in a given program any number of times.
Important Points:
•Execution of a c program starts from main()
•A c program can have more than one function
•Every function gets called directly or indirectly from main()
•There are two types of functions in c. Let's talk about them.
Types of Functions:
•Library functions: Commonly required functions grouped together in a library file on disk.
•User-defined functions: These are the functions declared and defined by the user.
Why use functions?
•To avoid rewriting the same logic again and again
•To keep track of what we are doing in a program
•To test and check logic independently
#include<stdio.h>
void display(); // Function prototype/declaration
int main(){
int a;
display(); // Function call
return(0);
}

void display(){ // Function definition


printf(“Hi I am display”);
}

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.

A function in C must always be declared


globally before calling it.
Function Definition
The function definition consists of actual statements which are executed when the function is called
(i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function definition always
starts with the function declaration so we do not need to declare it explicitly. The below example
serves as both a function definition and a declaration.
Function Call
A function call is a statement that instructs the compiler to execute the function. We use the
function name and parameters in the function call.
Types of function calls
Based on the way we pass arguments to the function, function calls are of two types.
[Link] by value -> sending the values of arguments.
[Link] by reference -> sending the address of arguments

Function call is neccessary to bring the


program control to the function definition. If
not called, the function statements will not
be executed.
Sum is: 40
Function Return Type
Function return type tells what type of value is returned after all function is executed. When we don’t
want to return a value, we can use the void data type.

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);

Types of function calls


Based on the way we pass arguments to the function, function calls are of two types.
[Link] by value -> sending the values of arguments.
[Link] by reference -> sending the address of arguments
Recursion
A function defined in C can call itself. This is called recursion.
A function calling itself is also called a recursive function.
Example of Recursion:
A very good example of recursion is factorial

factorial(n) = 1x 2 x 3...........x n

factorial(n)= 1 x 2 x 3...........n-1 x n

factorial(n)= factorial of (n-1) x n

The condition which doesn’t call the function any further in


a recursive function is called the base condition.
The value obtained in the function is given back to main by using ________ keyword.
a) return
b) static
c) new
d) volatile Which of the following is a correct format for declaration of function?
View Answer a) return-type function-name(argument type);
Answer: a b) return-type function-name(argument type){}
c) return-type (argument type)function-name;
d) all of the mentioned
View Answer
Answer: a
What is Array in C?
An array in C is a fixed-size collection of similar data items stored in contiguous memory
locations. It can be used to store the collection of primitive data types such as int, char, float,
etc., and also derived and user-defined data types such as pointers, structures, etc.

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.

int marks[90]; => integer array

char name[20]; => character array or string


C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the array is
declared or allocated memory, the elements of the array contain some garbage value. So, we need
to initialize the array to some meaningful value. There are multiple ways in which we can initialize
an array in C.

1. Array Initialization with Declaration

data_type array_name [size] = {value1, value2, ... valueN};

2. Array Initialization with Declaration without Size

data_type array_name[] = {1,2,3,4,5};

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];

One thing to note is that the indexing in the array always


starts with 0, i.e., the first element is at index 0 and
the last element is at N – 1 where N is the number of
elements in the array.

Update Array Element


We can update the value of an element at the given index i in a similar way to accessing an
element by using the array subscript operator [ ] and assignment operator =.

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.

Elements in Array: 10 20 100 40 50


int ary[4] = {1, 2, 3, 4}; #include <stdio.h>
int p[4];
int main() {
p = ary; int source[4] = {1, 2, 3, 4};
int destination[4];
In C, you cannot directly assign one array to another
for (int i = 0; i < 4; i++) {
destination[i] = source[i]; // Copy each element
}
In C, you cannot directly assign one array to another using
the assignment operator. Instead, you need to copy the // Print the destination array
elements individually. for (int i = 0; i < 4; i++) {
printf("%d ", destination[i]);
}
printf("\n");

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:

1. One Dimensional Array in C


The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one
dimension.

[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:

char s[ ] = { ‘H’ , ’A’ , ’R’ , ’R’ , ’Y’ , ’\0’ }

There is another shortcut for initializing strings in c language:

char s[ ] = “HARRY”; => In this case C adds a null character automatically.


Geeks
Length of string str is 5

The C language does not provide an inbuilt data type


for strings but it has an access specifier “%s” which
can be used to print and read strings directly.
Read a String Input From the User

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.

gets() is a function that can be


used to receive a multi-word
string.
puts() vs printf() for printing a string
In C, both puts() and printf() functions are used for printing a string on the console and are defined in
<stdio.h> header file

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");

Likewise, puts can be used to output a string.


puts(st); =>Prints the string and places the cursor on the next line
Function Name Description
strlen(string_name) Returns the length of string name.

strcpy(s1, s2) Copies the contents of string s2 to string s1.

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.

strlwr() Converts string to lowercase.

strupr() Converts string to uppercase.

strstr(s1, s2) Find the first occurrence of s2 in s1.


The main goal of strstr() is to search for a substring within a larger string and it helps to find
the first occurrence of a specified substring.
What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of other C variables or
a memory location. We can access and manipulate the data stored in that memory location
using pointers.
A pointer is a variable that stores the address of another variable.

j is a pointer
j points to i.

The "address of" (&) operator &i=> 87994


The address of operator is used to obtain the address of a given variable &j=>87998
If you refer to the diagrams above

*(&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.

Format specifier for printing pointer address is ‘%u’


How to Use Pointers?
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer,
we use the ( * ) dereference operator before its name.
int *j; => declare a variable j of type int-pointer
int *ptr;
j=&i =>store address of i in j
The pointer declared here will point to some random memory address as it is not initialized. Such pointers
are called wild pointers.

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 var = 10;


int * ptr;
ptr = &var;
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory address specified in
the pointer. We use the same ( * ) dereferencing operator that we used in the pointer declaration.
8
Pointers to a pointer:
Just like j is pointing to i or storing the address of i, we can have another variable, k which can
store the address of j. What will be the type of k?

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];

for (int i = 0; i < 4; i++) {


destination[i] = source[i]; // Copy each element
}

// Print the destination array


for (int i = 0; i < 4; i++) {
printf("%d ", destination[i]);
}
printf("\n");

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

Which is an indirection operator among the following?


a) &
b) *
c) ->
d) .
View Answer
Answer: b
C Structures
The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language. The items in the structure are called its member and they can be of any
valid data type. Additionally, the values of a structure are stored in contiguous memory locations.

Arrays and Strings => Similar data (int, float, char)


Structures can hold => dissimilar data

struct MyStructure { // Structure declaration


int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon

To access the structure, you must create a variable of it.


Use the struct keyword inside the main() method, followed by the name of the structure and
then the name of the structure variable

To access members of a structure, use the dot syntax (.)


Unions in C

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).

If we do not explicitly assign values to enum names, the


compiler by default assigns values starting from 0.
C typedef
The typedef is a keyword that is used to provide existing data types with a new name. The C typedef
keyword is used to redefine the name of already existing data types.
When names of datatypes become difficult to use in programs, typedef is used with user-defined
datatypes, which behave similarly to defining an alias for commands.

typedef short unsigned int USHORT;


USHORT x;

Macros and its types in C


In C, a macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined
by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with
the definition of the macro. Macro definitions need not be terminated by a semi-colon(;).
Storage Classes in C
C storage classes define the scope (visibility) and lifetime
of variables and/or functions within a C Program. They precede the type that they modify.

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.

Properties of Dynamic Memory allocation


[Link] is allocated at runtime.
[Link] can be allocated and released at any time.
[Link] memory is used here.
[Link] memory allocation is slow.
[Link] is more efficient as compared to Static memory allocation
[Link] allocation process is simple is complicated.
[Link] can be resized dynamically or reused.
The library functions of the stdlib.h header file, which helps to allocate memory dynamically are.
[Link]()
[Link]()
[Link]()
[Link]()

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 size is fixed and known at the time


The size can vary during execution.
of compilation.

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.

•Dynamic Arrays: Variable size,


allocated at runtime, more flexible,
require manual memory management,
and can lead to memory leaks if not
handled properly .

You might also like