Download C language fundamental and more Study notes C programming in PDF only on Docsity!
Structure of a C Program
Component Description
Documentation Comments describing the program’s purpose.
Preprocessor Directives Includes libraries and macros using #include and #define.
Definition Section Defines constants or macros used in the program.
Global Declarations Variables declared globally and accessible by all functions.
main() Function The entry point of the program where execution begins.
Variable Declarations Local variables declared inside functions.
Statements and Expressions Code logic, including operations, loops, and conditionals.
Sub Programs Additional user-defined sub-programs or functions.
Return Statement Indicates the end of program execution, often with a success code.
Execution of C Program
1. Creating a program: We need to create a program, to create a program type the source code and
save it as 'filename.c'
2. Compiling the program: After creating the program, we need to compile the program. To compile a
program shortcut key is Alt+F9 in turbo Compiler. By compiling, high level language is converted
into machine language.
3. Linking the program: It is a process of putting together the program files and function that are
required by the program. To link the function we need to call the libraries in the starting of the
program.
4. Executing the program: During executing the program it may request for some data to be entered
through the keyboard. Sometimes the program does not produce the desired results. Something is
wrong with the program logic or data, in this case source code is modified & executing the program
is repeated.
Constant: A constant is a name given to the variable whose values can’t be altered or changed. A constant
is very similar to variables in the C programming language, but it can hold only a single variable during the
execution of a program. It means that once we assign value to the constant, then we can’t change it
throughout the execution of a program- it stays fixed.
How to Declare and Define Constants in C?
Constants in C can be defined using two primary methods: the #define preprocessor directive and the const
keyword:
1. Using #define Preprocessor Directive
The #define directive is used to define constant values or macros at the start of a program. It instructs the
compiler to replace all occurrences of the defined constant with its value before the actual compilation
begins.
Syntax: #define CONSTANT_NAME value
CONSTANT_NAME: The name of the constant (conventionally written in uppercase).
value : The constant value being assigned.
Example:
#define PI 3.
#define MAX_SIZE 100
#define MESSAGE "Hello, World!"
int main() {
printf("Value of PI: %f\n", PI); // Outputs: Value of PI: 3.
printf("Max size is: %d\n", MAX_SIZE); // Outputs: Max size is: 100
printf(MESSAGE); // Outputs: Hello, World!
return 0;
2. Using const Keyword
The const keyword in C allows you to declare a variable whose value cannot be changed after initialization.
It provides type safety, meaning the compiler knows the type of the constant and ensures no modification is
made during the program's execution.
Syntax: const data_type variable_name = value;
data_type : The type of the constant (e.g., int, float, etc.).
variable_name: The name of the constant variable.
Example:
const float PI = 3.14159;
const int MAX_SIZE = 100;
int main() {
printf("Value of PI: %f\n", PI); // Outputs: Value of PI: 3.
printf("Max size is: %d\n", MAX_SIZE); // Outputs: Max size is: 100
return 0;
Difference between Constants and Variables in C
Feature Constants Variables
Definition Constants are fixed values that cannot
be changed once defined.
Variables are data holders whose values can be
modified during program execution.
Value
Modification
Cannot be changed after initialization. Can be changed throughout the program.
Declaration
Syntax
Declared using const keyword or
#define directive.
Declared by specifying data type and variable
name.
Memory
Allocation
Value is stored at a fixed memory
location that is protected.
Memory is allocated for storing data that can be
changed.
Use Cases Used for fixed values like pi, number of
days, etc.
Used when data changes during program
execution, like user input or calculation results.
Scope Scope can be local or global. Scope can be local or global, depending on
where it's declared.
Mutability Immutable (cannot be changed). Mutable (can be changed).
Storage Class Generally stored in read-only memory. Stored in read/write memory.
Example const int DAYS_IN_WEEK = 7; int age = 25;
What Are Variables in C?
Variables in C language are like containers used to store data that a program needs to process. Each variable
has a name, a type, and a value. The type defines what kind of data the variable can hold, like an integer or a
decimal number. The variable's name helps us refer to it later in the code, and its value is the actual data
stored in it.
3. Static Variables
Static variables in C can be either local or global, but their key feature is that they retain their value between
function calls. If declared inside a function, a static variable is initialized only once and maintains its value
across multiple calls to that function.
Example:
void increment() {
static int count = 0; // Static variable
count++;
printf("%d", count);
int main() {
increment(); // Output: 1
increment(); // Output: 2 (retains value from previous call)
return 0;
Scope: If declared globally, they have global scope. If declared locally, they are limited to the function but
retain their value across function calls.
Lifetime: Exists for the entire duration of the program.
4. Automatic Variables
By default, all local variables in C are automatic variables. These variables are created when a function is
called and destroyed when the function exits. The keyword auto can be used to explicitly declare automatic
variables, though it is rarely used as this is the default behavior.
Example:
void display() {
auto int x = 5; // Automatic variable (default behavior for local variables)
printf("%d", x);
Scope: Limited to the function/block they are declared in.
Lifetime: Exists only during the function’s execution.
5. External Variables (extern)
External variables in C language are declared outside of all functions (like global variables) but can be
accessed across multiple files in a project using the extern keyword. They are defined in one file and can be
used in others by declaring them with extern.
Example (File 1 - Declaration):
int globalVar = 50; // External/global variable
Example (File 2 - Usage):
extern int globalVar; // Referencing external variable
void display() {
printf("%d", globalVar); // Can be accessed in this file
Scope: Entire program across multiple files.
Lifetime: Exists for the entire duration of the program.
Data Types in C
Data types in C program help define the kind of data a variable can store, like numbers or letters. Each data type tells the compiler how much memory to allocate and how to interpret the data.
Types of Data Type in C Language
1. Basic Data Types: These include fundamental types like int (for integers), char (for characters), float (for floating-point numbers), and double (for double-precision floating-point numbers). 2. Derived Data Types: These are derived from basic data types and include arrays, pointers, and functions. 3. User-Defined Data Types: These are created by the programmer and include structures (struct), unions (union), and enumerations (enum).
Basic Data Types Derived Data Types User-Defined Data Types
int Arrays struct
char Pointers union
float Functions enum
double typedef
void
1. int:
Used to store integer values, which are whole numbers without a decimal point.
Generally occupies 2 or 4 bytes, depending on the system.
Example
int age = 25;
printf("%d", age);
Output: 25
2. char:
Used to store single characters. Characters are enclosed in single quotes ('A').
Occupies 1 byte of memory.
Example:
char grade = 'A';
Example:
struct Student {
int id;
char name[50];
float grade;
struct Student s1 = {1, "John", 95.5};
printf("ID: %d, Name: %s, Grade: %.1f\n", s1.id, s1.name, s1.grade);
2. Unions (union):
A union is similar to a structure, but members share the same memory location, meaning only one member
can hold a value at a time.
Example:
union Data {
int i;
float f;
union Data data;
data.i = 10;
printf("i: %d\n", data.i);
data.f = 20.5;
printf("f: %.2f\n", data.f); // 'i' is overwritten
3. Enumerations (enum):
An enum is a data type consisting of named integer constants, improving code readability for sets of values.
Example:
enum Days { Sunday, Monday, Tuesday };
enum Days today = Monday;
printf("Today is: %d\n", today);
Output: 1 (for Monday)
Data Types in C with Size and Range
Data Type
Memory Size
Signed Range Unsigned Range
char 1 byte - 128 to 127 0 to 255
short 2 bytes - 32,768 to 32,767 0 to 65,
int 4 bytes - 2,147,483,648 to 2,147,483,647 0 to 4,294,967,
long 4 bytes - 2,147,483,648 to 2,147,483,647 0 to 4,294,967,
long long 8 bytes - 9,223,372,036,854,775,808 to 9,223,372,036,854,775,
0 to 18,446,744,073,709,551,
float 4 bytes 3.4E-38 to 3.4E+38 N/A
double 8 bytes 1.7E-308 to 1.7E+308 N/A
Declaration in c
In C programming, a declaration serves to inform the compiler about the existence and a characteristic of an
identifier (such as a variable, function, or type) before it is used. It specifies the name, data type, and other
attributes, but typically does not allocate memory or provide the full implementation.
There are two primary types of declarations in C:
1. Variable Declarations: These introduce a variable's name and its data type, allowing the compiler to
reserve appropriate memory and perform type checking.
Syntax: type variableName; or type variableName = initialValue;
Example:
int age; // Declares an integer variable named 'age'
double salary = 50000.0; // Declares and initializes a double variable named 'salary'
extern int globalVar; // Declares a variable defined elsewhere (in another file)
2. Function Declarations (Function Prototypes): These inform the compiler about a function's name,
return type, and the types and order of its parameters. This allows the compiler to verify function
calls and ensures correct argument passing.
Syntax: returnType functionName(parameterTypeList);
Example:
int sum(int a, int b); // Declares a function named 'sum' that takes two integers and returns an integer
void printMessage(void); // Declares a function named 'printMessage' that takes no arguments and
returns nothing
Common Escape Sequences in C
Escape
Sequence
Meaning Example Output
\n Newline printf("Hello\nWorld"); Hello
World
\t Horizontal Tab printf("Hello\tWorld"); Hello World
\ Backslash printf("C:\Program C:\Program Files
C
(Traditional)
1972 Dennis Ritchie General-purpose, system
programming, Unix OS.
K&R C 1978 Brian Kernighan,
Dennis Ritchie
First official documentation
and refinement of C.
ANSI C 1989 ANSI Committee Standardized version for cross-
platform compatibility.
C99 1999 Standardization
Committee
Introduced new features like
inline functions and better data
types
Operators in C
Operators in C are symbols that instruct the compiler to perform specific operations on variables and data.
They are used to manipulate data, perform calculations, make decisions, and control the flow of a program.
Operators work with operands, which are the values or variables involved in the operation.
For instance:
If you want to add two numbers, you use the + operator.
If you want to compare two values, you use operators like > (greater than) or < (less than).
If you want to check if something is true or false, you use logical operators like && (AND) or ||
(OR).
Example: int a = 5, b = 10;
int sum = a + b; // '+' is an arithmetic operator
if (a > b) { // '>' is a relational operator
printf("a is greater than b");
How C Operators Work in Expressions?
C language operators are used in expressions to perform operations on values or variables. An expression is
a combination of variables, constants, and operators that produce a value. Operators act on operands and
return a result.
Basic Structure of an Expression:
Operand1 operator operand
Operand : The value or variable involved in the operation.
Operator : The symbol that tells the compiler to perform a specific operation.
Example: int a = 5, b = 10;
int result = a + b;
Types of Operators in C
1. Arithmetic Operators: Arithmetic operators in C language are used to perform basic
mathematical operations on variables and values. These include addition, subtraction, multiplication,
division, and modulus operations.
Name of the Operator Arithmetic Operation Syntax
Addition Adds two operands a + b
Subtraction Subtracts one from another a - b
Multiplication Multiplies two operands a * b
Division Divides one by another a / b
Modulus Finds the remainder a % b
Example:
#include
int main() { int x = 15 , y = 6 ; int result;
// Print initial values printf("x = %d and y = %d\n", x, y);
// Addition result = x + y; printf("x + y = %d\n", result);
// Subtraction result = x - y; printf("x - y = %d\n", result);
// Multiplication result = x * y; printf("x * y = %d\n", result);
// Division result = x / y; printf("x / y = %d\n", result);
// Modulus result = x % y; printf("x %% y = %d\n", result); // Use %% to print '%'
// Equal to if (a == b) { printf("a is equal to b\n"); } else { printf("a is not equal to b\n"); }
// Not equal to if (a != b) { printf("a is not equal to b\n"); }
// Greater than if (a > b) { printf("a is greater than b\n"); }
// Less than if (a < b) { printf("a is less than b\n"); }
// Greater than or equal to if (a >= b) { printf("a is greater than or equal to b\n"); }
// Less than or equal to if (a <= b) { printf("a is less than or equal to b\n"); }
return 0 ; }
3. Logical Operators: Logical operators are used to combine or invert conditions, returning true (1)
or false (0) based on the evaluation of the expressions. They are essential for decision-making in
conditional statements, such as if, while, and for.
Types of Logical Operators:
AND (&&): Returns true if both conditions are true.
OR (||): Returns true if at least one condition is true.
NOT (!): Inverts the value of the condition.
Example: #include
int main() { int x = 5 , y = 10 ; // AND operator if (x > 0 && y > 0 ) { printf("Both x and y are positive\n"); } // OR operator if (x > 0 || y < 0 ) { printf("At least one condition is true\n"); } // NOT operator if (!(x == y)) { printf("x is not equal to y\n"); }
return 0 ; }
4. Bitwise Operators: Bitwise operator allows operations directly on bits of integer values. These
operators are used for manipulating individual bits within an integer, making them essential for low-
level programming, cryptography, and hardware interactions. The operations are performed at the
binary level.
Types of Bitwise Operators:
AND (&): Performs a bitwise AND.
OR (|): Performs a bitwise OR.
XOR (^): Performs a bitwise XOR (exclusive OR).
NOT (~): Inverts the bits.
Left Shift (<<) : Shifts bits to the left.
Right Shift (>>): Shifts bits to the right.
*= Multiply and Assign a *= b
/= Divide and Assign a /= b
%= Modulus and Assign a %= b
Example: #include
int main() { int a = 10 , b = 5 ; // Basic assignment a = b; printf("a = %d\n", a); // a becomes 5 // Compound assignment operators a += 3 ; // equivalent to a = a + 3 printf("a += 3 - > %d\n", a); a *= 2 ; // equivalent to a = a * 2 printf("a *= 2 - > %d\n", a); a - = 4 ; // equivalent to a = a - 4 printf("a - = 4 - > %d\n", a); a /= 3 ; // equivalent to a = a / 3 printf("a /= 3 - > %d\n", a); return 0 ; }
6. Increment and Decrement Operators: Increment (++) and decrement (--) operators are used to increase or decrease the value of a variable by 1. They can be used in two forms: prefix (before the variable) and postfix (after the variable).
In prefix, the operation is performed before the value is used, while in postfix, the original value is
used first, and then the operation is performed.
Operator Symbol Name Syntax
++ Increment ++x or x++
Example:
7. Conditional (Ternary) Operator: The conditional or ternary operator is a shorthand way of
writing an if-else statement. It uses the symbols? and: and returns one of two values depending on
the evaluation of a condition. If the condition is true, the first expression is executed, otherwise, the
second expression is executed.
Syntax : condition? expression_if_true : expression_if_false;
Example: