[go: up one dir, main page]

0% found this document useful (0 votes)
2 views15 pages

C Programming

The document outlines the syllabus for the CS3251 - Programming in C course at Anna University, detailing five units that cover fundamental to advanced topics in C programming. It includes definitions and examples of functions, variables, and library functions, as well as concepts like modular programming, recursion, and the importance of user-defined functions. Additionally, it explains function declaration, calling, parameters, return types, and the differences between call by value and call by reference.
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)
2 views15 pages

C Programming

The document outlines the syllabus for the CS3251 - Programming in C course at Anna University, detailing five units that cover fundamental to advanced topics in C programming. It includes definitions and examples of functions, variables, and library functions, as well as concepts like modular programming, recursion, and the importance of user-defined functions. Additionally, it explains function declaration, calling, parameters, return types, and the differences between call by value and call by reference.
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/ 15

As per the Anna University Regulation 2021, the first-year engineering syllabus for the

course CS3251 - Programming in C is divided into five units covering the fundamentals of the
language to more complex topics like file processing.
Unit I: Basics of C programming
This unit covers introductory programming concepts and the fundamental elements of the C
language, including its structure, data types, operators, expressions, control flow statements
(if, switch, for, while, do-while), and the compilation process.
Unit II: Arrays and strings
This unit focuses on arrays and strings, covering the declaration and use of one-dimensional
and two-dimensional arrays, basic string operations, and implementation of sorting (selection
sort) and searching (linear and binary search) algorithms.
Unit III: Functions and pointers
This unit introduces modular programming with functions, including function prototypes,
definitions, calls, and recursion. It also covers pointers, pointer arithmetic, the relationship
between arrays and pointers, and different methods of parameter passing.

Unit IV: Structures and unions


This unit explores user-defined data types like structures and unions, including defining and
using them, nested structures, pointers with structures, arrays of structures, self-referential
structures, dynamic memory allocation, and storage classes.
Unit V: File processing
This unit teaches file handling in C, covering different types of file processing (sequential and
random access), operations on files, and the use of command-line arguments.

Define function in c programming

In C programming, a function is a block of code that performs a specific task and can be reused in a
program.

🔹 Definition:

A function in C is a self-contained block of statements that performs a particular operation and can be
called (invoked) from other parts of the program.
Syntax:
return_type function_name(parameter_list)
{
// body of the function
}
Example:
#include <stdio.h>

// Function definition
int add(int a, int b)
{
return a + b; // returns the sum
}

int main()
{
int result = add(5, 3); // Function call
printf("Sum = %d", result);
return 0;
}

Parts of a Function:

1. Return type – Type of value the function returns (e.g., int, float, void).

2. Function name – Unique name to identify the function.

3. Parameters (arguments) – Input values passed to the function.

4. Function body – Set of statements that define what the function does.

5. Return statement – Sends a value back to the calling function.

🔹 Types of Functions:

1. Library functions – Predefined in C libraries (e.g., printf(), scanf(), sqrt()).

2. User-defined functions – Created by the programmer to perform custom tasks.

Library Function in C Programming

A library function in C is a predefined function that is already written, compiled, and stored in
C libraries (such as stdio.h, math.h, string.h, etc.).
These functions are ready to use, so you don’t have to write the code for common tasks like
input/output, mathematical calculations, string operations, etc.

Definition:

A library function is a function that is provided by the C standard library to perform common
operations.

Example:

#include <stdio.h>

#include <math.h>

int main() {

double num = 9.0;


double result = sqrt(num); // sqrt() is a library function

printf("Square root of %.2f = %.2f", num, result);

return 0;

Output:

Square root of 9.00 = 3.00

 sqrt() is a library function defined in math.h.


 printf() is another library function defined in stdio.h.

Common Header Files and Their Library Functions:

Header File Common Library Functions Purpose


printf(), scanf(), getchar(), putchar(), gets(),
stdio.h
puts()
Input and Output functions
math.h sqrt(), pow(), ceil(), floor(), sin(), cos() Mathematical operations
string.h strlen(), strcpy(), strcmp(), strcat() String handling functions
Memory management and
stdlib.h malloc(), free(), atoi(), exit()
conversions
ctype.h toupper(), tolower(), isdigit(), isalpha() Character handling
time.h time(), clock(), difftime() Date and time manipulation

Key Points:

 Library functions save time and reduce errors since they are well-tested and optimized.
 To use a library function, you must include its header file using #include.
 They are part of the C Standard Library.

Example with string.h:

#include <stdio.h>

#include <string.h>

int main() {

char str1[] = "Hello";

char str2[] = "World";

strcat(str1, str2); // Concatenates str2 to str1


printf("Concatenated String: %s", str1);

return 0;

Output:

Concatenated String: HelloWorld

User-Defined Function in C Programming

A user-defined function in C is a function created by the programmer to perform a specific task.


It allows the program to be modular, organized, and reusable.

Definition:

A user-defined function is a function that is defined by the user (programmer) to perform a particular
operation that is not already provided by the C library.

Syntax:

return_type function_name(parameter_list)

// Function body

// Statements

return value; // optional

Example:

#include <stdio.h>

// Function Declaration

int add(int a, int b);

int main() {

int sum;
sum = add(10, 20); // Function Call

printf("Sum = %d", sum);

return 0;

// Function Definition

int add(int a, int b) {

return a + b;

Output:

Sum = 30

Explanation:

1. Function Declaration (Prototype):


Informs the compiler about the function name, return type, and parameters.
Example: int add(int, int);
2. Function Definition:
Contains the actual code or logic of the function.
Example:

int add(int a, int b) {

return a + b;

3. Function Call:
Used to execute the function from the main() or another function.
Example: sum = add(10, 20);

Advantages of User-Defined Functions:

 Increases code reusability


 Makes code modular and easy to debug
 Enhances readability and maintainability
 Reduces code duplication

Need for User-Defined Functions in C


User-defined functions are functions created by the programmer to perform specific tasks. They help in
making programs more modular, readable, and reusable.

Here are the main reasons (needs) for using user-defined functions:

1. Modularity
o Functions divide a large program into smaller, manageable parts or modules.
o Each function performs a specific task, making the program easier to understand and
debug.
2. Reusability
o Once a function is written, it can be used (called) multiple times in the same program or
even in other programs.
o This avoids rewriting the same code again and again.
3. Code Clarity and Readability
o Functions make programs cleaner and easier to read.
o Instead of writing large blocks of code, you can just call the function with its name.
4. Ease of Maintenance
o When a change is needed, you only modify the function definition, not every place where
the code is used.
5. Debugging and Testing
o Errors can be located and fixed easily since each function can be tested individually.
6. Team Collaboration
o In large projects, multiple programmers can work on different functions simultaneously,
improving productivity.

Example:

#include <stdio.h>

void greet()

{ // User-defined function

printf("Hello! Welcome to C programming.\n");

int main() {

greet(); // Function call

greet(); // Reuse the same function

return 0;

}
Output:
Hello! Welcome to C programming.
Hello! Welcome to C programming.

In programming, a variable is a named storage location in memory that is used to store data.

🔹 Definition:

A variable is a symbolic name given to a memory location where data can be stored, modified, and
retrieved during program execution.

Example (in C):

int age = 25;

Here:

 int → data type (integer)


 age → variable name
 25 → value stored in the variable

Key Points:

 The value of a variable can change during program execution.


 Each variable has:
1. Name (identifier)
2. Type (e.g., int, float, char)
3. Value (data it holds)
4. Memory location

Example:

float temperature = 36.5;

char grade = 'A';

Define variables and its types in C programming

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

🔹 Definition:

A variable is a symbolic name given to a memory location where a program can store, modify, and
retrieve a value.

🔹 Syntax:

data_type variable_name;
or

data_type variable_name = value;

Example:

int age = 25;

float salary = 30000.50;

char grade = 'A';

Types of Variables in C

Variables in C can be classified in two main ways:

1. Based on Data Type

These determine what kind of data the variable can store.

Types of Variables in C

Variables in C can be classified in two main ways:

1. Based on Data Type

These determine what kind of data the variable can store.

Data Type Example Description


Int int a = 10; Stores integers (whole numbers).
Float float b = 5.5; Stores decimal (floating-point) numbers.
Char char c = 'A'; Stores single characters.
Double double d = 15.9876; Stores large decimal numbers with higher precision.
Void — Represents no value (used in functions).

2. Based on Scope and Lifetime


Type Description Example
Declared inside a function or block; accessible only int x = 10; (inside a
Local Variable
within it. function)
Declared outside all functions; accessible throughout int count = 0; (before
Global Variable
the program. main())
Static Variable Retains its value even after the function ends. static int num = 0;
Automatic Default for local variables; created and destroyed auto int y = 5;
Variable automatically.
Declared using extern to use a global variable from
External Variable extern int total;
another file.

Example Program:
#include <stdio.h>

int globalVar = 100; // Global variable

void demo() {

static int count = 0; // Static variable

count++;

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

int main() {

int localVar = 10; // Local variable

printf("Local Variable = %d\n", localVar);

printf("Global Variable = %d\n", globalVar);

demo();

demo();

return 0;

Output:

Local Variable = 10

Global Variable = 100

Count = 1

Count = 2

Function Declaration in c programming

A function declaration in C (also called a function prototype) tells the compiler about the function
name, return type, and parameters before the function is actually defined or used in the program.
Syntax:
return_type function_name(parameter_list);
Example:
int add(int a, int b);

Explanation:

 int → return type (the function returns an integer)


 add → function name
 (int a, int b) → parameters with their data types

💡 Purpose of Function Declaration:

1. Informs the compiler about the function before its use.


2. Enables type checking of arguments and return value.
3. Allows functions to be defined later in the program or in another file.
Example Program:
#include <stdio.h>

// Function declaration
int add(int, int);

int main() {
int result = add(10, 20); // Function call
printf("Sum = %d", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Output:
Sum = 30

Function Definition, Calling Function Parameters and Return Types, Call by Value and Call by Reference
Programming in C

Function Definition, Calling Function, Parameters and Return Types, Call by Value, and Call by
Reference in C programming — with examples 👇

🧩 1. Function Definition in C

A function definition specifies what a function does.


It contains the function name, return type, parameters, and body (the block of statements).

Syntax:
return_type function_name(parameter_list) {
// body of the function
// statements
return value; // optional
}
Example:
int add(int a, int b) { // Function definition
int sum = a + b;
return sum;
}

2. Calling a Function

A function call is used to execute the defined function.


You call a function by writing its name followed by parentheses containing any arguments.

Example:
#include <stdio.h>
int add(int a, int b); // Function declaration (prototype)
int main()
{
int result;
result = add(10, 20); // Function call
printf("Sum = %d", result);
return 0;
}

int add(int a, int b) { // Function definition


return a + b;
}

3. Function Parameters and Return Types

a) Return Type

 Specifies the type of value a function returns to the calling function.

 Examples: int, float, char, or void (if it returns nothing).

b) Parameters (Arguments)

 Values passed to a function to perform operations.

Example:
float multiply(float x, float y) {
return x * y;
}

int main() {
float result = multiply(2.5, 4.0);
printf("Product = %.2f", result);
return 0;
}
4. Call by Value

In Call by Value, a copy of the actual parameter is passed to the function.


Changes made inside the function do not affect the original variable.

Example:
#include <stdio.h>

void swap(int x, int y) {


int temp = x;
x = y;
y = temp;
printf("Inside swap: x = %d, y = %d\n", x, y);
}

int main() {
int a = 5, b = 10;
swap(a, b);
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Output:
Inside swap: x = 10, y = 5
After swap: a = 5, b = 10

5. Call by Reference

In Call by Reference, the address of the variable is passed.


Changes made inside the function affect the original values.

Example:
#include <stdio.h>
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}

int main() {
int a = 5, b = 10;
swap(&a, &b);
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Output:
After swap: a = 10, b = 5
Summary Table
Concept Description Example Keyword
Function Definition Specifies what the function does int add(int a, int b)
Function Call Executes the function add(10, 20);
Parameters Inputs to the function (int a, int b)
Concept Description Example Keyword
Return Type Type of value returned int, float, void
Call by Value Copies values (no change in original) swap(a, b)
Call by Reference Passes address (changes original) swap(&a, &b)

Recursive Functions, Scope and life time of Variables, header files and Modular Programming in C

1. Recursive Functions in C

A recursive function is a function that calls itself directly or indirectly to solve a problem.
It is mainly used for problems that can be broken down into smaller, similar sub-problems (like factorial,
Fibonacci, etc.).
Syntax:
return_type function_name(parameters)
{
if (base_condition)
return value; // stopping condition
else
return function_name(modified_parameters); // recursive call
}
Example:
#include <stdio.h>
int factorial(int n)
{
if (n == 0)
return 1; // base case
else
return n * factorial(n - 1); // recursive call
}

int main() {
printf("Factorial of 5 = %d", factorial(5));
return 0;
}

Explanation:
 factorial(5) calls factorial(4), and so on until factorial(0) is reached.
 The results return back up the chain, multiplying each number.

2. Scope and Lifetime of Variables in C

Storage Class
Type Scope Lifetime
Keyword
Local Created when the function is
Within a function/block auto (default)
Variable called and destroyed when it ends
Global
Available throughout the program Exists until program ends no keyword
Variable
Storage Class
Type Scope Lifetime
Keyword
Static Local to the function, but retains its
Till the program ends static
Variable value between function calls
External Declared in another file and used in
Till program ends extern
Variable current file

Example:
#include <stdio.h>
int globalVar = 10; // Global variable
void display() {
static int count = 0; // Static variable
count++;
printf("Count = %d\n", count);
}
int main() {
int localVar = 5; // Local variable
for (int i = 0; i < 3; i++)
display();
printf("Global Variable = %d", globalVar);
return 0;
}
Output:
Count = 1
Count = 2
Count = 3
Global Variable = 10

3. Header Files in C

A header file contains function declarations, macros, and definitions that can be reused across multiple
source files.
They usually have the extension .h.
Types:
1. Standard header files: Provided by C library
o Examples: stdio.h, stdlib.h, math.h, string.h
2. User-defined header files: Created by the programmer
o Example: myheader.h
Example:

// myheader.h
void greet();

// main.c
#include <stdio.h>
#include "myheader.h"
void greet() {
printf("Hello from header file!\n");
}

int main() {
greet();
return 0;
}

4. Modular Programming in C

Modular programming means dividing a program into independent modules (functions or files), each
performing a specific task.
It improves readability, reusability, debugging, and maintenance.
Example Structure:
File 1: math_utils.c

int add(int a, int b) {


return a + b;
}
File 2: math_utils.h
int add(int a, int b);

You might also like