Cprogram Yash
Cprogram Yash
----------------------------------------------PART-II--------------------------------------------------
UNIT - I
Introduction to Computers – Computer Systems, Computing Environments, Computer
Languages,Creating and running programs, Software Development.
Computer Systems:
A computer system consists of hardware and software components that work
together to perform tasks. In the context of C Programming and Data Structures,
understanding the computer system is crucial for efficient programming and
memory management.
Hardware: The physical parts of the computer system (e.g., CPU, memory,
input/output devices).
Software: The programs and applications that run on the computer (e.g.,
operating systems, compilers, application software).
Computing Environments:
The first step in creating a program is to write the source code. This is the set of
instructions that tell the computer what to do.
Steps:
Example (Python):
print("Hello, World!")
After writing the code, save the file with the correct file extension corresponding
to the language you're using.
If you are using a compiled language (e.g., C, C++, Java), you will need to
compile the source code into machine code before it can be executed. Compilation
translates human-readable code into an executable file that can be run by the
operating system.
Steps:
For interpreted languages (e.g., Python, JavaScript), the code is not compiled into
an executable first. Instead, an interpreter reads and executes the code directly.
Python: You don't need to compile the code. Just use the python command
to run it:
python filename.py
Once your program is compiled or interpreted, you can run it to see the results.
Steps:
If the program does not behave as expected, you’ll need to debug it. Common
errors might include syntax errors, logical errors, or runtime errors.
Debugging Tools:
Print Statements: Use print() (or similar) to trace variable values or the
flow of execution.
Debugger: Most IDEs come with a built-in debugger that allows you to step
through code, inspect variables, and set breakpoints.
Error Messages: Read the error message carefully; they often indicate the
source of the problem (e.g., syntax error, file not found).
Once the program is running, you may want to optimize it for performance or
readability.
Optimization Tips:
If you plan to distribute the program to others or deploy it to production, you may
need to package it:
Summary of Steps
This is a general process, and specific steps may vary depending on the programming language,
tools, and development environment you are using.
Here’s a flowchart representation of the process for creating and running a program:
Test in Different
Test on Platforms
Package/Deploy
Software Development:
In today's fast-paced digital world, software development is a critical driver of
innovation and business success. From small startups to large enterprises, software
systems are at the heart of nearly every business operation, providing functionality,
efficiency, and scalability.
----------------------------------------------PART-II--------------------------------------------------
Introduction to C Language – Background, Simple C programs, Identifiers, Basic data
types,Variables, Constants, Input / Output
Background of C Language
The C programming language was created in the early 1970s by Dennis Ritchie
at Bell Labs, as part of the development of the Unix operating system. Before C,
the Unix system was written in assembly language, which made it difficult to
maintain and modify. Ritchie and his colleague Brian Kernighan wanted a
language that could combine the efficiency of assembly with the simplicity and
readability of higher-level languages.
C was designed to be a portable, system-level language, allowing Unix to run on
different hardware platforms. It was inspired by earlier languages like BCPL and
B (which was also developed at Bell Labs by Ken Thompson), but C offered
improved features such as structured programming, data abstraction, and low-level
memory access.
In 1978, Kernighan and Ritchie published the influential book "The C
Programming Language", which popularized the language and set the foundation
for its widespread adoption. Over time, C became a standard for system
programming and has influenced the development of many other languages,
including C++, Java, C#, and Objective-C.
C's portability and efficiency remain central to its enduring relevance, especially
in contexts like operating systems, embedded systems, hardware drivers, and
compilers.
Simple C programs:
IDENTIFIERS :
What is an Identifier?
An identifier is a name given to a program element. It helps in identifying a
variable, function, or other components in the program. For example, in the code
int age = 25;, age is an identifier representing a variable.
Examples of Identifiers:
1. Variables:
int age = 25; // 'age' is an identifier representing an integer variable
float salary = 50000.50; // 'salary' is an identifier representing a floating-point
variable
2. Functions:
void displayMessage() { // 'displayMessage' is an identifier for a function
printf("Hello, World!\n");
}
3. Arrays:
int numbers[10]; // 'numbers' is an identifier for an array of integers
4. Structures:
struct Person { // 'Person' is an identifier for a structure
char name[50];
int age;
};
Conclusion:
In C programming, identifiers are the building blocks for naming variables,
functions, and other program components. Following the rules for naming
identifiers ensures that your code is error-free, readable, and maintainable.
Using descriptive names and adhering to common conventions like CamelCase
and uppercase constants can make your code much clearer for others (and
yourself) to understand.
By carefully choosing your identifiers, you can avoid errors, improve readability,
and ensure that your C programs are well-structured and easy to debug.
Data Types
In C programming, data types are used to define the type of data that a variable
can hold. Understanding data types is fundamental because they define how much
memory is allocated for a variable and what kind of operations can be performed
on it. C provides several built-in or basic data types that are used to represent
different types of data.
Conclusion:
In C programming, choosing the appropriate data type is essential for efficient
memory use and performance. By selecting the right data type (such as int for
whole numbers, float for decimal numbers, or char for characters), you ensure that
your program runs effectively and uses memory appropriately. C’s basic data types
allow you to handle a wide variety of tasks, from simple calculations to complex
systems programming.
Types of Operators in C
Operators in C are classified into the following categories:
1. Arithmetic Operators
2. Relational (Comparison) Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and Decrement Operators
7. Conditional (Ternary) Operator
8. Special Operators (Sizeof, Comma, Pointer Operators)
1. Arithmetic Operators
These operators perform basic mathematical operations.
Operator Operation Example
+ Addition a + b (sum of a and b)
- Subtraction a - b (difference between a and b)
* Multiplication a * b (product of a and b)
/ Division a / b (quotient of a and b)
% Modulus (Remainder) a % b (remainder of a divided by b)
Example:
int a = 10, b = 5;
int sum = a + b; // sum = 15
int product = a * b; // product = 50
3. Logical Operators
Logical operators are used to perform logical operations, often in conditional
expressions (like if statements).
Operator Operation Example
&& Logical AND a && b (True if both a and b are true)
` `
! Logical NOT !a (True if a is false)
Example:
int a = 1, b = 0;
int result = (a && b); // result = 0 (False)
4. Bitwise Operators
Bitwise operators perform bit-level operations. These operators are used to
manipulate individual bits of variables.
Operator Operation Example
& Bitwise AND a&b
` ` Bitwise OR
^ Bitwise XOR a^b
~ Bitwise NOT (Complement) ~a
<< Left Shift a << n (shift a left by n positions)
>> Right Shift a >> n (shift a right by n positions)
Example:
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a & b; // result = 1 (0001 in binary)
5. Assignment Operators
Assignment operators are used to assign values to variables.
Operator Operation Example
= Simple assignment a = 5
+= Add and assign a += 5 (equivalent to a = a + 5)
-= Subtract and assign a -= 5 (equivalent to a = a - 5)
*= Multiply and assign a *= 5 (equivalent to a = a * 5)
Operator Operation Example
/= Divide and assign a /= 5 (equivalent to a = a / 5)
%= Modulus and assign a %= 5 (equivalent to a = a % 5)
Example:
int a = 10;
a += 5; // a = a + 5 -> a = 15
8. Special Operators
These are a few additional operators that are commonly used in C.
sizeof: Used to get the size of a data type or variable in bytes.
Example:
int a = 10;
printf("Size of a: %zu bytes", sizeof(a)); // Output: Size of a: 4 bytes (on
most systems)
Comma Operator: Allows multiple expressions to be evaluated in a single
statement.
Example:
int a = 5, b = 10;
int result = (a = a + 5, b = b - 2); // Evaluates both expressions, result = b =
8
Pointer Operators:
o &: Address-of operator, used to get the memory address of a variable.
o *: Dereference operator, used to access the value at a given address
(pointer).
Example:
int a = 5;
int *ptr = &a; // ptr holds the address of a
printf("Value at ptr: %d", *ptr); // Output: 5
Conclusion
Operators are one of the core components in C programming. They allow you to
perform mathematical, logical, relational, and bitwise operations. By
understanding the different types of operators and how to use them, you can
manipulate data effectively and write powerful, efficient C programs.
Variables:
Variables in C: Short Note
In C programming, variables are used to store data that can be manipulated during
the execution of a program. A variable is essentially a container that holds data
values. The value of a variable can change throughout the execution of the
program, which is why they are called "variables."
Definition of a Variable:
A variable in C is a symbolic name for a memory location that stores data. Each
variable has a data type that determines the kind of data it can hold, such as
integers, floating-point numbers, or characters.
Variable Initialization:
A variable can be initialized at the time of declaration, meaning it is assigned a
value when it is declared.
Example:
int age = 25; // Declares and initializes 'age' with the value 25
float salary = 50000.5; // Declares and initializes 'salary' with the value 50000.5
If a variable is not initialized, it may contain a garbage value (an unknown value),
which can lead to unpredictable behavior.
Types of Variables in C:
1. Local Variables:
o Defined inside a function or block.
o They can only be accessed within that function/block.
o They are created when the function is called and destroyed when the
function exits.
2. Global Variables:
o Defined outside all functions, usually at the top of the program.
o They can be accessed from any function within the same program.
o Global variables have a program-wide scope.
3. Static Variables:
o Defined with the static keyword, and they retain their value between
function calls.
o They are only initialized once and preserve their value for the duration
of the program.
4. External Variables:
o Defined in another file and linked to the current program using the
extern keyword.
int main() {
int age = 30; // Local variable in main
float salary = 45000.50;
return 0;
}
Output:
Age: 30
Salary: 45000.50
Local Variable: 50
Static Variable: 10
Local Variable: 50
Static Variable: 11
Conclusion:
Variables in C are essential to store and manipulate data in a program. By
understanding how to declare, initialize, and use variables correctly, you can write
programs that are efficient, organized, and easy to understand. Always choose
descriptive variable names and be mindful of the scope and lifetime of your
variables to avoid errors and improve code clarity.
Constants:
Constants in C: Short Note
In C programming, a constant is a value that cannot be modified during the
execution of the program. Once a constant is assigned a value, it remains
unchanged throughout the program. Constants are used when we need to refer to a
fixed value multiple times without the risk of accidentally altering it.
Types of Constants in C:
1. Integer Constants
2. Floating-Point Constants
3. Character Constants
4. String Constants
5. Enumerated Constants
6. Symbolic Constants (using #define or const)
1. Integer Constants
An integer constant is a whole number, either positive or negative, without any
decimal point.
Example:
int a = 10; // 10 is an integer constant
Types:
Decimal: 10, 255
Octal: 075, 012 (prefixed with 0)
Hexadecimal: 0x1A, 0xFF (prefixed with 0x)
2. Floating-Point Constants
A floating-point constant represents numbers with decimal points.
Example:
float pi = 3.14159; // 3.14159 is a floating-point constant
Floating-point constants can be written in scientific notation:
Example:
float e = 1.23e4; // Equivalent to 1.23 * 10^4
3. Character Constants
A character constant is a single character enclosed in single quotes.
Example:
char ch = 'A'; // 'A' is a character constant
Note: Character constants are treated as integers in C, where the character is stored
as its corresponding ASCII value.
4. String Constants
A string constant is a sequence of characters enclosed in double quotes.
Example:
char str[] = "Hello, World!"; // "Hello, World!" is a string constant
5. Enumerated Constants
Enumerated constants are defined using the enum keyword. They are useful for
defining a set of named integer constants.
Example:
enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday };
By default, the first constant (Sunday) is assigned the value 0, and the others are
incremented by 1 (Monday = 1, Tuesday = 2, etc.).
int main() {
int age = 25;
printf("Value of PI: %.5f\n", PI);
printf("Max allowed age: %d\n", MAX_AGE);
return 0;
}
Output:
Value of PI: 3.14159
Max allowed age: 100
Conclusion:
Constants are an essential feature of C programming, providing a way to store
values that cannot be changed. They improve the readability, maintainability, and
reliability of code by allowing fixed values to be used consistently throughout the
program without the risk of accidental modification. Constants can be defined
using literals (integer, floating-point, character), symbolic constants (via #define or
const), or enumerated types, depending on the use case.
Input/Output :
In C programming, Input/Output (I/O) refers to the process of reading data from
the user or a file (input) and displaying data to the user or writing data to a file
(output). C provides standard functions and libraries to handle I/O operations.
int main() {
int num = 10;
float pi = 3.14;
char grade = 'A';
return 0;
}
Output:
Number: 10
Pi value: 3.14
Grade: A
int main() {
int age;
float salary;
char name[30];
return 0;
}
Example Output:
Enter your age: 25
Enter your salary: 55000.50
Enter your name: John
Age: 25
Salary: 55000.50
Name: John
Format Specifiers in C
For both printf() and scanf(), format specifiers are used to indicate the type of data
being input or output.
Specifier Data Type Example
%d Integer scanf("%d", &num)
%f Float scanf("%f", &num)
%c Character scanf("%c", &ch)
%s String scanf("%s", str)
%lf Double (long float) scanf("%lf", &num)
%x Hexadecimal Integer scanf("%x", &num)
Important Notes:
1. scanf() and Buffer Issues:
o scanf() can sometimes behave unpredictably when reading strings or
characters after reading numeric values, because it leaves newline
characters in the input buffer. To avoid this, use getchar() or getch() to
consume the newline if necessary.
o To handle strings with spaces, use fgets() instead of scanf().
2. Input Validation:
o Always validate the input received via scanf(). If the input is not of
the expected type, it can lead to unexpected behavior.
Example:
if(scanf("%d", &num) != 1) {
printf("Invalid input!\n");
}
Conclusion:
Input and output operations are crucial in C programming for interacting with users
and processing data. Functions like printf() and scanf() are used to output and input
data, respectively, while format specifiers help control the data types. It’s essential
to handle user input carefully, especially when working with functions like scanf()
and gets(), to avoid errors and security vulnerabilities like buffer overflows.
Always validate and sanitize input for better program robustness.