0% found this document useful (0 votes)
5 views

C Language V26554

Uploaded by

sirius black
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C Language V26554

Uploaded by

sirius black
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Contents

How computer works............................................................................................................................1


ASCII......................................................................................................................................................1
Compilation process.............................................................................................................................3
Technical terms.....................................................................................................................................4
C language.............................................................................................................................................5
Variables................................................................................................................................................5
How to name a variable?...................................................................................................................6
Keywords in C....................................................................................................................................7
How to declare a variable..................................................................................................................7
How to print variables?......................................................................................................................8
Data types in C / C++.............................................................................................................................8
Operators in c......................................................................................................................................10
Arrays in C...........................................................................................................................................10
Comments in C....................................................................................................................................11
Memory allocation..............................................................................................................................12
Conditional Statements in C...............................................................................................................15
POINTERS............................................................................................................................................20
Structures............................................................................................................................................25
Void pointer.........................................................................................................................................36
Dynamic memory allocation................................................................................................................37

How computer works


A computer works by receiving data through an input unit based on the instructions it is given and
after it processes the data, it sends it back through an output device.

Data is an individual unit that contains raw materials which do not carry any specific
meaning. Information is a group of data that collectively carries a logical meaning. Data doesn't
depend on information. Information depends on data.
ASCII
ASCII stands for American Standard Code for Information Interchange. It's a character encoding standard
used for representing text in computers and other devices that use text. In ASCII, each character is
represented by a unique 7-bit binary number. This includes letters (both uppercase and lowercase), digits,
punctuation marks, and control characters (such as carriage return and line feed). ASCII was originally
developed in the 1960s and has been widely used ever since as a basic character encoding scheme in
computers and communication equipment.
The ASCII (American Standard Code for Information Interchange) character encoding scheme
encompasses a total of 128 character codes. These codes include both printable characters (such as
letters, digits, punctuation marks, and symbols) as well as non-printable control characters (such as
carriage return, line feed, tab, etc.). Each character is represented by a unique 7-bit binary number,
resulting in a total of 128 possible values (from 0 to 127).

For example, the ASCII character 'A' has a decimal value of 65. In binary, this is represented
as 01000001. Each bit in this binary representation corresponds to a specific power of 2, and
when these bits are combined, they represent the decimal value 65.
Compilation process
Technical terms
 Program – set of instructions given to the computer
 Syntax – rules and regulations to be followed
 IDE – Integrated Development Environment
 Compilation – translation
 Run – executing the instructions
 Function – has ()
 Statement – an instruction
o An instruction should end with - ;
 Console – view our output
 Header file - A C header file is a text file that contains pieces of code written in the C
programming language. The name of a header file, by convention, ends with the . h
extension. It is inserted inside a program by coding the #include preprocessor directive.
C language
 High level language
 Mother of all languages
 The C programming language was developed in the Bell Labs
 by an employee called Dennis Ritchie between 1969

ALGOL (Algorithmic Language)

BCPL (Basic Combined Programming Language)

B programming language

Variables
Variables are named memory locations.

Variables are identifiers, used for identification processes.


Memory location in C
name val ma
a 10 2000015
b 20 2000016
c 30 2000017
d 40 2000018
e 50 2000019
f 60 2000020
g 70 2000021
h 80 2000022
i 90 2000023

How to name a variable?


Rules for Naming a Variable in C

We give a variable a meaningful name when we create it. Here are the rules that we must follow
when naming it:

1. The name of the variable must not begin with a digit.

2. A variable name can consist of digits, alphabets, and _ underscore.

3. A variable name must not have any keywords, for instance, float, int, etc.

4. There must be no spaces or blanks in the variable name.

5. The C language treats lowercase and uppercase very differently, as it is case sensitive. Usually, we
keep the name of the variable in the lower case.
Examples :
int var1; // it is correct

int 1var; // it is incorrect – the name of the variable should not start using a number

int my_var1; // it is correct

int my$var // it is incorrect – no special characters should be in the name of the variable

char else; // there must be no keywords in the name of the variable

int my var; // it is incorrect – there must be no spaces in the name of the variable

int COUNT; // it is a new variable

int Count; // it is a new variable

int count; // it is a valid variable name

Keywords in C
Keywords in C
auto signed static

unsigne
break d struct
case continue switch
char default typedef
const do union
unsigne
long double d
registe
r else void
return enum volatile
short extern while
signed float goto
sizeof for if

How to declare a variable


A variable should be declared like:
Int variable1;

Char variable2;

Float variable3;

Double variable4;

The variable name should follow the data type of the corresponding value.

How to print variables?


Int - printf (“%d”,variable1);

Char - printf (“%c”,variable2);

Float - printf (“%f”,variable3);

Double - printf (“%f”,variable4);

// variablename

Number - printf (2);

Character - printf ("%c", 'A'); int a; int a[12];

Data types in C / C++

Literals in c :
Format specifiers in C:
In c language variables should be printed using format specifiers.
Printing variables without format specifiers will create an error.

DATA TYPE FORMAT SPECIFIER


CHAR %c
INT %d
FLOAT %f
DOUBLE %f

Printing variables in c:
Operators in c

sizeof(); operator used to return the size of any variable of any datatype.

Arrays in C
1. Arrays are variables that can store multiple values in a single variable name.
2. Arrays are commonly used for tasks such as storing lists of numbers, characters.
3. There can be arrays for all datatypes.

Declaring arrays:

int numbers[5];

char letters[5];

float decimals[5];

double longdecimals[5];
Comments in C
Comments are lines that are not executed or compiled.

If a text is placed after // then it is considered as single line comments.

If any text is placed between /* and */ then it is considered as multi line comments.
Memory allocation
8 bits = 1 byte.

1 bit can store 1 or 0.

1 bit can have 21 = 2 combinations

2 bits can have 22 = 4 combinations

3 bits can have 23 = 8 combinations

4 bits can have 24 = 16 combinations

8 bits can have 256 combinations

16 bits can store 65536 combinations (wide char)

Minimum 2 bits are required for an integer in c++

Also the memory allocation of a data type depends on a processor and the compiler we are using.

//Char used to store a single character


Control Statements in C
1) If condition
a) Simple if statement
b) If else statements
c) If else-if ladder
2) For loop
3) While loop
4) Do while loop
5) Switch case

If Else:
The if statement is used to execute a block of code only if the condition is true.
The if-else statement is used to execute one block of code if the condition is true and
another block if it's false
While Loop:

1. Syntax: Basic syntax of a while loop: while (condition).


2. Condition: Teach about the condition part, which is evaluated before each
iteration of the loop. The loop continues as long as this condition evaluates to
true.
3. Loop Body: Emphasize that the loop body is executed only if the condition
evaluates to true.
4. Initialization: Explain that any variables used in the condition must be initialized
before the loop.
5. Increment/Decrement: If applicable, explain how to manually increment or
decrement loop control variables within the loop body.
6. Scope: Discuss the scope of variables declared within the loop body.
7. Termination: Ensure there's a way for the loop to eventually terminate to avoid
infinite loops.
8. Control Variable: If applicable, discuss the importance of a loop control variable
and how it's updated to eventually make the condition false.
9. Nested Loops: Introduce the concept of nested while loops, where one while
loop is placed inside another.
FOR LOOP:

 The basic syntax of a for loop: for (initialization; condition; increment/decrement).


 Initialization: Teach about the initialization part, where a loop control variable is
initialized. This is usually where you declare and initialize a variable that will control
the loop.
 Condition: Explain the condition part, which is evaluated before each iteration of the
loop. The loop continues as long as this condition evaluates to true.
 Increment/Decrement: Discuss the increment or decrement part, which is executed
after each iteration of the loop. It's usually responsible for changing the loop control
variable to eventually make the condition false.
 Scope: Emphasize the scope of the loop, explaining that the loop body is enclosed
within curly braces {} and everything inside these braces will be executed in each
iteration.
 Termination: Explain how the loop terminates when the condition becomes false.
 Control Variable: Emphasize the importance of the loop control variable and how it's
used to track the progress of the loop.
 Nested Loops: Introduce the concept of nested loops, where one loop is placed
inside another.
 Common Mistake: Highlight common mistakes such as infinite loops (when the
condition never becomes false) and off-by-one errors.

Do-While Loop:
Syntax: Start by explaining the basic syntax of a do-while loop: do { ... } while (condition);.

Loop Body: Discuss that the loop body is executed at least once before the condition is checked.

Condition: Teach about the condition part, which is evaluated after each iteration of the loop. The
loop continues as long as this condition evaluates to true.

Initialization: Ensure any variables used in the condition are properly initialized before the loop.

Increment/Decrement: If applicable, explain how to manually increment or decrement loop control


variables within the loop body.

Scope: Discuss the scope of variables declared within the loop body.

Termination: Ensure there's a way for the loop to eventually terminate to avoid infinite loops.

Control Variable: If applicable, discuss the importance of a loop control variable and how it's
updated to eventually make the condition false.

Nested Loops: Introduce the concept of nested do-while loops, where one do-while loop is placed
inside another.
Switch Case:
Introduction: Start by explaining that the switch case statement is a control statement used for
decision-making purposes in C programming.

Need for Switch Case: Discuss scenarios where multiple conditions need to be evaluated against the
same variable. Instead of using multiple if-else statements, a switch case provides a cleaner and
more efficient way to handle such situations.

Uses of Switch Cases: Explain that switch cases are commonly used when there are several possible
execution paths based on the value of a single variable.

Advantages of Switch Cases:

Readability: switch cases can make code more readable and understandable, especially when
dealing with multiple conditions.

Efficiency: switch cases can be more efficient than long chains of if-else statements, especially when
the number of conditions is large.

Optimization: Some compilers can optimize switch statements more effectively than if-else chains.

Syntax: Introduce the syntax of the switch case statement:


Expression: Explain that the expression inside the switch statement is evaluated once, and its value is
compared with the values of each case.

Implementation: Discuss that each case label specifies a possible value for the expression and the
corresponding block of code to execute if the expression matches that value.

Break Statement: Highlight the importance of the break statement after each case block. It's used to
exit the switch statement and prevent falling through to subsequent case blocks.

Default Case: Explain the default case, which is optional and is executed when none of the case
values match the expression.

POINTERS
The pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. A pointer is called
as a pointer as it points to the memory address of another variable …

567 % 5 422882 788647


422882 - (A) 422886 (B) 422887 (C) 764567 - (M) 238746 - (N)
M N

Pointer Memory Address of M


Memory Address Value of M

Value of the variable

How to declare a pointer ?

Assign a Value to a pointer

Printing the value of the variable using the pointer :In

Additional info:
1. In the above topic, *ptr can also be referred as *(&a).
2. Because, the * is going to return the value stored in the address.
3. And obviously &a refers the memory address of a.
4. So, in short we are ordering the compiler to return the value stored in the memory
address of a.
5. And obviously &p will return the memory address of the pointer variable.

Char pointer is something different from integer pointers :

Double pointer:
A pointer is a variable that stores the memory address of a variable.
A double pointer is a variable that stores the memory address of another pointer.
A double pointer should be declared using two asterisk symbols.
1. int a=90;
2. int *p=&a;
3. int **ptr2=&p;
The 3rd point can also be replace with:
int **ptr2;
ptr = &p;

To be remembered while printing:

1. a will print 90;


2. p will print the memory address of a;
3. *p will print the value of a;
4. &p will print the memory address of the p(pointer)
5. ptr2 will print the memory address of p;
6. *ptr2 will print the value of the variable p (memory address of a);
7. **ptr2 will print the value of a… Because the memory address of p is stored in
ptr2, and the memory address of a is stored in p, so the ** return the value of
the variable ‘a’.
8. And obviously &ptr2 will print the address of the double pointer ptr2;
Possible arithmetic operation with pointers
1. Addition or increment
2. Subtraction or decrement
3. Subtraction of one pointer from another pointer ( Same type pointer only)
4.

Other than this all kind of relational operations can be performed with the pointers.
But operations like multiplication, division cannot be done with general numbers and among
pointers.
Generally variables are stored non continuously.
But when it comes to arrays, elements are stored in contagious memory locations .

Call by value and call by reference :


Call by value:
1. The int a in the gokulsFunction is called as formal parameter or formal argument.

2. While the argument of the gokulsFunction inside the main() is known as


Actual parameter / Actual argument.
Referring with the value of the variable for a function doesn’t change the actual value of the
variable. (a) - CALL BY VALUE.
Instead referring the variable with its memory address changes the actual value of the
variable permanently. - CALL BY REFERENCE.
call by reference:

Note:
While addressing the address of a in the above program, &a can also be replaced with by
ptr_a, as both refer to the address of the variable a.
Call by value and call by reference using swap example

Even though the both are void functions(they return nothing),

 the values are swapped in the first function ”swapByValue”


 the references are swapped in the second function “swapByReference”

Structures
1. Structures are user defined variables.
2. A structure is similar to an array.
a. An array can store multiple elements of the same data type.
b. A structures can store multiple elements of different data types as per the
need of the user.
3. Members of a structure are stored in contagious memory locations.
4. The concept of structures allows us to create customized data types on our own.
5. The below example depicts the outline to define a structure (User defined data type).
6. We all know a data type defines the value of the data a variable contains.

Creating the variable of student data type and accessing the


elements of the structure :
1. Accessing the elements is done by the . operator.
2. Initialization can also be done like:

i.e.,
variable declaration and initialization in the same line.
3. Multiple structures data types can be created in a program.
4. Multiple variables for a single structure data type can also be created.

File handling
 Files are used for permanent storage.

 Data stored in the RAM are vanished after closing the program.
 So, if you want to want something to be stored permanently, you should create files.

 File handling functions are present in <stdio.h>.


 File pointers are needed to open a file.
 FILE *fp;
 Buffer is created in the RAM. Random Access Memory

BUffer
Bufferbu

 Whenever a file is created, buffer is first filled and then it is filled into disk (hard disk,
whether in c local disk c, local disk d, etc.,)
 When the program is closed, whatever is present in the buffer is transferred into the
disk.
 Buffers are for efficiency.
 RAM can be accessed easily.
 Writing in the buffer until it gets filled and then transferring it to the ram is efficient
and time saving.

Modes :

“w”  Write mode.


 If there is no such file a new file is
FILE *fp; created.
fp = fopen(filename , mode);  If open an existing file in “w” mode,
fp = fopen(“gokul.txt” , “w”); the contents inside the file are
deleted and then new contents are
to be written.
“a”  Appending mode.
 To add something in the existing file.
 Existing contents won’t be deleted.
“r”  Read mode.
 Only existing files can be opened.
“ w+ ”  Similar to write but we can also read

“ r+ ”  Similar to read but we can also write.


 The major advantage is we can
update something.
“ a+ ”  Append + read

Wb
Rb
Ab
.
.
.
The file pointer returns null if there is any issue in opening a file.
fclose(filepointer)
fclose(fp)

 How to open/create a file.


 How to close a file.
 How to read from a file.
 How to write a char, string, int in a file.
 How to read a char, string, int in a file

Linked list

 A singly linked list in C is like a chain of connected blocks, where each block stores some
data and points to the next block in the chain.
 You can only move forward through the chain, starting from the beginning.
 Each block, or node, holds information and a pointer to the next node.
 This setup allows for flexible storage and efficient insertion and deletion of data.
 Difference between linked list and array is flexibility.
 In a singly linked list, each node contains two fields: the data field, which stores the actual
information, and a pointer field, which points to the next node in the sequence.
 This pointer essentially establishes the link between nodes, hence the name "linked list."
 One characteristic of singly linked lists is their unidirectional nature. Each node only
points to the next node in the sequence, forming a linear chain.

Need for linked list

 Dynamic memory allocation


 Traversal
 Efficient insertion and deletion
 Memory management

Head pointer
852 200 801
PADDING IN C
1. What is padding?
2. Padding is the extra memory added by the compiler to ensure that each member of a
structure is properly aligned in memory.
3. Why is padding needed?
4. Memory alignment refers to the requirement that certain types of data have to be
located at certain addresses in memory for optimal performance.
5. For example, accessing a 4-byte integer may be faster if it starts at an address that is
a multiple of 4.
6. How does padding work?
7. When you define a structure in C, the compiler tries to align each member to a
memory address that is a multiple of its size.
8. If a member's alignment requirement isn't met, the compiler inserts extra bytes
(padding) between members to align them properly.
9. When does padding occur?
10. Padding occurs between members of a structure, especially when the sizes of the
members are not multiples of each other.
11. For example, consider a structure with an int (4 bytes) followed by a char array of size
3 (3 bytes). To align the char array properly, the compiler may insert 1 byte of
padding after the int.
12. Why does padding vary?
13. Padding depends on factors like the size and order of structure members, compiler
settings, and target architecture.
14. Different compilers and architectures may have different padding requirements.
15. How to minimize padding?
16. You can control padding by rearranging the order of structure members or using
compiler-specific directives to pack the structure tightly.
17. However, be cautious as minimizing padding may impact performance due to
potential alignment issues.
18. In summary, padding ensures that each member of a structure is properly aligned in
memory, which can improve performance. It's added by the compiler as extra
memory between structure members to meet alignment requirements.
Understanding padding helps in designing efficient data structures in C.

Remember:

This is how to pass an array to a function.

The below program denotes how to declare return an array from a function,
It has been save in C example programs in the name of ReturningArraysWithPointers.c;
In c arrays cant be returned directly, instead they can be returned using the concept of
pointers. Actually the a which is returned here is a pointer according to the
compiler/processor. A denotes the first element’s address. in order to return a
pointer(memory address) the return type is denoted as int*.
Here we use static int because as soon the function is completed the memory spaces
allocated for the variables inside the function (getArray) are deallocated. Then also the
pointer (a) will point the element’s address, but there will be no element in the memory as
it would be vanished after the function completion.
So we use, static to retain the values in the RAM. Then we can use the pointer to retrieve the
values from the RAM. In order to store the pointer / memory address (a) which is returned,
we create a variable called *p in the main function, and then use it to print the elements of
the array.
After that we perform arithmetic with the pointer to print the consecutive numbers as usual.
#define a 5; MACRO DEFINITION of the variable ‘a’. a=5 cannot be changed throughout the
program.
MACRO definition can also be used to declare constant statements. (for short cut purposes)
An example of how to use this :
The difference between macro definition and global variable declaration is that we can
change the value of the global variable throughout the program, assign different values to it,
change the value of it.
Whereas the value of a macro defined variable cannot be changed throughout the program.

Void pointer

Cannot access value of the variable until it is declared like this


Dynamic memory allocation
To avoid wastage of memory spaces.

Malloc – malloc(20)
Used to allocate memory dynamically. i.e., if you declare an int array[10]
and you only store 5 elements. The remaining (5*4) 20 bytes are allocated but
have no values in them. This leads to the slowness of the program. In order to
avoid this we tell the compiler to allocate the space for the array during the
runtime, using malloc();
So, if you declare int x[20] and you only use 10 elements, the remaining
space for the 10 elements are not allocated, because space is allocated only for
How many elements you use in the program.

So the malloc function allocates a space of 20 bytes in the heap segment and
return the starting address of the 20 bytes in a null pointer(as null pointers are
multi purpose). The null pointer’s value can be stored in another pointer
variable(of the corresponding data type).
(20 bytes can store 5 integers)
But before performing a arithmetic, the null pointer should be typecasted into
the corresponding data type.
And the storing pointer must be the same data type for example :
Int *ptr;
Ptr = (int*)malloc(20);
(or)
Ptr = (int*)malloc(5*sizeof(int));

Similarly if you allocate space for float


Float *ptr;
Ptr = (float*)malloc(20);
(or)
Ptr = (float*)malloc(5*sizeof(float));

ADDITIONAL INFO :If there is no available space in the heap memory, the malloc will return NULL;

So as usually, if you print the value of the pointer (*ptr) if there is no space, you’ll get null printed.
Calloc

You might also like