PPS - Chapter 2
PPS - Chapter 2
UNIT – II
Topics
Overview of C: Input/output:
• Unformatted & formatted I/O function in C.
• Elements of C
• Data types
• Storage classes in C Control statements:
• Operators: • if statement
• Arithmetic • switch statement
• Relational
• Logical • Repetition:
• Bitwise • For
• Unary, assignment • While
• Conditional operators • do-while loop;
• Efficiency
• Portability
• Speed
• Powerful
Why C?
• Efficiency:
• C programs tend to be compact (Compact refers to
something that is small, concise, and efficiently
Organized) and to run quickly.
• In C programming, compact means that C programs are written in a way that minimizes
unnecessary code. They don’t contain unnecessary content.
• Programmers plan to express functionality using the fewest lines of code possible.
Why C?
• Portable:
• C programs written on one system can be run on
other systems with little or no modification.
• Powerful:
•C is powerful and flexible. For example, most of the powerful,
flexible UNIX operating system is written in C. Many compilers
and interpreters for other languages such as FORTRAN, APL,
Pascal, LISP, Logo, and BASIC have been written in C.
Why C?
• Speed
• C is known for its speed. What does that mean?
• Minimal Overhead:
• C doesn’t introduce unnecessary processing overhead.
• Unlike languages with automatic garbage collection, C doesn’t spend time
managing memory.
• This lack of overhead allows C programs to execute fastly .
•Close to Hardware:
•C provides low-level access to memory and system resources.
•Programmers have the ability to work directly with memory addresses.
•Instead of relying solely on high-level abstractions, programmers can access specific memory locations.
Where C is used?
• C is the backbone of many operating systems, including Windows,
Linux, iOS, Android, and macOS.
• The keywords cannot be used as variable names because if we do so, we are trying
to assign a new meaning to the keyword, which is not allowed.
Variable and Constant
• A variable is an entity that may change during the execution of the program
whereas a constant is an entity that doesn’t change.
• Consider the memory locations shown in Figure 1.3. Here 3 is stored in a memory location and a
name x is given to it. Then we have assigned a new value 5 to the same memory location x. This
would overwrite the earlier value 3, since a memory location can hold only one value at a time.
• In the above image, x is known as a variable (or a variable name). As against this, 3 or 5 do not
change, hence are known as constants.
• In programming languages, constants are often called literals, whereas, variables are called
identifiers.
Constant
• A constant is a number, character, or character string that can be used as a value in
a program.
Identifier
• Identifiers refer to the names we give to entities such as variables, functions,
structs, and arrays to distinguish them in our code.
• Here, 'score' is an identifier that we've used to name our integer variable.
Rules for Naming Identifiers
• There are certain rules and conventions while naming these identifiers. Let see
them:
• The first rule while naming an identifier is that it must start with either a letter (lowercase or
uppercase) or an underscore. The subsequent characters can be a mix of letters (a-z or A-Z), digits
(0-9), or underscores (_). Identifiers must only contain alphanumeric characters.
• Example:
• These identifiers adhere to the rules and will be accepted by the C compiler.
Rules for Naming Identifiers
• Example:
• While the ANSI C standard does not impose a specific limit on the length of identifiers, some
older compilers may have had limitations.
• Modern compilers generally support longer identifiers, and the actual maximum length can vary
depending on the compiler and implementation.
• It is recommended to choose meaningful and concise identifiers without excessive length,
following good coding practices.
• Example:
• Identifiers are case-sensitive, meaning the same sequence of characters but with a different case is
treated as a different identifier. Therefore, 'score' and 'Score' are two distinct identifiers in C.
• Example:
int score = 10;
int Score = 20;
Printf("%d %d", score, Score); // Outputs "10 20“
• As demonstrated, 'score' and 'Score' are treated as two different variables holding separate
values.
Rules for Naming Identifiers
Reserved Keywords in Identifiers
• C language reserves certain words, known as keywords, for its syntax. These keywords carry
special meanings for the compiler and, therefore, cannot be used as identifiers. Attempting to use
such words as identifiers will result in a compilation error. Reserved keywords include int, char,
for, while, if, etc.
• Example:
int for = 10; // Invalid identifier: 'for' is a reserved keyword
Rules for Naming Identifiers
Naming Conventions for Identifiers
• While the rules for naming identifiers form the necessary foundation, naming conventions take a
step further into the realm of good practices. Adhering to these conventions is widely regarded as a
hallmark of high-quality, maintainable code.
• Descriptive Names: Identifiers should accurately reflect the purpose of the variable, function, or
other entity they're naming. For example, if a variable holds the age of a person, 'age' would be a
more descriptive identifier than a vague name like 'a' or 'x’.
• Use of Underscores: Underscores can be used to separate words in an identifier, making it more
readable.
• Case Sensitivity: Since C is case-sensitive, it's important to be consistent with the case you use for
an identifier. It's easy to forget the case and inadvertently create or reference the wrong variable.
• Avoid Abbreviations: : Where possible, avoid abbreviations or make sure they're explained clearly
in the comments.
• Along with not using spaces or other non-alpha numeric characters (except the underscore), do
not use built-in function as variable names, either. The following are invalid variable names:
Operators
• Operators: Operators are specific symbols that enable you to manipulate and compute data in the
C programming language.
• Arithmetic Operators: These operators are mainly used to perform mathematical calculations on numerical
data types in C.
• Addition Operator - Operators that add two operands and return their sum are referred to as addition operators.
Example, int sum = num1 + num2;
• Subtraction Operator - Operators that subtract the second operand from the first operand and return the difference
are known as subtraction operators. Example, int difference = num1 - num2;
• Multiplication Operator - They multiply two operands and generate the final product.
Example: int product = num1 * num2;
• Division Operator - They divide the first operand by the second operand and return the quotient.
Example, int quotient = num1 / num2;
• Modulus Operator - They divide the first operand by the second operand and return the remainder.
Example, int remainder = num1 % num2;
• Increment Operator - Operators that increase the value of an operand by one are referred to as increment operators.
For example, num++;
• Decrement Operator - Operators that decrease the value of an operand by two are known as decrement operators.
Example, num--;
Operators - Relational Operators
• Relational operators in C are primarily used to compare values and determine the relationships between operands. After
evaluating the conditions thoroughly, they generate a result that can either be true or false. Overall, relational operators play
a very crucial role in the decision-making process and comparing operations in C.
• Equality Operator - They check whether the operands are equal. For example, if (num1 == num2).
• Inequality Operator - They check if the operands are unequal. For example, if (num1 != num2).
• Greater Than Operator - Operators that check if the left operand is greater than the right are referred to as greater than
operators. For example, if (num1 > num2).
• Less Than Operator - These refer to those operators that check if the left operand is less than the right operand. For
example, if (num1 < num2).
• Greater Than Or Equal To Operator - They determine if the left operand is greater than or equal to the right operand. For
example, if (num1 >= num2).
• Less Than Or Equal To Operator - They check if the left operand is less than or equal to the right operand. For example,
if (num1 <= num2).
Operators - Logical Operators
• Logical operators in C enable you to combine multiple conditions and then determine the overall truth value of the
combined expression.
• Logical AND Operator- If both the left and right operands are true, it returns true. In any other case, it shall return false.
Example, if (condition1 && condition2).
• Logical OR Operator- When both or any one of two operands is true, it returns true.
For example, if (condition1 || condition2)
• Logical NOT Operator- It reverses the truth value of the operand, meaning if the operand is true, it returns false, and vice
versa.
For example, if (!condition).
• Point: One interesting fact about logical operators is that you can use these alongside relational operators to generate more
complex decision-making statements.
Operators - Logical Operators Use of && operator
Use of ! operator
Operators - Assignment Operators
• The main responsibility of assignment operators in C is to assign values to variables. They do so by performing operations with
arithmetic operators or bitwise operators and then assigning the result to the variables. Let's take a look at some of the most common
types of assigned operators in C.
• Simple Assignment Operator- The value on the right-hand side (p) is assigned to the variable on the left-hand side (q). For example,
p=q
• Addition Assignment Operator- The value on the right-hand side of the variable is added to the left-hand side, and the result is
assigned to the variable. For example, p + = q.
• Subtraction Assignment Operator- The value on the right-hand side is subtracted from the variable on the left-hand side, and the
result is assigned to the variable. For example, p - = q.
• Multiplication Assignment Operator- The product generated after multiplying the left-hand side of the variable by the right-hand
side is equal to p. For example, p *= q
• Division Assignment Operator- The value of the left-hand side variable is divided by the right-hand side, and the result is returned
to the variable. For example, p / = q.
• Modulus Assignment Operator- The remainder, after dividing p by q, is equal to p. For example, p % = q.
Operators - Logical Operators Use of *+ operator
Operators - Bitwise Operators
• Bitwise operators in C refer to those operators that help to manipulate the individual bits of a binary number. There are
primarily six bitwise operators used. They are, namely,
• Bitwise AND Operator (&)- It takes two numbers as operands and performs a Bitwise AND operation on them. If both the bits are
1, then the result generated will be 1; if not, then the result will be 0.
• Bitwise OR Operator ( | ) - It performs OR operation on the corresponding bits of two operands. Even if one of the bits is 1, it will
generate a result of 1, and if not, then the result will be 0.
• Bitwise NOT Operator - It performs a bitwise complement, also referred to as NOT operation, on a single operand, inverting each
bit. The 0s are flipped to 1s, and the 1s to 0s.
• Bitwise XOR Operator - It performs bitwise exclusive OR operation on each bit of two numbers. Even if both the bits are
different, it will generate a result of 1.
• Left Shift Operator - It takes two numbers as operands; the left shifts the bit to the left by a certain number of positions as
specified by the second operand.
• Right Shift Operator - It shifts the bits of the left operand to the right by a specified number of positions. If they are signed
numbers, then the sign bits are replicated. If not, then zeros are used to fill in the left.
Operators - Logical Operators Use of Bitwise &
Bitwise AND Operator (&)- It takes two numbers as operands and performs a Bitwise AND operation on
them. If both the bits are 1, then the result generated will be 1; if not, then the result will be 0
Operators - Logical Operators Use of Bitwise |
Bitwise NOT Operator - It performs a bitwise complement, also referred to as NOT operation,
on a single operand, inverting each bit. The 0s are flipped to 1s, and the 1s to 0s.
Operators - Logical Operators Use of Bitwise ^
Bitwise XOR Operator - It performs bitwise exclusive OR operation on each bit of two
numbers. Even if both the bits are different, it will generate a result of 1.
Operators - Logical Operators Use of Bitwise ^
Left Shift Operator - It takes two numbers as operands; shifts the bits to the left by a certain
number of positions as specified by the second operand.
Operators - Logical Operators Use of Bitwise ^
•Right Shift Operator - It shifts the bits of the left operand to the right by a specified number of
positions.
Algorithm
• Planning is very important in every walk of life. Even for our routine kind of things, we have to plan.
Such a plan of doing things is also as process. For example, we have to plan our monthly budget
otherwise things can go astray and we may not enough money left in our pocket towards the end of the
month.
• Planning should not be in the mind only (adhoc process), you must write it down, i.e., you must
document it (defined process). The results of adhoc process are not guaranteed where as the results of
defined process are guaranteed and predictable.
• Likewise, if you know the steps to be followed for solving a given problem but you have not
documented them, you may forget to apply some of the steps or you may apply some of the steps in
wrong sequence. Obviously, you will get a wrong answer.
• Similarly, while writing a program, if the programmer leaves out some of the instructions or writes the
instructions in wrong sequence, the computer will give a wrong answer.
• The various tools collectively referred to as program design tools, that helps in planning the program are
algorithm, flowchart and pseudocode.
Algorithm
• Computer scientist niklaus Wirth stated that
Program = Algorithms + Data
• An algorithm is a part of the plan for the computer program. In fact, an algorithm
is ‘an effective procedure for solving a problem in a finite number of steps’.
• An algorithm is effective, which means that an answer is found and it has a finite
number of steps.
• Input: These are zero or more values which are externally supplied. An algorithm has zero or more inputs:
quantities that are given to it initially before the algorithm begins, or dynamically as the algorithm runs. T
• Definiteness: Each step must be clear and unambiguous, i.e., having one and only one meaning.
• Finiteness: If we trace the steps of an algorithm, then for all cases, the algorithm must terminate after a finite
number of steps.
• Effectiveness: Each step must be sufficiently basic that it can in principle be carried out by a person using
only paper and pencil. In addition, not only each step is definite, it must also be feasible.
Algorithm
• Effectiveness: An algorithm is also generally expected to be effective, in the sense that its operations must
all be sufficiently basic that they can in principle be done exactly and in a finite length of time by someone
using pencil and paper.
• Effective operation:
• Algorithm E uses only the operations of dividing one positive integer by another, testing if an integer is zero,
and setting the value of one variable equal to the value of another. These operations are effective, because
integers can be represented on paper in a finite manner, and because there is at least one method (the
“division algorithm”) for dividing one by another.
• Ineffective operation:
• The same operations would not be effective if the values involved were arbitrary real numbers specified by an
infinite decimal expansion,
Algorithm
• The following is an algorithm for making a cup of tea.
1. Put the teabag in a cup.
2. Fill the kettle with water.
3. Boil the water in the kettle.
4. Pour some of the boiled water into the cup.
5. Add milk to the cup.
6. Add sugar to the cup.
7. Stir the tea.
8. Drink the tea.
• As you can see, there are certain steps that must be followed. These steps are in a specific order, even though
some of the steps could be rearranged. For example, steps 5 and 6 can be reversed.
• You could add the sugar first, and the milk afterwards.
• Please keep in mind that the order of some steps can probably be changed but you can't move them far away
from where they should be. For example, you can't move step 3 ("Boil the water in the kettle.") to the end of
the algorithm, because you will end up drinking a cup of iced tea (and not a warm one) which is totally
different from the initial goal.
Algorithm
• Here is an example of an algorithm, for making a pot of tea.
1. If the kettle does not contain water, then fill the kettle.
2. Plug the kettle into the power point and switch it on.
3. If the teapot is not empty, then empty the teapot.
4. place tea leaves in the teapot.
5. If the water in the kettle is not boiling, then go to step 5.
6. Switch off the kettle.
7. pour water from the kettle into the teapot.