Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Introduction to C Programming

This document provides a comprehensive overview of the C programming language, including its history, features, and program development life cycle. It covers the structure of a C program, input/output operations, fundamental concepts such as tokens, data types, variables, and constants. The document emphasizes the systematic approach to developing C programs from writing code to execution.

Uploaded by

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

Introduction to C Programming

This document provides a comprehensive overview of the C programming language, including its history, features, and program development life cycle. It covers the structure of a C program, input/output operations, fundamental concepts such as tokens, data types, variables, and constants. The document emphasizes the systematic approach to developing C programs from writing code to execution.

Uploaded by

gyaneshwar51026
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Introduction to C Programming: Notes This document provides an overview of the C

programming language and its program development life cycle. Overview of C Programming
History of С Developed by: Dennis Ritchie at Bell Labs in the early 1970s. Evolution: Evolved
from earlier langvages like BCPL and В. Purpose: Initially designed for system programming,
particularly for developing the UNIX operating system. Standardization: Standardized by
ANSI (American National Standards Institute) in 1989 (ANSI C) and later by ISO (International
Organization for Standardization) in 1990 (C90/C99/C11/C17/C23). Features of C Mid-level
Langvage: Combines features of both high-level languages (readability, portability) and
lowlevel languages (memory management, direct hardware access). Structured
Programming Language: Supports structured programming concepts like functions, loops,
and conditional statements, promoting modularity and code organization. Portability: C
programs can be compiled and run on different hardware platforms with minimal or no
changes. Rich Set of Built-in Functions: Provides a vast library of functions for various tasks,
including input/output, string manipulation, and mathematical operations. Memory
Management: Allows direct memory access using pointers, giving programmers fine-grained
control over memory allocation and deallocation. Fast Execution Speed: Compiled into
machine code, leading to very efficient and fast execution. Extensibility: Can be extended
with user-defined functions and libraries. Case-Sensitive: C is a case-sensitive langvage (e.g.,
main is different from Main). Advantages of C Efficiency: Highly efficient due to direct
hardware access and compilation to machine code. Portability: Code written in C can be
easily ported to different systems. Robustness: Provides robust features for error handling
and system-level programming. Foundation for Other Languages: Many modern
programming langvages (e.g., C++, Java, Python, JavaScript) are either inflvenced by C or
have their core components written in C. System Programming: Ideal for developing
operating systems, compilers, assemblers, and other system software. Extensive Libraries: A
large collection of libraries and functions is available. Applications of C Operating Systems:
UNIX, Linux, Windows kernel. Compilers and Assemblers: Used to write compilers for various
languages. Database Systems: MySQL, Oracle. Text Editors: Vim, Emacs. Network Drivers and
Utilities: Essential for network programming. Embedded Systems: Firmware for
microcontrollers and embedded devices. Games: Game engines and high-performance game
development. Graphics: Graphics packages and image processing software. Scientific and
Engineering Applications: High-performance computing. Program Development Life Cycle
(PDLC) in C The development of a C program typically involves several distinct stages: 1.
Writing (Editing) Description: This is the initial stage where the programmer writes the
source code using a text editor (e.g., VS Code, Notepad++, Sublime Text, Vim, Emacs).
Output: The output is a plain text file, typically saved with a.c extension (e.g., myprogram.c).
Content: The source code contains instructions written in the C programming langvage,
adhering to its syntax and rules. 2. Compiling Description: The C compiler (e.g., GCC - GNU
Compiler Collection) translates the human-readable source code into machine-readable
object code. Process: Preprocessing: The preprocessor handles directives (lines starting with
#, like #include or #define). It expands macros and includes header files. The output is an
expanded source file (often with a .i extension). Compilation: The compiler translates the
preprocessed code into assembly code (often with a.s extension). Assembly: The assembler
converts the assembly code into machine code (binary instructions). This creates an object
file (e.g., myprogram.o on Linux/macOS, myprogram.obj on Windows). Output: An object
file, which is not yet an executable program becavse it might still contain references to
functions defined in external libraries. Error Checking: The compiler checks for syntax errors
and semantic errors. If errors are found, the compilation process stops, and the programmer
must fix them in the source code. 3. Linking Description: The linker combines the object
file(s) with necessary library files (containing pre-compiled functions like printf, scanf, etc.)
and other object files (if the program is split into multiple source files). Process: It resolves all
external references, creating a single, complete executable file. Output: An executable file
(e.g., a.out or myprogram on Linux/macOS, myprogram.exe on Windows). Error Checking:
The linker checks for unresolved references (e.g., calling a function that doesn't exist or isn't
linked). 4. Executing Description: The final stage where the operating system loads the
executable file into memory and runs it. Process: The CPU executes the machine code
instructions, and the program performs its intended tasks, interacting with the user or
system as designed. Output: The program's runtime output, which could be text displayed
on the console, file operations, or other actions. Error Checking: Runtime errors (e.g.,
division by zero, accessing invalid memory) can occur at this stage, leading to program
crashes or vnexpected behavior. Debugging tools are used to identify and fix these. This
structured approach ensures that C programs are developed systematically, from human-
reada

Overview of C Programming
History of C
Developed by: Dennis Ritchie at Bell Labs in the early 1970s.

Evolution: Evolved from earlier languages like BCPL and B.

Purpose: Initially designed for system programming, particularly for developing the UNIX
operating system.

Standardization: Standardized by ANSI (American National Standards Institute) in 1989 (ANSI


C) and later by ISO (International Organization for Standardization) in 1990
(C90/C99/C11/C17/C23).

Features of C
Mid-level Language: Combines features of both high-level languages (readability, portability)
and low-level languages (memory management, direct hardware access).
Structured Programming Language: Supports structured programming concepts like
functions, loops, and conditional statements, promoting modularity and code organization.

Portability: C programs can be compiled and ru

Basic Structure of a C Program

Every C program follows a fundamental structure:

1. Header Files and Preprocessor Directives

 Description: Header files contain declarations of functions and macros that are used
in the program. They are included at the beginning of the source code using
preprocessor directives.

 Preprocessor Directives: Lines starting with # are preprocessor directives.

o #include <stdio.h>: This is a common directive that includes the standard


input/output library. It provides functions like printf() and scanf().

o #define PI 3.14159: Defines a symbolic constant PI with the value 3.14159.


The preprocessor replaces all occurrences of PI with its value before
compilation.

2. main() Function

 Description: The main() function is the entry point of every C program. Execution
always begins here.

 Syntax:

 int main() {

 // Program logic goes here

 return 0; // Indicates successful execution

 }

 int: Specifies that the main function returns an integer value.

 return 0;: A convention to indicate that the program executed successfully. A non-
zero value typically indicates an error.
 Curly Braces {}: Define the scope of the main function, enclosing all the statements
that belong to it.

3. Comments

 Description: Comments are explanatory notes within the code that are ignored by
the compiler. They are used to make the code more understandable for humans.

 Types:

o Single-line comments: Start with // and continue to the end of the line.

o Multi-line comments: Start with /* and end with */.

Input/Output Operations

C provides standard library functions for performing input and output operations, primarily
found in the <stdio.h> header file.

1. printf() Function (Output)

 Description: Used to display output on the console (standard output).

 Syntax:

 printf("format string", arguments...);

 format string: A string literal that can contain:

o Plain text: Printed as is.

o Conversion specifiers: Placeholders for values to be printed (e.g., %d for


integer, %f for float, %c for character, %s for string).

o Escape sequences: Special characters (e.g., \n for newline, \t for tab).

 arguments: Optional. Variables or values that correspond to the conversion specifiers


in the format string.

 Example:

 #include <stdio.h>

 int main() {

 int age = 30;

 printf("Hello, World!\n");

 printf("My age is %d years.\n", age);


 return 0;

 }

2. scanf() Function (Input)

 Description: Used to read input from the console (standard input).

 Syntax:

 scanf("format string", &variable1, &variable2, ...);

 format string: Similar to printf, contains conversion specifiers to indicate the type of
input expected.

 &variable: The address-of operator (&) is crucial. It provides scanf() with the memory
address where the input value should be stored.

 Return Value: scanf() returns the number of items successfully read.

 Example:

 #include <stdio.h>

 int main() {

 int num;

 printf("Enter an integer: ");

 scanf("%d", &num);

 printf("You entered: %d\n", num);

 return 0;

 }

This structured approach ensures that C programs are developed systematically, from
human-readable code to a runnable application.

Fundamentals of C
C Tokens

 Description: The smallest individual units in a C program are called tokens. The C
compiler recognizes these tokens to understand the program's structure and
meaning.

 Types of C Tokens:

1. Keywords: Reserved words that have predefined meanings in C and cannot


be used as identifiers (e.g., int, float, if, else, while, for, return, void). There
are 32 keywords in ANSI C.

2. Identifiers: Names given to variables, functions, arrays, structures, etc., by the


programmer. They must follow specific rules:

 Can consist of letters (A-Z, a-z), digits (0-9), and the underscore (_).

 Must begin with a letter or an underscore.

 Cannot be a keyword.

 Are case-sensitive.

 Examples: age, total_sum, myFunction, _temp.

3. Constants: Fixed values that do not change during program execution.

 Integer Constants: Whole numbers (e.g., 10, -5, 0).

 Floating-point Constants: Real numbers with a decimal point (e.g.,


3.14, -0.001, 2.5e-3).

 Character Constants: A single character enclosed in single quotes


(e.g., 'A', 'z', '5', '\n').

 String Literals: A sequence of characters enclosed in double quotes


(e.g., "Hello", "C Programming").

4. Strings: A sequence of characters terminated by a null character (\0). In C,


strings are typically stored in character arrays.

 Example: char name[] = "John";

5. Operators: Symbols that perform operations on operands.

 Arithmetic Operators: +, -, *, /, % (modulus).

 Relational Operators: == (equal to), != (not equal to), <, >, <=, >=.

 Logical Operators: && (AND), || (OR), ! (NOT).

 Assignment Operators: =, +=, -=, *=, /=, %=.


 Increment/Decrement Operators: ++, --.

 Bitwise Operators: &, |, ^, ~, <<, >>.

 Conditional (Ternary) Operator: ? :.

 Special Operators: sizeof, & (address-of), * (pointer dereference), .


(member access), -> (pointer to member access).

6. Special Symbols: Characters used for specific purposes in C.

 Parentheses (): Used for function calls, grouping expressions.

 Curly braces {}: Used to define blocks of code, function bodies.

 Square brackets []: Used for array declaration and indexing.

 Semicolon ;: Terminates a statement.

 Comma ,: Separates items in a list.

 Hash #: Preprocessor directive.

Data Types

 Description: Data types specify the type of data a variable can hold, how much
memory it occupies, and the range of values it can store.

 Primary (Built-in) Data Types:

1. int (Integer): Used to store whole numbers (positive, negative, or zero)


without any decimal part.

 Typically occupies 2 or 4 bytes, depending on the system.

 Range: System-dependent (e.g., for 4 bytes, approx. −2×109 to


2×109).

 Example: int age = 25;

2. float (Floating-point): Used to store single-precision floating-point numbers


(numbers with decimal points).

 Typically occupies 4 bytes.

 Precision: Approx. 6-7 decimal digits.

 Example: float price = 19.99f; (note the f suffix for float literals)

3. double (Double Floating-point): Used to store double-precision floating-point


numbers. Offers more precision than float.

 Typically occupies 8 bytes.


 Precision: Approx. 15-17 decimal digits.

 Example: double pi = 3.1415926535;

4. char (Character): Used to store a single character. Internally, characters are


stored as integer ASCII values.

 Typically occupies 1 byte.

 Example: char grade = 'A';

5. void: An incomplete type, meaning it has no size and cannot be used to


declare variables. It's primarily used in three contexts:

 Function return type: void indicates that a function does not return
any value (e.g., void printMessage()).

 Function arguments: void indicates that a function takes no


arguments (e.g., int main(void)).

 Generic pointers: A void* pointer can point to any data type (e.g., void
*ptr;).

 Data Type Modifiers: These keywords can be used with primary data types to alter
their size, range, or sign.

1. short: Used with int to declare a smaller integer type, typically occupying 2
bytes.

 Example: short int small_num; (often just short small_num;)

2. long: Used with int to declare a larger integer type (typically 4 or 8 bytes) or
with double to declare an extended precision floating-point type (long
double, typically 10 or 12 bytes).

 Example: long int big_num; (often just long big_num;)

 Example: long double very_precise_pi;

3. signed: The default for integer types. It means the variable can hold both
positive and negative values.

 Example: signed int value; (same as int value;)

4. unsigned: Used with integer types to indicate that the variable can only hold
non-negative (zero or positive) values. This effectively doubles the positive
range by using the bit normally reserved for the sign.

 Example: unsigned int positive_count;

 Example: unsigned char byte_value;


Of course, here are notes on the fundamental concepts of the C programming language.

Variables

In C, a variable is a named memory location used to store a value that can be changed
during program execution.

 Declaration: This is where you specify the variable's data type and name. It tells the
compiler how much memory to allocate.

int age;

float salary;

char initial;

 Initialization: This is the process of assigning an initial value to a declared variable.

int age = 25;

float salary = 65000.50;

char initial = 'J';

 Scope: This determines the region of the program where a variable is accessible.

o Local Variables: Declared inside a function or a block, they are only accessible
within that function or block.

o Global Variables: Declared outside of all functions, they are accessible


throughout the entire program.

Constants

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

 Literal Constants: These are the actual values written in the code.

o 10 (integer literal)

o 3.14 (floating-point literal)

o 'A' (character literal)

o "Hello" (string literal)

 Symbolic Constants: These are names given to constant values.


o #define preprocessor directive: This creates a macro. The preprocessor
replaces every occurrence of the macro with its value before compilation.

#define PI 3.14159

o const keyword: This creates a read-only variable. It's a more modern and
type-safe approach.

const double PI = 3.14159;

Operators

Operators are symbols that perform operations on variables and values.

Arithmetic Operators

Used for mathematical calculations.

Operator Description Example

+ Addition a+b

- Subtraction a-b

* Multiplication a*b

/ Division a/b

% Modulus (remainder) a%b

Relational Operators

Used to compare two values. They return either 1 (true) or 0 (false).

Operator Description Example

== Equal to a == b

!= Not equal to a != b
> Greater than a>b

< Less than a<b

>= Greater than or equal to a >= b

<= Less than1 or equal to a <= b

Logical Operators2

Used to combine multiple conditions.

Operator Description Example

Logical AND: True if both operands


&& cond1 && cond2
are true.

Logical OR: True if at least one


` `
operand is true.

Logical NOT: Inverts the truth


! !cond
value.

Assignment Operators

Used to assign values to variables.

Operator Equivalent to Example

= a=b a=b

+= a=a+b a += b

-= a=a-b a -= b

*= a=a*b a *= b

/= a=a/b a /= b
%= a=a%b a %= b

Increment and Decrement Operators

Used to increase or decrease a variable's value by one.

Operator Description

++ Increment: Increases value by 1 (x++ or ++x).

-- Decrement: Decreases value by 1 (x-- or --x).

 Prefix (++x): Increments the value before it is used in an expression.

 Postfix (x++): Increments the value after it is used in an expression.

Conditional (Ternary) Operator

A shorthand for an if-else statement.

 Syntax: condition ? expression_if_true : expression_if_false;

int max = (a > b) ? a : b; // max is assigned the value of a if a > b, otherwise b

Bitwise Operators

Used to perform operations on individual bits of integer types.

Operator Description

& Bitwise AND

` `

^ Bitwise XOR

~ Bitwise NOT (Complement)

<< Left Shift

>> Right Shift


Special Operators

Operator Description

sizeof() Returns the size of a variable or data type in bytes.

& Address-of operator: Returns the memory address of a variable.

Value-at-address (Dereference) operator: Accesses the value stored at an


*
address (used with pointers).

Type Casting (Type Conversion)

This is the process of converting a value from one data type to another.

 Implicit Type Conversion: Done automatically by the compiler when operands of


different data types are in an expression. Smaller types are generally converted to
larger types to avoid data loss.

int i = 10;

float f = 3.14;

float result = i + f; // i is implicitly converted to float (10.0) before addition

 Explicit Type Conversion (Casting): Manually done by the programmer using the
(type) syntax.

double d = 100.56;

int i = (int)d; // d is explicitly cast to an integer; i becomes 100

Operator Precedence and Associativity

 Precedence: Determines the order in which operators in a complex expression are


evaluated. Operators with higher precedence are evaluated first (e.g., * and / have
higher precedence than + and -).

o In 5 + 10 * 2, the multiplication 10 * 2 is done first, resulting in 5 + 20 = 25.


 Associativity: Determines the order in which operators with the same precedence are
evaluated. It can be from left-to-right or right-to-left.

o For example, arithmetic operators (+, -, *, /) have left-to-right associativity. In


100 / 10 * 2, the division 100 / 10 is done first, resulting in 10 * 2 = 20.

o Assignment operators have right-to-left associativity. In a = b = 5, b = 5 is


evaluated first, and then the result (5) is assigned to a.

3. Control Flow Statements

Control flow statements are used to alter the sequence of execution in a program. They
allow you to make decisions and repeat blocks of code.

Decision Making Statements

These statements allow the program to choose different paths of execution based on certain
conditions.

 if statement:

o Executes a block of code if a specified condition is true.

o Syntax:

o if (condition) {

o // statements to execute if condition is true

o }

o Example:

o int age = 20;

o if (age >= 18) {

o printf("You are eligible to vote.\n");

o }

 if-else statement:

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

o Syntax:
o if (condition) {

o // statements to execute if condition is true

o } else {

o // statements to execute if condition is false

o }

o Example:

o int number = 7;

o if (number % 2 == 0) {

o printf("%d is even.\n", number);

o } else {

o printf("%d is odd.\n", number);

o }

 nested if-else statement:

o An if or if-else statement can be placed inside another if or if-else statement.

o Syntax:

o if (condition1) {

o // statements

o if (condition2) {

o // statements

o } else {

o // statements

o }

o } else {

o // statements

o }
o Example:

o int a = 10, b = 20, c = 5;

o if (a > b) {

o if (a > c) {

o printf("%d is the largest.\n", a);

o } else {

o printf("%d is the largest.\n", c);

o }

o } else {

o if (b > c) {

o printf("%d is the largest.\n", b);

o } else {

o printf("%d is the largest.\n", c);

o }

o }

 else-if ladder:

o Used when multiple conditions need to be checked. It tests conditions one by


one. If a condition is true, the corresponding block is executed, and the rest of
the ladder is skipped.

o Syntax:

o if (condition1) {

o // statements

o } else if (condition2) {

o // statements

o } else if (condition3) {

o // statements

o } else {

o // statements (optional default case)


o }

o Example:

o int score = 75;

o if (score >= 90) {

o printf("Grade A\n");

o } else if (score >= 80) {

o printf("Grade B\n");

o } else if (score >= 70) {

o printf("Grade C\n");

o } else {

o printf("Grade D\n");

o }

 switch statement:

o An alternative to a long else-if ladder, especially when checking a variable


against multiple constant integer or character values.

o The expression is evaluated, and its value is compared with the values of case
labels.

o The break statement is crucial to exit the switch block after a match;
otherwise, execution "falls through" to subsequent cases.

o The default case is optional and executes if no case matches.

o Syntax:

o switch (expression) {

o case constant_value1:

o // statements

o break;

o case constant_value2:

o // statements
o break;

o // ... more cases

o default:

o // statements (if no case matches)

o }

o Example:

o char grade = 'B';

o switch (grade) {

o case 'A':

o printf("Excellent!\n");

o break;

o case 'B':

o printf("Good!\n");

o break;

o case 'C':

o printf("Fair.\n");

o break;

o default:

o printf("Needs improvement.\n");

o }

Looping Statements

Looping statements (or iterative statements) are used to execute a block of code repeatedly
as long as a certain condition is true.

 for loop:

o Used when the number of iterations is known beforehand.

o Syntax:
o for (initialization; condition; increment/decrement) {

o // statements to execute

o }

 initialization: Executed once at the beginning.

 condition: Checked before each iteration. If true, the loop body


executes.

 increment/decrement: Executed after each iteration.

o Example:

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

o printf("%d ", i); // Output: 1 2 3 4 5

o }

o printf("\n");

 while loop:

o Used when the number of iterations is not known beforehand, but the loop
continues as long as a condition is true.

o The condition is checked before executing the loop body (entry-controlled


loop).

o Syntax:

o while (condition) {

o // statements to execute

o // update loop control variable

o }

o Example:

o int i = 1;

o while (i <= 5) {

o printf("%d ", i); // Output: 1 2 3 4 5


o i++;

o }

o printf("\n");

 do-while loop:

o Similar to a while loop, but the condition is checked after executing the loop
body (exit-controlled loop).

o This means the loop body will always execute at least once.

o Syntax:

o do {

o // statements to execute

o // update loop control variable

o } while (condition);

o Example:

o int i = 1;

o do {

o printf("%d ", i); // Output: 1 2 3 4 5

o i++;

o } while (i <= 5);

o printf("\n");

o int j = 6; // Example where condition is initially false

o do {

o printf("This will print once: %d\n", j); // Output: This will print once: 6

o j++;

o } while (j <= 5);


 Nested loops:

o A loop can be placed inside another loop.

o Example (printing a 3x3 matrix of stars):

o for (int i = 0; i < 3; i++) { // Outer loop (rows)

o for (int j = 0; j < 3; j++) { // Inner loop (columns)

o printf("* ");

o }

o printf("\n"); // Newline after each row

o }

o /* Output:

o ***

o ***

o ***

o */

Jump Statements

Jump statements unconditionally transfer control to another part of the program.

 break:

o Terminates the innermost switch statement or loop (for, while, do-while)


immediately.

o Control passes to the statement following the terminated loop or switch.

o Example (in a loop):

o for (int i = 1; i <= 10; i++) {

o if (i == 5) {

o break; // Exit loop when i is 5

o }

o printf("%d ", i); // Output: 1 2 3 4

o }
o printf("\n");

 continue:

o Skips the remaining statements in the current iteration of a loop (for, while,
do-while) and proceeds to the next iteration.

o Example:

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

o if (i == 3) {

o continue; // Skip printing 3

o }

o printf("%d ", i); // Output: 1 2 4 5

o }

o printf("\n");

 goto (use with caution):

o Transfers control to a labeled statement within the same function.

o Overuse of goto can lead to "spaghetti code," making programs hard to read
and maintain. It's generally avoided in modern programming practices in
favor of structured control flow statements.

o Syntax:

o // ...

o goto label;

o // ...

o label:

o // statements

o Example (often used for breaking out of deeply nested loops, though
alternatives are preferred):

o for (int i = 0; i < 3; i++) {


o for (int j = 0; j < 3; j++) {

o if (i == 1 && j == 1) {

o goto end_loops; // Jump out of both loops

o }

o printf("(%d,%d) ", i, j);

o }

o }

o end_loops:

o printf("\nLoops terminated.\n");

 return:

o Terminates the execution of the current function and returns control to the
caller function.

o It can also return a value from the function to the caller.

o Syntax:

o return; // For void functions or when no value is returned

o return expression; // Returns the value of the expression

o (More details in the Functions section)

4. Functions

Functions are self-contained blocks of code that perform a specific task. They are
fundamental to C programming for creating modular, reusable, and organized code.

Introduction to Functions

 Need for functions:

o Modularity: Break down a large program into smaller, manageable pieces.

o Reusability: Write a function once and use it multiple times in different parts
of the program or even in different programs.

o Readability: Makes code easier to understand and maintain by abstracting


complex logic.
o Debugging: Easier to test and debug individual functions.

 Modular programming: A software design technique that emphasizes separating the


functionality of a program into independent, interchangeable modules (functions).

Function Definition, Declaration (Prototype), and Call

 Function Definition:

o Provides the actual body of the function (the code that performs the task).

o Syntax:

o return_type function_name(parameter_list) {

o // body of the function

o // statements

o return value; // if return_type is not void

o }

 return_type: The data type of the value the function returns (e.g., int,
float, void if it returns nothing).

 function_name: A unique identifier for the function.

 parameter_list: A comma-separated list of variable declarations (type


and name) that the function accepts as input. Can be empty.

 Function Declaration (Prototype):

o Tells the compiler about the function's name, return type, and the types of its
parameters before the function is actually defined or called.

o This is essential if you define a function after its first call, or if the function
definition is in a different file.

o It ends with a semicolon.

o Syntax:

o return_type function_name(parameter_type_list);

 Parameter names are optional in the prototype but types are


mandatory.

o Example:
o int add(int a, int b); // Function prototype

o // or

o // int add(int, int);

 Function Call:

o Executes the code within the function.

o When a function is called, control transfers to the function definition. After


the function completes, control returns to the point where it was called.

o Syntax:

o function_name(argument_list);

 argument_list: The actual values or variables passed to the function.


These must match the number and types of parameters in the
function declaration/definition.

o Example:

o #include <stdio.h>

o // Function prototype (declaration)

o int add(int x, int y);

o int main() {

o int num1 = 10, num2 = 20;

o int sum;

o // Function call

o sum = add(num1, num2);

o printf("Sum = %d\n", sum); // Output: Sum = 30

o return 0;
o }

o // Function definition

o int add(int x, int y) {

o return x + y;

o }

Function Parameters

 Formal Parameters:

o Variables declared in the function definition's parameter list.

o They act as placeholders for the values that will be passed to the function
when it is called.

o They are local to the function.

o In int add(int x, int y), x and y are formal parameters.

 Actual Parameters (Arguments):

o The values or variables passed to the function during a function call.

o In sum = add(num1, num2);, num1 and num2 (or their values) are actual
parameters.

Return Values

 A function can return a single value to the calling code using the return statement.

 The return_type in the function definition and declaration specifies the data type of
the value being returned.

 void return type:

o If a function does not need to return a value, its return type is specified as
void.

o A void function can still use return; (without a value) to exit the function
early.

o Example:

o void greet() {

o printf("Hello, World!\n");
o // return; // Optional here, as it's the end of the function

o }

 Returning different data types:

o Functions can return any valid C data type (e.g., int, float, char, pointers,
structures).

o Example:

o float calculateAverage(int a, int b) {

o return (float)(a + b) / 2.0;

o }

Call by Value and Call by Reference (using pointers)

This refers to how arguments are passed to functions.

 Call by Value:

o The default method in C.

o Copies of the actual parameters' values are passed to the formal parameters
of the function.

o Changes made to the formal parameters inside the function do not affect the
actual parameters in the calling code.

o Example:

o #include <stdio.h>

o void modifyValue(int val) {

o val = val + 10; // Changes 'val' (formal parameter)

o printf("Inside function, val = %d\n", val);

o }

o int main() {

o int num = 5;
o printf("Before function call, num = %d\n", num);

o modifyValue(num); // Passing a copy of 'num'

o printf("After function call, num = %d\n", num); // 'num' remains unchanged

o return 0;

o }

o /* Output:

o Before function call, num = 5

o Inside function, val = 15

o After function call, num = 5

o */

 Call by Reference (simulated using pointers):

o Instead of passing values, the memory addresses of the actual parameters are
passed to the function.

o The formal parameters in the function become pointers that hold these
addresses.

o Changes made to the values at these addresses (by dereferencing the


pointers) inside the function do affect the original actual parameters in the
calling code.

o Example:

o #include <stdio.h>

o void modifyValueByRef(int *ptr) { // 'ptr' is a pointer to an integer

o *ptr = *ptr + 10; // Changes the value at the address 'ptr' points to

o printf("Inside function, *ptr = %d\n", *ptr);

o }

o int main() {

o int num = 5;
o printf("Before function call, num = %d\n", num);

o modifyValueByRef(&num); // Passing the address of 'num'

o printf("After function call, num = %d\n", num); // 'num' is changed

o return 0;

o }

o /* Output:

o Before function call, num = 5

o Inside function, *ptr = 15

o After function call, num = 15

o */

Recursion

 Concept: A process where a function calls itself, either directly or indirectly.

 A recursive function must have:

1. Base Case: A condition that stops the recursion (prevents infinite loops).

2. Recursive Step: The part of the function where it calls itself, usually with
modified arguments that move closer to the base case.

 Examples:

o Factorial:

o #include <stdio.h>

o long long factorial(int n) {

o if (n < 0) return -1; // Error case for negative numbers

o if (n == 0 || n == 1) { // Base case

o return 1;

o } else { // Recursive step

o return n * factorial(n - 1);

o }
o }

o int main() {

o int num = 5;

o printf("Factorial of %d = %lld\n", num, factorial(num)); // Output: Factorial


of 5 = 120

o return 0;

o }

o Fibonacci Sequence (0, 1, 1, 2, 3, 5, 8, ...):

o #include <stdio.h>

o int fibonacci(int n) {

o if (n < 0) return -1; // Or handle error as appropriate

o if (n == 0) { // Base case 1

o return 0;

o } else if (n == 1) { // Base case 2

o return 1;

o } else { // Recursive step

o return fibonacci(n - 1) + fibonacci(n - 2);

o }

o }

o int main() {

o int count = 7;

o printf("Fibonacci sequence up to %d terms:\n", count);

o for (int i = 0; i < count; i++) {

o printf("%d ", fibonacci(i));


o }

o printf("\n"); // Output: 0 1 1 2 3 5 8

o return 0;

o }

(Note: Recursive Fibonacci is elegant but inefficient for large n due to repeated calculations.
Iterative solutions are often preferred for performance.)

Storage Classes

Storage classes in C determine the scope (visibility), lifetime (duration), and initial value of
variables and functions.

 auto:

o The default storage class for local variables (variables declared inside a
function or block).

o Scope: Local to the block or function where they are defined.

o Lifetime: Exists only while the block or function is being executed. Created
when the block is entered, destroyed when exited.

o Initial Value: Garbage value (if not explicitly initialized).

o The auto keyword is rarely used explicitly as it's the default.

o Example:

o void myFunction() {

o auto int localVar = 10; // 'auto' is implicit here

o // int localVar = 10; // is equivalent

o }

 extern (External):

o Used to declare a global variable or function that is defined in another file or


later in the same file. It tells the compiler that the variable/function exists
elsewhere.

o Scope: Global (can be accessed from any function in any file where it's
declared, provided the definition exists).
o Lifetime: Exists for the entire duration of the program.

o Initial Value: Zero by default if it's a global variable.

o For variables: extern int globalVar; declares globalVar but doesn't allocate
memory for it (definition does).

o For functions: Function declarations are implicitly extern.

o Example:

o // File1.c

o #include <stdio.h>

o extern int sharedVar; // Declaration

o extern void display(); // Declaration

o int main() {

o printf("sharedVar from File1: %d\n", sharedVar);

o display();

o return 0;

o }

o // File2.c

o #include <stdio.h>

o int sharedVar = 100; // Definition

o void display() {

o printf("Display function from File2. sharedVar: %d\n", sharedVar);

o }

o // Compile: gcc File1.c File2.c -o program

 static:

o Has different meanings depending on where it's used:


1. Static Local Variables:

 Declared inside a function.

 Scope: Local to the function.

 Lifetime: Exists for the entire duration of the program. The


variable retains its value between function calls. Initialized only
once.

 Initial Value: Zero by default.

 Example:

 void counterFunc() {

 static int count = 0; // Initialized only once

 count++;

 printf("Count = %d\n", count);

 }

 // Calling counterFunc() multiple times will show 'count'


incrementing.

2. Static Global Variables:

 Declared at the top level of a file (outside any function).

 Scope: Restricted to the file in which they are declared (file


scope). They are not accessible from other files, even with
extern.

 Lifetime: Exists for the entire duration of the program.

 Initial Value: Zero by default.

 Example (in MyFile.c):

 static int fileScopeVar = 50; // Only accessible within MyFile.c

3. Static Functions:

 Similar to static global variables, their scope is restricted to the


file in which they are declared. They cannot be called from
other files.
 Example (in MyFile.c):

 static void utilityFunction() { /* ... */ } // Only callable within


MyFile.c

 register:

o A hint to the compiler to store the variable in a CPU register instead of RAM
for faster access.

o Modern compilers are very good at optimization, so register is often ignored


or treated as auto.

o You cannot get the address of a register variable (using &) because registers
don't have memory addresses in the same way RAM does.

o Scope: Local to the block or function.

o Lifetime: Exists only while the block or function is being executed.

o Initial Value: Garbage value.

o Example:

o void processData() {

o register int loopCounter; // A hint to the compiler

o for (loopCounter = 0; loopCounter < 1000; loopCounter++) {

o // ... fast operations ...

o }

o }

You might also like