C Programming Micro 1 - 045421
C Programming Micro 1 - 045421
Features of C Language
C is the widely used language. It provides many features that are given
below 1 Simple C is a simple language in the sense that it provides a
structured approach (to break the problem into parts), the rich set of
library functions, data types, etc.
2) Machine Independent or Portable Unlike assembly language, c
programs can be executed on different machines with some machine
specific changes. Therefore, C is a machine independent language.
3) Mid-level programming language Although, C is intended to do
lowlevel programming. It is used to develop system applications such as
kernel, driver, etc. It also supports the features of a high-level language.
That is why it is known as mid-level language.
4) Structured programming language C is a structured programming
language in the sense that we can break the program into parts using
functions. So, it is easy to understand and modify. Functions also provide
code reusability.
5) Rich Library C provides a lot of inbuilt functions that make the
development fast.
6) Memory Management It supports the feature of dynamic memory
allocation. In C language, we can free the allocated memory at any time by
calling the free() function.
7) Speed The compilation and execution time of C language is fast since
there are lesser inbuilt functions and hence the lesser overhead.
8) Pointer C provides the feature of pointers. We can directly interact with
the memory by using the pointers. We can use pointers for memory,
structures, functions, array, etc.
What is a compilation?
The compilation is a process of converting the source code into object code. It is done
with the help of the compiler. The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the
object code or machine code. The compilation process can be divided into
four steps, i.e., Pre-processing, Compiling, Assembling, and Linking. The
preprocessor takes the source code as an input, and it removes all the
comments from the source code. The preprocessor takes the preprocessor
directive and interprets it. For example, if <stdio.h>, the directive is available
in the program, then the preprocessor interprets the directive and replace
this directive with the content of the 'stdio.h' file. The following are the
phases through which our program passes before being transformed into an
executable form:
o Preprocessor o
Compiler o
Assembler o
Linker
For example,
Here,
• data_type: Type of data that a variable can store.
• variable_name: Name of the variable given by the user.
C Variable Types
The C variables can be classified into the following types:
1. Local Variables
2. Global Variables
3. Static Variables
4. Automatic Variables
5. Extern Variables
6. Register Variables
There are 3 aspects of defining a variable:
1. Variable Declaration
2. Variable Definition
3. Variable Initialization
Variable declaration in C tells the compiler about the existence of the variable
with the given name and data type.When the variable is declared compiler
automatically allocates the memory for it.
In the definition of a C variable, the compiler allocates some memory and
some value to it. A defined variable will contain some random garbage value
till it is not initialized. Initialization of a variable is the process where the user
assigns some meaningful value to the variable.
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
Basic Data Types The basic data types are integer-based and
floatingpoint based. C language supports both signed and unsigned literals. The
memory size of the basic data types may change according to 32 or 64-bit
operating system.
Int: Integers are entire numbers without any fractional or decimal parts, and the int data
type is used to represent them. It is frequently applied to variables that include values, such
as counts, indices, or other numerical numbers. The int data type may represent both
positive and negative numbers because it is signed by default. An int takes up 4 bytes of
memory on most devices, allowing it to store values between around -2 billion and +2 billion.
Char: Individual characters are represented by the char data type. Typically used to hold
ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols, or
commas. There are 256 characters that can be represented by a single char, which takes up
one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.
Float: To represent integers, use the floating data type. Floating numbers can be used
to represent fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not
be very precise. It can store values with an accuracy of about 6 decimal places and a
range of about 3.4 x 1038 in 4 bytes of memory.
Double: Use two data types to represent two floating integers. When additional
precision is needed, such as in scientific calculations or financial applications, it provides
greater accuracy compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal
places, yields larger values. C treats floating point numbers as doubles by default if no
explicit type is supplied.
In the example above, we declare four variables: an int variable for the person's age, a
char variable for the student's grade, a float variable for the temperature reading, and
two variables for the number pi.
Derived Data Type Beyond the fundamental data types, C also supports
derived data types, including arrays, pointers, structures, and unions. These
data types give programmers the ability to handle heterogeneous data, directly
modify memory, and build complicated data structures.
Array: An array, a derived data type, lets you store a sequence of fixed-size elements
of the same type. It provides a mechanism for joining multiple targets of the same data
under the same name.
The index is used to access the elements of the array, with a 0 index for the first entry.
The size of the array is fixed at declaration time and cannot be changed during program
execution. The array components are placed in adjacent memory regions.
Here is an example of declaring and utilizing an array:
#include <stdio.h>
return 0;
}
Output:
Values in the array: 10 20 30 40 50
Pointer:
A pointer is a derived data type that keeps track of another data type's memory address.
When a pointer is declared, the data type it refers to is stated first, and then the
variable name is preceded by an asterisk (*).
You can have incorrect access and change the value of variable using pointers by
specifying the memory address of the variable. Pointers are commonly used in tasks such
as function pointers, data structures, and dynamic memory allocation.
1. #include <stdio.h>
2.
3. int main() {
4. int numbers[5]; // Declares an integer array with a size of 5 elements
5.
6. // Assign values to the array elements
7. numbers[0] = 10;
8. numbers[1] = 20;
9. numbers[2] = 30;
10. numbers[3] = 40; 11. numbers[4] = 50;
12.
13. // Display the values stored in the array
14. printf("Values in the array: ");
15. for (int i = 0; i < 5; i++) {
16. printf("%d ", numbers[i]);
17. }
18. printf("\n");
19.
20. return 0;
21. }
Output:
Values in the array: 10 20 30 40 50
Pointer:
A pointer is a derived data type that keeps track of another data type's memory address.
When a pointer is declared, the data type it refers to is stated first, and then the
variable name is preceded by an asterisk (*).
You can have incorrect access and change the value of variable using pointers by
specifying the memory address of the variable. Pointers are commonly used in tasks such
as function pointers, data structures, and dynamic memory allocation.
#include <stdio.h>
int main() {
int num = 42; // An integer variable
int *ptr; // Declares a pointer to an integer
ptr = # // Assigns the address
of 'num' to the pointer
Output:
Integer Value: 42
Float Value: 3.14
1. #include <stdio.h>
2.
3. // Define an enumeration for days of the
week
4. enum DaysOfWeek {
5. Monday,
6. Tuesday,
7. Wednesday,
8. Thursday,
9. Friday,
10. Saturday,
11. Sunday
12. };
13. int main() {
14. // Declare a variable of type
enum DaysOfWeek
15. enum DaysOfWeek today;
17.
18. // Assign a value from the enumeration
19. today = Wednesday;
20.
21. // Accessing the enumeration value
22. printf("Today is %d\n", today);
23.
24. return 0;
25. }
Output:
Today is 2
Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We can
define the token as the smallest individual element in C. For `example, we cannot create a
sentence without using words; similarly, we cannot create a program in C without using
tokens in C. Therefore, we can say that tokens in C is the building block or the basic
component for creating a program in C language.
Classification of tokens in C
• Keywords in C
• Identifiers in C
• Strings in C
• Operators in C
• Constant in C
• Special Characters inC
Keywords in C
Keywords in C are reserved words that have predefined meanings and are
part of the C language syntax. These keywords cannot be used as variable
names, function names, or any other identifiers within the program except
for their intended purpose. They are used to define the structure flow and
behavior of a C program.
C Identifiers
C identifiers represent the name in the C program, for example, variables, functions, arrays,
structures, unions, labels, etc. An identifier can be composed of letters such as uppercase,
lowercase letters, underscore, digits, but the starting letter should be either an alphabet
or an underscore. If the identifier is not used in the external linkage, then it is called as an
internal identifier. If the identifier is used in the external linkage, then it is called as an
external identifier.
We can say that an identifier is a collection of alphanumeric characters that begins either
with an alphabetical character or an underscore, which are used to represent various
programming elements such as variables, functions, arrays, structures, unions, labels, etc.
There are 52 alphabetical characters (uppercase and lowercase), underscore character, and
ten numerical digits (0-9) that represent the identifiers. There is a total of 63
alphanumerical characters that represent the identifiers.
Rules for constructing C identifiers o The first character of an identifier
should be either an alphabet or an underscore, and then it can be followed
by any of the character, digit, or underscore.
o It should not begin with any numerical digit. o In identifiers, both
uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters. o
Identifiers should be written in such a way that it is meaningful, short,
and easy to read.
Keyword Identifier
It must be written in a lowercase letter. It can be written in both lowercase and uppercase letters.
Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.
It does not contain the underscore character. It can contain the underscore character.
Operators : Operators means special symbol, are used to perform operations on
variables and values.
1. Binary Operator
2. Unary Operator
3. Ternary Operator
1.Binary Operators:
1. Arithmetic Operators
2. Relational /Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
H
2.
Comparison Operators :
== Equal x == y Returns 1 if
to the values
are equal
!= Not x != y Returns 1 if
equal the values
are not
equal
3.logical Operators
You can also test for true or false values with logical operators.
! Logical not !(x < 5 && x < Reverse the result, returns 0 if the result is
10) 1
4.Bitwise Operators :
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.
There are 6 bitwise operators in C:
| Bitwise OR operator
5.Assignment operators
2. Unary operators :
Operators that work on single operand. This includes :
3.Ternary Operators :
Conditional Operator ( ? : )
1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
6. Conditional Operator
7. Jump Statements:
• break
• continue
• goto
• return
default: default_statement;
}
For Ex: #include <stdio.h>
void main()
// switch variable
int month;
scanf("%d",&month);
// switch statement
switch (month) {
case 1:
printf("January");
break;
case 2:
printf("February");
break;
case 3:
printf("march");
break;
default:
printf("Invalid input! Please enter month number
between 1-12.");
break;
The looping simplifies the complex problems into the easy ones. It enables
us to alter the flow of the program so that instead of writing the same code
again and again, we can repeat the same code for a finite number of times.
For example, if we need to print the first 10 natural numbers then, instead of
using the printf statement 10 times, we can print inside a loop which runs up
to 10 iterations.
Advantage of loops in C
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops
1. do while
2. while
3. for
do-while loop in C
A "do-while" loop is a form of a loop in C that executes the code block first,
followed by the condition. If the condition is true, the loop continues to run;
else, it stops. However, whether the condition is originally true, it ensures
that the code block is performed at least once.
do{
//code to be executed
}while(condition);
Example:
#include <stdio.h>
#include <string.h>
1. int main() {
char password[] = "secret";
2. char input[20];
3. do {
4. printf("Enter the password: ");
5. scanf("%s", input);
} while (strcmp(input, password) != 0);
6. printf("Access granted!\n");
7. return 0;
8. }
Output
Enter the password: 123
Enter the password: abc
Enter the password: secret
Access Granted!
2.while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows
a part of the code to be executed multiple times depending upon a given
boolean condition. It can be viewed as a repeating if statement. The while
loop is mostly used in the case where the number of iterations is not known
in advance.
1. while(condition){
2. //code to be executed
}
Flowchart of while loop in C
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
for loop in C
The for loop in C language is used to iterate the statements or a part of the
program several times. It is frequently used to traverse the data structures like the
array and linked list.
EX: C Program: Print table for the given number using C for
loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }
Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
C Program: Print table for the given number using C for loop
Flowchart of for loop in C
C Array
An array is defined as the collection of similar type of data items stored at
contiguous memory locations. Arrays are the derived data type in C
programming language which can store the primitive type of data such as
int, char, double, float, etc. It also has the capability to store the collection of
derived data types, such as pointers, structure, etc. The array is the simplest
data structure where each data element can be randomly accessed by using
its index number.
By using the array, we can access the elements easily. Only a few lines of code
are required to access the elements of the array.
Properties of Array
o Each element of an array is of same data type and carries the same size, i.e., int =
4 bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address
of each element of the array with the given base address and the size of the data
element.
Advantage of C Array
3) Ease of sorting: To sort the elements of the array, we need a few lines of
code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
Initialization of Arrays
float arr_float[5];
for (int i = 0; i < 5; i++) {
arr_float[i] = i * 2.5;
}
Types of Array :
1. One-Dimensional Arrays (1D Arrays)
The array is declared with one value of size in square brackets,
it is called one dimensional array. In a one dimensional array,
each element is identified by its index or subscript.
Example:
Students[hall][row][column]
Example
#include<stdio.h>
int main(){
int i, j, k;
int arr[3][3][3]= {
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
for(i=0;i<3;i++) {
for(j=0;j<3;j++){
for(k=0;k<3;k++){
printf("%4d",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
Output:
21 22 23
24 25 26
27 28 29
31 32 33
34 35 36
37 38 39
#include <stdio.h>
#include <string.h>
int main()
{
// declare and initialize string
char str[] = "Geeks";
// print string
printf("%s\n", str);
int length = 0;
length = strlen(str);
return 0;
}
Output
Geeks
Length of string str is 5
We can see in the above program that strings can be printed using normal
printf statements just like we print any other variable. Unlike arrays, we do
not need to print a string, character by character.
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.
As the pointers in C store the memory addresses, their size is independent
of the type of data they are pointing to. This size of pointers in C only
depends on the system architecture.
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;
where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also
define pointers to functions, structures, etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing
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.
Example
int *ptr;
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 ( & ) addressof operator to get the
memory address of a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method is
called pointer definition as the pointer is declared and initialized at the same time.
Example
int *ptr = &var;
Note: It is recommended that the pointers should always be initialized to some value
before starting using it. Otherwise, it may lead to number of errors.
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.
Uses of Pointers in C
The C pointer is a very powerful tool that is widely used in C programming
to perform various useful operations. It is used to achieve the following
functionalities in C:
1. Pass Arguments by Reference
2. Accessing Array Elements
3. Return Multiple Values from Function
4. Dynamic Memory Allocation
5. Implementing Data Structures
6. In System-Level Programming where memory addresses are
useful.
7. In locating the exact value at some memory location.
8. To avoid compiler confusion for the same variable name.
9. To use in Control Tables.
Advantages of Pointers
• Following are Pointers are used for dynamic memory allocation and
deallocation.
• An Array or a structure can be accessed efficiently with pointers
• Pointers are useful for accessing memory locations.
• Pointers are used to form complex data structures such as linked
lists, graphs, trees, etc.
• Pointers reduce the length of the program and its execution time as
well.
Disadvantages of Pointers
Pointers are vulnerable to errors and have following disadvantages:
• Memory corruption can occur if an incorrect value is provided to
pointers.
• Pointers are a little bit complex to understand.
• Pointers are majorly responsible for memory leaks in C.
• Pointers are comparatively slower than variables in C.
• Uninitialized pointers might cause a segmentation fault.
Conclusion
In conclusion, pointers in C are very capable tools and provide C language
with its distinguishing features, such as low-level memory access,
referencing, etc. But as powerful as they are, they should be used with
responsibility as they are one of the most vulnerable parts of the language.
the major advantages of pointers in C:
What is Structure
Structure in c is a user-defined data type that enables us to store the
collection of different data types. Each element of a structure is called a
member. Structures ca; simulate the use of classes and templates as it can
store various information
Syntax:
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
struct book{
char title[10];
double price;
int pages;
};
During the program, you can declare an array and initialize it by giving the
values of each element inside curly brackets. Each element in the struct
array is a struct value itself. Hence, we have the nested curly brackets as
shown below −
How does the compiler allocate the memory? Since we have an array of
three elements, of struct whose size is 32 bytes, the array occupies 32X3
bytes. Each block of 32 bytes will accommodate a title, price and pages
element.
We can also accept data from the user to fill the array
Example
#include <stdio.h>
#include <string.h>
struct book{
char title[10];
double price;
int pages;
};
int main (){
struct book b[3];
strcpy(b[0].title, " Learn C ");
b[0].price = 650.50;
b[0].pages=325;
strcpy(b[1].title, " C Pointers ");
b[1].price = 175;
b[1].pages=225;
strcpy(b[2].title, "C Pearls ");
b[2].price = 250;
b[2].pages=325;
printf("\nList of books\n");
for (int i=0; i<3; i++){
printf("Title: %s Price: %7.2lf No of Pages: %d\n", b[i].title, b[i].price,
b[i].pages);
}
return 0;
}
Output
List of books
Title: Learn C Price: 650.50 No of Pages: 325
Title: C Pointers Price: 175.00 No of Pages: 225
Title: C Pearls Price: 250.00 No of Pages: 325
Union in C
Union is a user-defined data type, but unlike structures, they share the same
memory location.
For Example:
1. struct abc
2. {
3. int a;
4. char b;
5. }
The above code is the user-defined structure that consists of two members, i.e., 'a' of
type int and 'b' of type character. When we check the addresses of 'a' and 'b', we found
that their addresses are different. Therefore, we conclude that the members in the
structure do not share the same memory location.
File Handling in C
In programming, we may require some specific input data to be generated several
numbers of times. Sometimes, it is not enough to only display the data on the console.
The data to be displayed may be very large, and only a limited amount of data can be
displayed on the console, and since the memory is volatile, it is impossible to recover the
programmatically generated data again and again. However, if we need to do so, we may
store it onto the local file system which is volatile and can be accessed every time. Here,
comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed on
a file.
o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }
Output
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in
the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls
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.
Syntax
Example
Example of C Function
#include <stdio.h>
// their sum
return a + b;
// Driver code
int main()
{
// Calling sum function and
return 0;
Output
Sum is: 40
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.
Example:
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements
inside the function.
Note: Only one value can be returned from a C function. To return multiple
values, we have to use pointers or structures.
Example:
int function_name(int var1, int var2);
1. Library Function
// C program to implement
#include <math.h>
#include <stdio.h>
// Driver code
int main()
double Number;
Number = 49;
// library function
Number, squareRoot);
return 0;
Output
The Square root of 49.00 = 7.00
// C program to show
// user-defined functions
#include <stdio.h>
return a + b;
// Driver code
int main()
// function call
return 0;
Output
Sum is: 70
// of call by value
#include <stdio.h>
var1 = var2;
var2 = temp;
// Driver code
int main()
var1, var2);
swap(var1, var2);
var1, var2);
return 0;
2. Pass by Reference
The caller’s actual parameters and the function’s actual parameters refer to
the same locations, so any changes made inside the function are reflected in
the caller’s actual parameters.
Example:
// call by Reference
#include <stdio.h>
*var1 = *var2;
*var2 = temp;
// Driver code
int main()
{
var1, var2);
swap(&var1, &var2);
var1, var2);
return 0;
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3
Advantages of Functions in C
Functions in C is a highly useful feature of C with many advantages as
mentioned below:
1. The function can reduce the repetition of the same statements in
the program.
2. The function makes code readable by providing modularity to our
program.
3. There is no fixed number of calling functions it can be called as
many times as you want.
4. The function reduces the size of the program.
5. Once the function is declared you can just use it without thinking
about the internal working of the function.
Disadvantages of Functions in C
The following are the major disadvantages of functions in C:
1. Cannot return multiple values.
2. Memory and time overhead due to stack frame allocation and
transfer of program control.
Conclusion
In this article, we discussed the following points about the function as
mentioned below:
1. The function is the block of code that can be reused as many times
as we want inside a program.
2. To use a function we need to call a function.
3. Function declaration includes function_name, return type, and
parameters.
4. Function definition includes the body of the function.
5. The function is of two types user-defined function and library
function.
6. In function, we can according to two types call by value and call by
reference according to the values passed.
Syntax