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

c Programming Notes-merged

Uploaded by

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

c Programming Notes-merged

Uploaded by

vyommore03
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

What is C programming ?

● C is a powerful, general-purpose programming language developed in the early


1970s by Dennis Ritchie at Bell Labs.
● C is often referred to as the "mother of all programming languages" because
many other popular programming languages, such as C++, Java, and Python,
were influenced by it.

Why Learn C?

● It is one of the most popular programming languages in the world


● If you know C, you will have no problem learning other popular programming
languages such as Java, Python, C++, C#, etc, as the syntax is similar
● C is very fast, compared to other programming languages, like Java and Python
● C is very versatile; it can be used in both applications and technologies

Common Applications:

● Operating Systems: The UNIX operating system was written in C.


● Embedded Systems: Often used in programming microcontrollers.
● Game Development: Provides the speed needed for performance-critical
applications.
● Compilers: Many compilers are themselves written in C.
● Database Systems: For example, MySQL is written in C.
● Network Drivers and Protocols: Used for developing network tools and
applications.

Fundamentals of C Programming

1.1 Character Set in C

The character set in C consists of the basic building blocks used to write C programs.

Categories:

● Letters: Uppercase (A-Z), Lowercase (a-z)


● Digits: 0-9
● Special Characters: + - * / = < > { } [ ] , ; . " ' & % # ! ^ | ~ etc.
● White Spaces: Space, tab, newline, etc.
1.2 Identifiers and Keywords

Identifiers

Identifiers are the names given to variables, functions, arrays, or other user-defined
elements in a C program.

Rules for Identifiers:

● Must start with a letter (A-Z, a-z) or an underscore (_).


● Cannot use keywords.
● Can contain letters, digits (0-9), and underscores (_).
● Case-sensitive (sum and Sum are different).

Keywords

Keywords are reserved words in C that have a special meaning and cannot be used as
identifiers.

Examples of Keywords in C:

auto, break, case, char, const, continue, default, do, double, else, enum, extern, float,
for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef,
union, unsigned, void, volatile, while

1.3 Data Types in C

Data types define the type of data a variable can hold.

Primary Data Types:

● int: Integer (e.g., 10, -20)


● float: Floating-point numbers (e.g., 3.14, -2.5)
● double: Double-precision floating-point numbers (e.g., 3.14159)
● char: Single character (e.g., 'A', 'z')
● void: Used for functions with no return value.

Derived Data Types:

● Arrays, Pointers, Functions

User-defined Data Types:

● struct, union, enum, typedef


1.4 Constants

Constants are fixed values that do not change during the execution of a program.

1.5 Variables

Variables are named storage locations in memory that hold data, which can be modified
during program execution.

Syntax for Declaring Variables:

data_type variable_name;

Example:

int age;

float salary;

char grade;

2. Operators in C

Operators are symbols used to perform operations on variables and values.

2.1 Arithmetic Operators:

Perform basic mathematical operations.


2.2 Relational Operators:

Compare values and return true (1) or false (0).

1.3 Logical Operators:

1.4 Assignment Operators:

Assign values to variables.


1.5 Unary Operators:

Operate on a single operand.

1.6 Bitwise Operators:

Perform bit-level operations.

3. Expressions and Statements

● Expression: A combination of variables, constants, and operators that produces a


value. Example: a + b * c
● Statement: A complete instruction to perform an action. Example: int x = 10; or
printf("Hello");

4. Library Functions

Library functions are built-in functions provided by C to perform specific tasks.


Examples:

● printf() and scanf() (I/O operations, <stdio.h>)


● strcpy(), strlen() (String functions, <string.h>)
● sqrt(), pow() (Math functions, <math.h>)
● malloc(), free() (Memory functions, <stdlib.h>)

5. Preprocessor

The preprocessor processes the code before compilation.

Eg- #include

6. Data Input and Output in C

C provides various functions for input and output operations. These functions are
included in the standard library and defined in <stdio.h>.

6.1 Character Input and Output:

● getchar(): Reads a single character from standard input (keyboard).


● putchar(): Writes a single character to standard output (screen).

6.2 Formatted Input and Output:

● scanf(): Reads formatted input (numbers, characters, strings, etc.) from standard
input.
● printf(): Outputs formatted data to the standard output.

Common Format Specifiers for scanf() and printf():

6.3 String Input and Output:

● gets(): Reads an entire line of text (string) from standard input.


● puts(): Writes a string to the standard output.
6.4 Structure of a C Program
1. Branching in C

Branching allows the program to make decisions and execute different code blocks based on
conditions.

1.1 If Statement

The simplest conditional statement; executes a block of code if a condition is true.

if (condition)

// Code to execute if condition is true

1.2 If-Else Statement

Executes one block of code if the condition is true and another block if it is false.

if (condition)

// Code if condition is true

else

// Code if condition is false

1.3 Multiway Decision (if-else-if Ladder)

Used to check multiple conditions sequentially.

if (condition1)

// Code if condition1 is true


}

else if (condition2)

// Code if condition 2 is true

else

// Code if none of the above conditions are true

2. Looping in C

Loops are used to execute a block of code repeatedly until a condition is satisfied.

2. 1 While Loop

Tests the condition before executing the block.

while (condition)

// Code to execute

2.2 Do-While Loop

Executes the block at least once, then checks the condition.

do

// Code to execute

} while (condition);
2.3 For Loop

The most commonly used loop; initializes, tests, and increments in a single line.

for (initialization; condition; increment/decrement)

// Code to execute

3. Nested Control Structures

3.1 Switch Statement

Used for multi-way branching based on the value of an expression.

switch (expression)

case value1:

// Code for case value1

break;

case value2:

// Code for case value2

break;

default:

// Code if none of the cases match

}
3.2 Continue Statement

Skips the current iteration of a loop and moves to the next iteration.

for (int i = 1; i <= 5; i++)

if (i == 3) continue; // Skip when i is 3

printf("%d\n", i);

3.3 Break Statement

Exits the loop or switch statement immediately.

3.4 Goto Statement

Transfers control to a labeled statement in the program.

goto label;

label:

// Code to execute
1. Functions in C

Functions are blocks of code designed to perform specific tasks, which can be reused
multiple times in a program.

1.1 Defining a Function

To create a user-defined function:

return_type function_name(parameters)
{
// Function body
return value; // If required
}

example-

#include <stdio.h>
int add(int a, int b)
{
return a + b;
}

1.2 Accessing (Calling) a Function

A function is called by its name followed by parentheses containing any required


arguments.

1.3 Passing Arguments to a Function

Arguments can be passed in two ways:

1.3.1 Call by Value

A copy of the argument's value is passed to the function. Changes made inside the
function do not affect the original value.

1..3.2 Call by Reference

The actual memory address of the argument is passed, allowing changes to affect the
original variable.
1.4 Recursion

Recursion is when a function calls itself to solve smaller instances of a problem.

1.5 Advantages of Functions

1. Code Reusability: Write once, use multiple times.


2. Modular Programming: Break down large problems into smaller pieces.
3. Improved Readability: Simplifies complex code.
4. Easier Debugging: Functions can be tested independently.
1. Arrays in C

An array is a collection of variables of the same data type stored in contiguous memory
locations.

Concepts of Arrays

● One-dimensional Array: Stores a list of elements.


● Multidimensional Array: Stores data in a tabular (2D) or higher-dimensional
structure.

1.1 Declaration and Definition of an Array


data_type array_name[size];

int numbers[5]; // Declares an array of 5 integers.

1.2 Initialization During Declaration:


int numbers[5] = {1, 2, 3, 4, 5};

1.3 Accessing Array Elements:

Use the index (starting from 0).

2 Strings in C

A string in C is a sequence of characters

2.1 Declaration and Initialization:


char name[10] = "Alice";

2.2 Array of Strings

An array of strings is a 2D character array.

#include <stdio.h>
int main()
{
char names[3][10] = {"Alice", "Bob", "Eve"};
for (int i = 0; i < 3; i++)
{
printf("Name: %s \n", names[i]);
}
return 0;
}

2.3 String Functions in <string.h>

3 Structures in C

Structures (also called structs) are a way to group several related variables into one
place. Each variable in the structure is known as a member of the structure.

Unlike an array, a structure can contain many different data types (int, float, char, etc.).

You can create a structure by using the struct keyword and declare each of its members
inside curly braces:

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:
Create a struct variable with the name "s1":

struct myStructure

int myNum;

char myLetter;

};

int main()

struct myStructure s1;

return 0;

}
1. Pointers in C

Pointers are variables that store the memory address of another variable.

1.1 Uses of Pointers:

● Access and manipulate memory directly.


● Efficiently pass large data structures (e.g., arrays) to functions.
● Enable dynamic memory allocation.
● Facilitate data structures like linked lists and trees.

1.2 Address Operator (&)- is used to get the memory address of a variable.

int a = 10;

printf("Address of a: %p\n", &a); // Outputs the address of variable `a`.

1.3 Pointer Variable

Declared using the * operator.

Points to a specific data type.

data_type *pointer_name;

int a = 10;

int *ptr = &a; // Pointer to an integer

1.4 Dereferencing a Pointer-

Access the value stored at the memory address pointed to by the pointer.

int a = 10;

int *ptr = &a;

printf("Value of a: %d\n", *ptr); // Outputs: 10


Files in C

Files are used in C programming to store data permanently on a disk. File handling allows you
to create, open, read, write, and close files.

1. File Operations in C

2. Opening a File

Files are opened using the fopen() function.

FILE *fopen(filename,mode);
3. Creating a File

A file is automatically created when opened in w or a mode if it doesn't already exist.

Example:

FILE *file = fopen("newfile.txt", "w"); // Creates if not present

if (file != NULL)

fprintf(file, "File created successfully.\n");

fclose(file);

You might also like