0% found this document useful (0 votes)
27 views

Full Unit 1 Notes

Uploaded by

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

Full Unit 1 Notes

Uploaded by

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

lOMoARcPSD|46000405

FULL UNIT 1 NOTES

Programming For Problem Solving (SRM Institute of Science and Technology)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Abel (abelantony765@gmail.com)
lOMoARcPSD|46000405

SRM Institute of Science and Technology, SRM Institute of Science and Technology,
Chennai Chennai

21CSS101J –Programming for Problem Solving


Unit-I

Evolution of Programming Languages


Unit-I
Programming Language is considered as the set of commands and instructions that we give to the
Evolution of Programming & Languages - Problem solving through programming -
machines to perform a particular task. For example, if you give some set of instructions to add two numbers
Writing algorithms & Pseudo code - Single line and multiline comments - Introduction to
then the machine will do it for you and tell you the correct answer accordingly.
C: Structure of the C program - Input and output statements. Variables and identifiers, But a good programming language----
Constants, Keywords - Values, Names, Scope, Binding, Storage Classes - Numeric Data 1. Portability

types: integer, floating point Non-Numeric Data types: char and string - L value and R 2. Maintainability
3. Efficient
value in expression, Increment and decrement operator - Comma, Arrow and Assignment
4. Reliable
operator, Bitwise and Size-of operator - Arithmetic, Relational and logical Operators -
5. Machine Independence
Condition Operators, Operator Precedence - Expressions with pre / post increment operator 6. Cost Effectiveness
7. Flexible

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Evolution of Programming Languages Evolution of Programming Languages

In the global, we have about 500+ programming languages with having their own syntax and features. • Developed by Alick Glennie
1952 Autocode • It is the first compiled computer programming language
• Ex: FORTRAN, COBOL
In the early days, Charles Babbage had made the device, but he was confused about
how to give instructions to the machine, and then Ada Lovelace wrote the instructions • Developed by IBM
1883
for the analytical engine. 1957 FORTRAN • Numeric computation and scientific computing
• Software for NASA was written in FORTRAN
• It is a type of low-level language • ALGOrithmic language
• AL can be easily understandable by machine • It is the fundamental for C, C++ and Java
1949 Assembly
• It is also used to create computer viruses 1958 ALGOL
• The first PL to have a code block like “Begin” that indicates that your program has
Language
• Real time programs such as simulation of flight navigation system and medical started and “End” means you have ended your code
equipment.
• It stands for Common Business Oriented Language
1959 COBOL
• In 1997, 80% of the world business ran on COBOL

Evolution of Programming Languages Evolution of Programming Languages

▪ It is a general-purpose, procedural programming language and the most popular


programming language till now. • SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce. The
1972 SQL
▪ All the code that was previously written in assembly language gets replaced by the earlier name was SEQUEL (Structured English Query Language).
C language like operating system, kernel, and many other applications.
1972 C
▪ It can be used in implementing an operating system, embedded system, and also
on the website using the Common Gateway Interface (CGI). • It stands for MATrix LABoratory. It is used for matrix anipulation,
1978 MATLAB
▪ C is the mother of almost all higher-level programming languages like C#, D, Go, implementation of an algorithm, and creation of a user interface.
Java, JavaScript, Limbo, LPC, Perl, PHP, Python, and Unix’s C shell.
• C++ is the fastest high-level programming language. Earlier, Apple Inc uses
1983 C, C++ Objective-C to make applications.

• The language is very easy to understand. Famous language among data scientists
1991 Python
and analysts.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Evolution of Programming Languages Problem Solving through programming


What is problem solving?
• JAVA is everywhere. JAVA is the platform-independent language. Problem solving is the act of defining a problem; determining the cause of the problem; identifying,
• PHP is a scripting language mainly used in web programming for connecting prioritizing, and selecting alternatives for a solution; and implementing a solution.
databases.
1995 Java, PHP,
• JavaScript enables interactive web pages. JS is the most popular programming
Java Scipt
language. JS is famous for building a web application. It makes our page
interactive.

• C#(C-sharp) is mainly used for making games. Unity engine uses C# for making
2000 C#
amazing games for all platforms

Problem Solving through programming Problem Solving through programming


Stages of Problem solving #include <stdio.h>
1. Understand the problem int factorial(int);
2. Define the problem int main() {
3. Define boundaries int n, result;
4. Plan solution printf("Enter a non-negative number: ");
5. Check solution scanf("%d",&n);
result = factorial(n);
printf("The factorial of of %d is %d",n,result); To use divide and conquer algorithm
Divide and Conquer Approach return 0; recursion is used.
}
1. breaking the problem into smaller sub-problems int factorial(int n) {
2. solving the sub-problems, and if (n > 1) { Recursive
3. combining them to get the desired output. return n * factorial(n - 1); call
} else {
return 1;
}
}

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Problem Solving through programming Problem Solving through programming


Dynamic Programming Dynamic Programming
Dynamic programming is a technique that breaks the problems into sub-problems, and saves the result How can we calculate F(20)?
The F(20) term will be calculated using the nth formula of the Fibonacci series. The below figure
for future purposes so that we do not need to compute the result again. The main use of dynamic shows that how F(20) is calculated.
programming is to solve optimization problems. Here, optimization problems mean that when we are
trying to find out the minimum or the maximum solution of a problem.
Consider an example of the Fibonacci series. The following series is the Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ,…
F(n) = F(n-1) + F(n-2),
With the base values F(0) = 0, and F(1) = 1. To calculate the other numbers, we follow the above
relationship. For example, F(2) is the sum f(0) and f(1), which is equal to 1.

Problem Solving through programming Problem Solving through programming


Dynamic Programming
As we can observe in the above figure that F(20) is calculated as the sum of F(19) and F(18). In the
dynamic programming approach, we try to divide the problem into the similar sub problems. We are
following this approach in the above case where F(20) into the similar sub problems, i.e., F(19) and
F(18). If we recap the definition of dynamic programming that it says the similar sub problem should
not be computed more than once. Still, in the above case, the sub problem is calculated twice. In the
above example, F(18) is calculated two times; similarly, F(17) is also calculated twice. However, this
technique is quite useful as it solves the similar sub problems, but we need to be cautious while storing
the results because we are not particular about storing the result that we have computed once, then it
can lead to a wastage of resources.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Writing Algorithms and Pseudo Code Writing Algorithms and Pseudo Code
An algorithm is a set of steps designed to solve a problem or accomplish a task. Algorithms are usually Characteristics of a good algorithm
written in pseudocode, or a combination of your speaking language and one or more programming languages, 1: Input and output must be specified
in advance of writing a program. 2: All important steps must be mentioned
Step-1: Obtain detailed information on the problem. 3: Instructions must be perfectly ordered
Step-2: Analyze the Problem 4: Short and effective descriptions
Step-3: Think of a problem solving approach 5: The algorithm must contain finite number of steps
Step-4: Review the problem solving approach and try to think of a better alternative
Step-5: Develop a basic structure of the algorithm
Step-6: Optimize, improve and refine.

Writing Algorithms and Pseudo Code Writing Algorithms and Pseudo Code
Examples of Algorithm Examples of Algorithm
1. Addition of two numbers 2. Comparison of 3 numbers to find the largest number
1: Start
Step-1: Start 2: Declare variables num1, num2, and num3
Step-2: Declare variables num1, num2, and sum 3: Read values of num1 and num2 and num3
4: Compare num1, num2 and num3
Step-3: Read values of num1 and num2 5: If num1>num2 and num1>num3
Step-4:Add the values of num1 and num2 and assign the result Display num1 is the largest number
Else
Step-5: Display the sum If num2>num1 and num2>num3
Step-6: End Display num2 is the largest number
Else
Display num3 is the largest number
6: End

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Writing Pseudo Code Writing Pseudo Code


1. Always capitalize the initial word (often one of the main six constructs). Main Constructs of Pseudocode
Sequence: Sequentially completed linear tasks are represented by it.
2. Make only one statement per line.
WHILE: It is a loop that starts with a condition.
3. Indent to show hierarchy, improve readability, and show nested constructs.
REPEAT-UNTIL: A loop containing a condition present at the bottom called REPEAT-UNTIL.
4. Always end multi-line sections using any of the END keywords (ENDIF, ENDWHILE, etc.).
FOR: an additional looping method.
5. Keep your statements programming language independent.
IF-THEN-ELSE: A conditional statement that alters the algorithm’s flow is known as IF-THEN-ELSE.
6. Use the naming domain of the problem, not that of the implementation. For instance: “Append the
CASE: It is the IF-THEN-ELSE generalization form.
last name to the first name” instead of “name = first+ last.”
7. Keep it simple, concise and readable.
Note:

Algorithm: is kind of mathematical way/logic to solve the problem.


Pseudocode: is a simple way to write algorithm step by step in any language

Single line and Multi line comments Single line and Multi line comments

In general, there are two types of comments in programming languages. Example:


1. Single line comments /* This program takes age input from the user It stores it in the age variable And, print the value using
printf() */
Single line comments is accomplished by double-slash (//). Everthing that is followed by double-slash #include <stdio.h>
till the end of line is ignored by the compiler. int main() {
//declare integer variable
2. Multi line comments int age;
Multi-line comments starts by using forward slash followed by asterisk (/*) and ends by using asterisk printf("Enter the age: ");
scanf("%d", &age);
followed by forward slash (*/). Everthing between (/*) and (*/) are ignored by compiler whether it is printf("Age = %d", age);
one or more than one line. return 0;
}

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Basic Structure of C Program


Introduction to C
The C programming language contains a set of protocols that describe its operations.
Basic Structure of C Program

❖ C is a procedure oriented programming language. Dennis Ritchie invented it in the year 1972. It
was created primarily as a system programming language for creating an operating system.
❖ The main features of the C language include low-level memory access, a simple set of keywords,
and a clean style, these features make C language suitable for system programming like an operating
system or compiler development.
❖ Many advanced programming languages have borrowed syntax/features directly or indirectly from
the C language. The languages like Java, PHP, Java script and many other programming languages
are mainly based on the C language.

Basic Structure of C Program Basic Structure of C Program

The sections of a C program are listed below:

❖ Documentation section

❖ Preprocessor section

❖ Definition section

❖ Global declaration

❖ Main function

❖ User defined functions

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Basic Structure of C Program Basic Structure of C Program

Documentation Section: Preprocessor Section:


It includes statements such as a program's name, date, description, and title that are specified at the start All of the header files used in a program are found in the preprocessor section. It informs the system that
of the program. the header files should be linked to the system libraries. It is provided by:
Example: # i n c l u d e <s td i o . h> / / D e f i n e s c o r e i n p u t a n d o u t p u t f u n c t i o n s
//name of the program # i n c l u d e <s tr i ng . h > / / D e f i n e s s t r i n g h a n d l i n g f u n c t i o n s
(or) # i ncl ude<ma th.h> / / D efi nes co mmo n ma thema ti ca l functi o ns
/* This section provides instruction to the compiler to link the header files or functions from the system
Specify the title and date library.
*/
It provides overview of the program. The Documentation section consists of a set of comment lines.

Basic Structure of C Program Basic Structure of C Program

Definition Section: Main Function Section:


The definition section defines all symbolic constants such by using the #define directive. Every C-program should have one main() function. main() is the first function to be executed by the
#define a=5 computer. It is necessary for a code to include the main().
Global Declaration Section: The main function is declared as:
There are some variables that are used in more than one function, such variables are called global main()
variables. We can also use int or main with the main (). The void main() specifies that the program will not return
In C there are two types of variable declaration, any value. The int main() specifies that the program can return integer type data.
Local variable declaration: Variables that are declared inside the main function. int main()
Global variable declaration: Variables that are declared outside the main function. (or)
float num = 2.54; void main()
int a = 5;
char ch ='z';

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Basic Structure of C Program Basic Structure of C Program

Main Function Section: Main Function Section:


Main function is further categorized into local declarations, statements, and expressions. Statements:
Local Declarations The statements refers to if, else, while, do, for, etc. used in a program within the main function.
The variable that is declared inside a given function or block refers to as local declarations. Expressions:
An expression is a type of formula where operands are linked with each other by the use of operators. It
is given by:
main() a - b;
{ a +b;
int i = 2; //local variable
i++;
}

Basic Structure of C Program Basic Structure of C Program


/* Sum of two numbers */
User Defined Function: Example:
#include<stdio.h>
It includes number of functions implemented in the program. For example, color(), sum(), division(), etc.
int main()
Return statement is generally the last section of a code. But, it is not necessary to include. It is used
{
when we want to return a value. The return function returns a value when the return type other than the
int a, b, sum;
void is specified with the function.
printf("Enter two numbers to be added ");
return;
scanf("%d %d", &a, &b);
(or)
// calculating sum
return expression;
sum = a + b;
For example
printf("%d + %d = %d", a, b, sum);
return 0;
return 0; // return the integer value in the sum
}

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Executing a C Program Executing a C Program

Creating Source Code:


1. Click on the Start button
2. Select Run
3. Type cmd and press Enter
4. Type cd c:\TC\bin in the command prompt and press Enter
5. Type TC press Enter
6. Click on File -> New in C Editor window
7. Type the program
8. Save it as FileName.c (Use shortcut key F2 to save)

Executing a C Program Executing a C Program

Compile Source Code: Executing/Running Executable File(Ctrl+F9):


The compilation is the process of converting high-level language instructions into low-level language After completing compilation successfully, an executable file is created with a .exe extension. The
instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C. processor can understand this .exe file content so that it can perform the task specified in the source file.
Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On receiving a We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the .exe file is
source file, the compiler first checks for the Errors. If there are any Errors then compiler returns List of submitted to the CPU. On receiving .exe file, CPU performs the task according to the instruction written
Errors, if there are no errors then the source code is converted into object code and stores it as a file in the file. The result generated from the execution is placed in a window called User Screen.
with .obj extension. Check Result(Alt+F5):
Then the object code is given to the Linker. The Linker combines both the object code and After running the program, the result is placed into User Screen. Just we need to open the User Screen to
specified header file code and generates an Executable file with a .exe extension. check the result of the program execution. We use the shortcut key Alt + F5 to open the User Screen and
check the result.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

VARIABLES VARIABLES

A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can Rules for defining variables:
be reused many times. ❖ A variable can have alphabets, digits, and underscore.
It is a way to represent memory location through symbol so that it can be easily identified. ❖ A variable name can start with the alphabet, and underscore only. It can't start with a digit.
Syntax: ❖ No whitespace is allowed within the variable name.
datatype variable_name; ❖ A variable name must not be any reserved word or keyword, e.g. int, float, etc.
int a; Valid variable names:
float b; int a;
char c; int _ab;
Here, a, b, c are variables. The int, float, char are the data types. We can also provide values while
int a30;
declaring the variables as given below:
Invalid variable names:
int a=10,b=20;//declaring 2 variable of integer type
int 2;
float f=20.8;
int a b;
char c='A';
int long;

VARIABLES VARIABLES

Types of variables in C: local variable:


There are many types of variables in c: A variable that is declared inside the function or block is called a local variable.
1) local variable It must be declared at the start of the block.
2) global variable
3) static variable
4) automatic variable void add(){
5) external variable int x=12;//local variable
}

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

VARIABLES VARIABLES

global variable: static variable:


A variable that is declared outside the function or block is called a global variable. Any function can A variable that is declared with the static keyword is called static variable.
change the value of the global variable. It is available to all the functions. It retains its value between multiple function calls.
It must be declared at the start of the block.
void function1(){
int x=10;//local variable
If you call this function many times, the local variable
int value=20;//global variable static int y=10;//static
will print the same value for each function call, e.g,
void mul(){ variable
11,11,11 and so on. But the static variable will print
int x=10;//local variable x=x+1;
the incremented value in each function call, e.g. 11,
} y=y+1;
12, 13 and so on.
printf("%d,%d",x,y);
}

VARIABLES IDENTIFIER

automatic variable:
"Identifiers" or "symbols" are the names you supply for variables, types, functions, and labels in your program.
All variables in C that are declared inside the block, are automatic variables by default. We can explicitly
Identifier names must differ in spelling and case from any keywords. You can't use keywords (either C or
declare an automatic variable using auto keyword.
Microsoft) as identifiers; they're reserved for special use. Identifiers must be unique. They are created to give a
unique name to an entity to identify it during the execution of the program. For example:

void main(){
int money;
int x=10;//local variable (also automatic)
double accountBalance;
auto int y=20;//automatic variable
}
Here, money and accountBalance are identifiers
Also remember, identifier names must be different from keywords. You cannot use int as an identifier because
int is a keyword.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

IDENTIFIER Constant

A constant is a value or variable that can't be changed in the program. C Constants is the most
Rules for Naming Identifiers fundamental and essential part of the C programming language. Constants in C are the fixed values that
❖ A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores. are used in a program, and its value remains the same during the entire execution of the program.
❖ The first letter of an identifier should be either a letter or an underscore. ❖ Constants are also called literals.
❖ You cannot use keywords like int, while etc. as identifiers. ❖ Constants can be any of the data types.
❖ There is no rule on how long an identifier can be. However, you may run into problems in some ❖ It is considered best practice to define constants using only upper-case names.
compilers if the identifier is longer than 31 characters. Two ways to define constant in C
1. const keyword
2. #define preprocessor

Constant Constant

C const Keyword C const Keyword


The const keyword is used to define constant in C The const keyword is used to define constant in C programming. #include<stdio.h>
programming. #include<stdio.h>
Syntax: int main(){
Syntax: int main(){
const float PI=3.14;
const data_type constant_name; const float PI=3.14; const data_type constant_name;
PI=4.5;
Example: printf("The value of PI is: %f",PI); Example: printf("The value of PI is: %f",PI);
const float PI=3.14; return 0;
const float PI=3.14; return 0;
}
}

Output:
Note: If we try to change the value of PI, it will throw compile time error.
Compile Time Error: Cannot modify a const object

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Constant Constant

C #define preprocessor Constant Types in C

The #define preprocessor is also used to define constant. ❑ Numeric Constant


✓ Integer Constant
✓ Real Constant

#include <stdio.h> ❑ Character Constant

#define PI 3.14 Output: ✓ Single Character Constant

void main() { ✓ String Constant

printf("%f",PI); ✓ Backslash Character Constant

Constant Constant

Integer Constant Single Character Constant


It's referring to a sequence of digits. Integers are of three types: It simply contains a single character enclosed within ' and ' (a pair of single quote). It is to be noted that
✓ Decimal Integer the character '8' is not the same as 8.
✓ Octal Integer Example:
✓ Hexadecimal Integer 'X', '5', ';’
Example: String Constant
15, -265, 0, 99818, +25, 045, 0X6 These are a sequence of characters enclosed in double quotes, and they may include letters, digits, special
Real Constant characters, and blank spaces. It is again to be noted that "G" and 'G' are different - because "G"
The numbers containing fractional parts like 99.25 are called real or floating points constant. represents a string as it is enclosed within a pair of double quotes whereas 'G' represents a single
character.
Example:
"Hello!", "2015", "2+1"

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Constant KEYWORDS

Backslash Character Constant


A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only
C supports some character constants having a backslash in front of it. The lists of backslash characters
32 reserved words (keywords) in the C language.
have a specific meaning which is known to the compiler. They are also termed as "Escape Sequence".
For Example:
\t is used to give a tab auto break case char const continue default Do
\n is used to give a new line
double else enum extern float for goto If

int long register return short signed sizeof Static

struct switch typedef union unsigned void Volatile while

Input and Output Statements Input and Output Statements


Input and Output statement are used to read and write the data in C programming. These are embedded in scanf() and printf() functions
1. The printf() function
stdio.h (standard Input/Output header file). The printf() function is the most used function in the C language. This function is defined in <stdio.h>
header file.
When we say Input, it means to feed some data into a program. An input can be given in the form of a file
1. Print a sentence
or from the command line. C programming provides a set of built-in functions to read the given input and printf(“Welcome to SRMIST”);
feed it to the program as per requirement. 2. Print an integer value
We can use the printf() function to print integer value using the %d format specifier.
Example:
When we say Output, it means to display some data on screen, printer, or in any file. C programming
int x=10;
provides a set of built-in functions to output the data on the computer screen as well as to save it in text or printf(“X=%d”,x);
binary files.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Input and Output Statements Input and Output Statements


Format specifier getchar() & putchar() functions
Float-%f The getchar() function reads a character from the terminal and returns it as an integer.
Integer-%d Syntax:
Double-%lf int getchar(void)
Character-%c The putchar() function is used to display only one character at a time.
2. The scanf() function int putchar(int character)
The scanf() is used to store the input value into a variable. gets() & puts() functions
Syntax: The gets() function reads a line from standard input into the buffer pointed to by str pointer.
Scanf(“%f”,&var); Syntax:
Input integer value char* gets(char* str)
scanf(“%d”,&var1); The puts() function writes the string str with a newline character at the end to stdout. On success, non-
Input float value negative value is returned.
scanf(“%f”,&var1); Syntax:
int puts(const char* str)

Input and Output Statements Input and Output Statements


The main difference between scanf() and gets() functions is The main difference between scanf() and gets() functions is
gets() function reads space as character. gets() function reads space as character.
scanf() stop reading characters when it encounters a space. scanf() stop reading characters when it encounters a space.
If we eneter SRM University using scanf() it will only read and store SRM and will leave the part of the If we eneter SRM University using scanf() it will only read and store SRM and will leave the part of
string after space. But gets() function will read it completely. the string after space. But gets() function will read it completely.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Scope Scope
Local Variables:
A block or a region where a variable is declared, defined and used and when a block or a region ends, Variables that are declared within the function block and can be used only within the function are called
variable is automatically destroyed. local variables.
#include <stdio.h>
Local Scope or Block Scope
int main()
{ A local scope or block is a collective program statement placed and declared within a function or block (a
int var = 34; // Scope of this variable is within main() function only.
specific area surrounded by curly braces). C also has a provision for nested blocks, which means that a
// Therefore, called LOCAL to main() function.
printf("%d", var); block or function can occur within another block or function. So it means that variables declared within a
return 0;
block can be accessed within that specific block and all other internal blocks of that block but cannot be
}
accessed outside the block.

Scope Scope
Example (Local Variable): Example (Global Variable):
#include <stdio.h> #include <stdio.h>
int main () int z; //global variable
{ int main ()
//local variable definition and initialization {
int x,y,z; //local variable definition and initialization
//actual initialization int x,y;
x = 20; //actual initialization
y = 30; x = 20;
z = x + y; y = 30;
printf ("value of x = %d, y = %d and z = %d\n", x, y, z); z = x + y;
return 0; printf ("value of x = %d, y = %d and z = %d\n", x, y, z);
} return 0;
}

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Binding Storage classes


In C, binding refers to the association of a name with a particular entity, such as a variable or a function. Each variable in C programming language ha two properties.
Binding is typically done through the use of declarations or definitions in the code. 1. type
2. storage class
Example:
Type refers to the data type of a variable. And, a storage class determines or specify the scope or lifetime
#include <stdio.h>
int main() { of the variable.
int x = 5; // Binding the name 'x' to the value 5 There are four types of storage classes
printf("The value of x is: %d\n", x);
{ 1. automatic
int x = 10; // Binding a new 'x' in a nested block 2. external
printf("The value of nested x is: %d\n", x);
} 3. static
printf("The value of x is still: %d\n", x); // Accessing the outer 'x' 4. register
return 0;
}

Storage classes Storage classes


Automatic variable
Storage Class Purpose The variables declared inside a block are automatic or local variables. The local variables exist only
inside the block in which it is declared.
auto It is a default storage class • Automatic variables are allocated memory automatically at runtime.
• The visibility of the automatic variables is limited to the block in which they are defined.
extern It is a global variable • The scope of the automatic variables is limited to the block in which they are defined. The automatic
variables are initialized to garbage by default.
It is a local variable which is capable of returning value even • The memory assigned to automatic variables gets freed upon exiting from the block.
static • The keyword used for defining automatic variables is auto.
when control is transferred to the function call
• Every local variable is automatic in C by default.
register It is a variable which is stored inside a register.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Storage classes Storage classes


Automatic variable Automatic variable
Example: #include <stdio.h>
auto int age; int main( )
int add(void) {
{ auto int j = 1;
int a=13; {
auto int b=48; auto int j= 2;
return a+b; {
} auto int j = 3;
printf ( " %d ", j);
}
printf ( "\t %d ",j);
}
printf( "%d\n", j);
}

Storage classes Storage classes


Extern Global variable
Variables that are declared outside of all functions are known as external or global variables. They #include <stdio.h>
void display();
are accessible from any function inside the program. int n = 5; // global variable
➢ The default initial value of global variable is 0 otherwise null. int main()
{
➢ The external variable can be initialized outside the function only. ++n;
display(); Output:
➢ An external variable can be declared many times but can be initialized at only once. n=7
return 0;
}
void display()
{
++n;
printf("n = %d", n);
}

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Storage classes Storage classes


static static variable
A static variable is declared by using the keyword static. For example #include <stdio.h>
void display();
static int i; int main()
The value of the static variable persists until the end of the program. {
display();
➢ A static variable can be declared many times but can be initialized at only once. display();
➢ The default value of the static variable is 0 otherwise null. }
void display() Output:
{ 6 11
static int c = 1;
c += 5;
printf("%d ",c);
}

Storage classes Storage classes


register register variable
The register keyword is used to declare register variables. Register variables were supposed to #include <stdio.h>
int main()
be faster than local variables. {
➢ The variables defined as register is allocated the memory into the CPU registers. register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
➢ We can not dereference the register variable. printf("%d",a);
➢ The access time of register variable is faster than the local variables. }
➢ The initial default value of the register variable is 0.
➢ Static variables cannot be stored to the register.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

DATA TYPES DATA TYPES

A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
Types Description

They are arithmetic types and are further classified into: (a) integer types and
Basic Types
(b) floating-point types.

Enumerated They are again arithmetic types, and they are used to define variables that
Types can only assign certain discrete integer values throughout the program.

void The type specifier void indicates that no value is available.

They include (a) Pointer types, (b) Array types, (c) Structure types, (d)
Derived Types
Union types and (e) Function types.

DATA TYPES DATA TYPES

Integer Types Integer Types


To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator.
The expressions sizeof(type) yields the storage size of the object or type in bytes.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

DATA TYPES DATA TYPES

Floating-Point Types The void type

L value and R value in expression L value and R value in expression


L value and R value refer to the left and right sides of the assignment operator. Note:
An L value refers to an expression that represents a memory location. An L value means expression L value can be used as an R value , but an R-value cannot be used as an L value.
which can be placed on the left-hand side of the assignment operator. An expression which has memory The unary operator ‘&’ can be used to get the address of L value.
location. The address of operator ‘&’ cannot be applied to R value.
An examples of L values include variables, array elements, and deferential pointers. int main() {
int x = 10; // 'x' is an l-value
An R value refers to an expression that represents a value that is stored at some location. int y = x; // 'x' is an r-value on the right side of the assignment, and 'y' is an l-value
It can appear on the right-hand side of the assignment operator.
int* ptr = &x; // '&' operator gets the address of 'x', which is an l-value
An examples of R value include literals (e.g numbers and characters), the results of arithmetic operations, // The following lines would result in compilation errors:
// int* ptr2 = &10; // Error: Cannot take the address of an r-value
and function return values. // &x = 20; // Error: 'x' is an l-value, but the left side of the assignment operator expects an l-value
return 0;
}

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

OPERATORS
Operator Precedence
❖ The precedence of operators in C indicates the order in which the operators will be evaluated in the An operator is a symbol that operates on a value or a variable.

expression. For example : a+b (or) 4+5

❖ Associativity, on the other hand, defines the order in which the operators of the same precedence will A symbol that instructs the compiler to perform specific mathematical or logical functions is known as an

be evaluated in an expression. Also, associativity can occur from either right to left or left to right. operator.

❖ The precedence of operators determines which operator is executed first if there is more than Types of Operators
1. Unary Operator
one operator in an expression.
2. Arithmetic Operator
3. Relational Operator
4. Logical Operator
5. The ternary or conditional operator
6. Increment and Decrement operator
7. Bitwise Operator
8. Comma Operator
9. Sizeof Operator

OPERATORS OPERATORS

Arithmetic Operator
An arithmetic operator performs mathematical operations on numerical values such as addition,
subtraction, multiplication, and division (constants and variables).

Operator Meaning of Operator

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo division

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

OPERATORS OPERATORS

Arithmetic Operator Relational Operators


#include <stdio.h> A relational operator checks the relationship between two operands. Relational operators are
int main()
{ specifically used to compare two quantities or values in a program. If the relation is true, it returns 1; if
Output
int a = 10,b = 20, c; the relation is false, it returns value 0.
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}

OPERATORS OPERATORS

Relational Operators Relational Operators

Operator Meaning of Operator


#include <stdio.h>
== Equal to int main() {

> Greater than int x = 5;


int y = 3;
< Less than
printf("%d", x == y); // returns 0 (false) because 5
!= Not equal to is not equal to 3

>= Greater than or equal to return 0;


}
<= Less than or equal to

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

OPERATORS OPERATORS

Relational Operators Relational Operators

#include <stdio.h> #include <stdio.h>


int main() { int main() {
int x = 5; int x = 5;
int y = 5; int y = 3;
printf("%d", x == y); // returns 1 (true) because 5 printf("%d", x != y); // returns 1 (true) because 5
is equal to 5 is not equal to 3
return 0; return 0;
} }

OPERATORS OPERATORS

Relational Operators Logical Operators


An expression containing logical operator returns either 0 or 1 depending upon whether expression
#include <stdio.h> results true or false. Logical operators are commonly used in decision making in C programming.
int main() {
int x = 5;
int y = 3;
printf("%d", x>y); // returns 1 (true) because 5 is
greater than 3
return 0;
}

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

OPERATORS OPERATORS #include <stdio.h>


int main()
Logical Operators Logical Operators {
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
Operator Meaning of Operator printf(" %d \n", result);
result = (a == b) && (c < b);
printf(" %d \n", result);
Logical AND. True only if all operands
&& result = (a == b) || (c < b);
are true
printf(" %d \n", result);
result = (a != b) || (c < b);
Logical OR. True only if either one printf(" %d \n", result);
||
operand is true result = !(a != b);
printf(" %d \n", result);
Logical NOT. True only if the operand is result = !(a == b);
! printf(" %d \n", result);
0
return 0;
}

OPERATORS OPERATORS

The ternary or conditional operator The ternary or conditional operator


The conditional operator is similar to the if-else statement in that it follows the same algorithm, but the Syntax:
The conditional operator is of the form
conditional operator takes less space and helps to write the if-else statements in the shortest possible
variable = Expression1 ? Expression2 : Expression3
way. It can be visualized into if-else statement as:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Since the Conditional Operator ‘?:’ takes three operands to work, hence they are also called ternary
operators.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

OPERATORS OPERATORS

The ternary or conditional operator Increment and Decrement operator


#include <stdio.h> C programming has two operators increment ++ and decrement -- to change the value of an operand
int main()
{ (constant or variable) by 1. Increment ++ increases the value by 1 whereas decrement -- decreases the
int m = 10, n = 8; value by 1. These two operators are unary operators, meaning they only operate on a single operand.

(m > n) ? printf("m is greater than n that is %d > %d",m, n)


: printf("n is greater than m that is %d > %d",n, m); #include <stdio.h>
return 0; int main()
} {
int a = 10,b=6,c=12,d=15;
printf("a=%d \n", ++a);
printf("b=%d \n", --b);
printf("c=%d \n", ++c);
printf("d=%d \n", --d);
return 0;
}

OPERATORS OPERATORS

Increment and Decrement operator Increment and Decrement operator

#include <stdio.h> #include <stdio.h>


int main() int main()
{ {
int a = 10,b=6,c=12,d=15; int a = 10;
printf("a=%d \n", a++); printf("a=%d \n", a++);
printf("b=%d \n", b--); printf("b=%d \n", a);
printf("c=%d \n", c++); printf("c=%d \n", ++a);
printf("d=%d \n", d--); printf("d=%d \n", a);
return 0; return 0;
} }

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Bitwise Operators in C Bitwise Operators in C

❖ Bitwise operators are used to manipulate one or more bits from integral operands like char, int, short,
long. Operator Description Example
❖ Bitwise operators operate on individual bits of integer (int and long) values.
❖ If an operand is shorter than int, it is promoted to int before doing the operations. & (AND) Returns AND of input values a&b
❖ In the calculation, just the individual bits of a number are considered, not the complete number.
❖ Negative integers are stored or represented in two’s complement form. For example, -4 is 1111 1111 1111
| (OR) Returns OR of input values a|b
1111 1111 1111 1111 1100.

^ (XOR) Returns XOR of input values a^b

~ (Complement) Returns the one’s complement ~a

Bitwise Operators in C Bitwise Operators in C


Bitwise AND ‘&’ Bitwise OR ‘|’

Truth Table int a=2; // 0010 Truth Table int a=2; // 0010
int b=3; // 0011 int b=3; // 0011

int c=a & b; int c=a | b;

0010 0010
0011 0011
Output: Output:
--------- ---------
0010 0011

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Bitwise Operators in C Bitwise Operators in C


Bitwise XOR ‘^’ Bitwise Negation ‘~’

Truth Table int a=2; // 0010 Truth Table int a=2; // 0010
int b=3; // 0011

int c=a ^ b; int c=~a;

0010 0010
0011 ---------
Output: Output:
--------- 11 01
00 01

Bitwise Operators in C Bitwise Operators in C


Bitwise Negation ‘~’ Shift operators are used to shift a number's bits left or right. Basically two types of shift
Input 2=> 0 0 1 0
operators,
#include <stdio.h>
int main() Apply negation 1101 1. Left Shift Operator (<<)
{ 1101 Output: 2. Right Shift Operator (>>)
printf("%d",~2); 0010
Take 2’s complement(1’s Left Shift Operator
1
return 0; complement+1)
---------- It moves the first operand's bits to the left by the number of positions specified by the
} 00 11
second operand. Simultaneously, the empty spaces left by the shifted bits are filled with
Equivalent decimal value is -3
zeroes.
Right Shift Operator
The right shift operator (>>) shifts the first operand to the right by the specified number of
bits. Excess bits that are shifted to the right are discarded.

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Bitwise Operators in C (Left Shift) Bitwise Operators in C Right Shift)

Example: Binary Format 0 0 0 0 1 0 1 0 Example: Binary Format 0 0 0 0 1 0 1 0


int a=10; int a=10;
c=a<<2; These two bits c=a>>2;
will be discarded These two
0 0 bits will
0 0
be
Filled with
128 64 32 16 8 4 2 1 removed.
zero’s
0 0 1 0 1 0 0 0
128 64 32 16 8 4 2 1
These two places
filled with zeros 0 0 0 0 0 0 1 0
32+8=40

Bitwise Operators in C Bitwise Operators in C

Program Program

#include <stdio.h> #include <stdio.h>


int main() int main()
{ {
printf("%d",10<<2); printf("%d",10>>2);
return 0; return 0;
} }

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Bitwise Operators in C (Signed Integer) Bitwise Operators in C (Signed Integer)

Signed integers are numbers with a “+” or “-“ sign. If n bits are used to represent a signed
No
-8>>0 1000 -8
binary integer number, then out of n bits,1 bit will be used to represent a sign of the number change
and rest (n - 1)bits will be utilized to represent magnitude part of the number itself.
-8>>1 1000 1100 -4
There are various ways of representing signed numbers in a computer −
•Sign and magnitude -4>>1 1100 1110 -2

•One's complement -2>>1 1110 1110 -1


•Two's complement
-1>>1 1110 1111 0

Bitwise Operators in C (Signed Integer) Bitwise Operators in C


#include <stdio.h>
Example: -13>>2 int main()
No
-8<<0 1000 -8 Perform right shift for two times.
change {
printf("%d",-13>>2);
-8>>1 1000 1100 -16
return 0;
-4>>1 1100 1110 -32 }
How? Output:
-2>>1 1110 1110 -64
-4
-1>>1 1110 1111 -128

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Bitwise Operators in C Bitwise Operators in C


#include <stdio.h>
The signed integer can not be processed directly as it is. It should be represented in 2’s Example: -13<<2 int main()
complement format. Now the computer will perform shifting of bits. To find the equivalent Perform right shift for two times. {

decimal value , again take 2’s complement. The MSB will be used to represent a sign of the printf("%d",-13<<2);
return 0;
number. Input Output Task
-13 1101 Binary representation of 13
}
1101 001 0 One’s complement How? Output:
0010 0011 Add 1 -52

0011 1100 Right shift

To find the equal decimal value take 2’s complement

Output=(-4)

Bitwise Operators in C Bitwise Operators in C


-13>>2 Perform shift operation for two times
Binary form of 13 Take 2’s complement of 13
00001101 Binary format
128 64 32 16 8 4 2 2
13 11110010 One’s complement
1 (+) Add 1
0 0 1 1 0 1 0 0
Perform left shift(two bits
11110011
will be removed)
Actual output of signed
After shifting 11001100
left shift
To get equivalent decimal
Take 2’s complement again
value 32+16+4=52
11001100
00110011 One’s complement
1(+) Add 1
Find the equivalent
00110100
decimal value

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

OPERATORS OPERATORS

Comma operator sizeof operator


Comma operators are used to link related expressions together. The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).

#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}

EXPRESSIONS EXPRESSIONS

In C, an expression is a set of operands and operators that computes a single value stored in a An expression can be defined depending on the position and number of its operator and operands:
variable. The operator represents the action or operation to be carried out. The operands are the Infix Expression (operator is used between the operands)
items to which the operation is applied. a=x+y
Postfix Expression (operator is used after the operands)
xy+
Prefix Expression (operator is used before the operands)
+xy
Unary Expression (one operator and one operand)
x++
Binary Expression (one operator and two operands)
x+y

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

EXPRESSIONS EXPRESSIONS

Types of Expression Types of Expression

Arithmetic Expression
It consists of arithmetic operators ( + , - , * , and / ) and computes values of int, float, or double type.

Relational Expression
It usually consists of comparison operators (> , < , >= , <= , === , and !== ) and computes the
answer in the bool type, i.e., true (1) or false (0).

Logical Expression
It consists of logical operators (&&, ||, and !) and combines relational expressions to compute
answers in the bool type.

EXPRESSIONS EXPRESSIONS

Types of Expression #include <stdio.h>


int main(){
int a = (6 * 2) + 7 - 9; //Arithmetic Expression
Conditional Expression printf("The arithmetic expression returns: %d\n", a);
int b = 10;
It consists of conditional statements that return true if the condition is met and false otherwise.
printf("The relational expression returns: %d\n", b % 2
== 0); //Relational Expression
int c = (7 > 9) && ( 5 <= 9); //Logical Expression
printf("The logical expression returns: %d\n", c);
Pointer Expression int d = (34 > 7) ? 1 : 0; //Conditional Expression
printf("The conditional expression returns: %d\n", d); //Pointer Expression
It may consist of an ampersand (&) operator and returns address values. int e = 20;
int *addr = &e;
printf("The pointer expression returns: %p\n", addr); //Bitwise Expression
Bitwise Expression int f = 10;
int shift = 10 >> 1;
It consists of bitwise operators ( >>, <<, ~, &, |, and ^ ) and performs operations at the bit level. printf("The bitwise expression returns: %d\n", shift);
return 0;
}`

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

EXPRESSIONS
Operator Precedence
Let us consider an example:
int x=5-17*9;
In C, the precedence of * is higher than – and =. Hence, 17*9 is evaluated first. Then – is evaluated and
The arithmetic expression returns: 10
The relational expression returns: 1 result is assigned to the variable x.
The logical expression returns: 0
The conditional expression returns: 1
The pointer expression returns: 0x7ffdb0430704
The bitwise expression returns: 5

Operator Precedence Operator Precedence


Category Operator Associativity Parentheses:
Postfix () [] -> . ++ - - Left to right The expressions within parentheses are evaluated first. This allows you to control the order of evaluation.
Unary + - ! ~ ++ - - (type)* & sizeof Right to left int result = (2 + 3) * 4; // result = 20
Multiplicative */% Left to right (2+3) is evaluated first and then it is multiplied with 4.
Additive +- Left to right 1) 2+3=5
Shift << >> Left to right 2) 5*4=20
Relational < <= > >= Left to right
Equality == != Left to right Postfix operators:
Bitwise AND & Left to right Postfix operators like function calls and array subscripting have higher precedence than most other
Bitwise XOR ^ Left to right operators.
Bitwise OR | Left to right int arr[5] = {1, 2, 3, 4, 5};
Logical AND && Left to right int value = arr[2] * 3; // value = 9
Logical OR || Left to right arr[2]=3
Conditional ?: Right to left 3*3=9
Assignment = += -= *= /= %=>>= <<= &= Right to left
^= |=
Comma , Left to right

Downloaded by Abel (abelantony765@gmail.com)


lOMoARcPSD|46000405

Operator Precedence Operator Precedence


Parentheses: Unary operators:
The expressions within parentheses are evaluated first. This allows you to control the order of evaluation. Unary operators, such as the increment (++) and decrement (--) operators, are applied next.
int result = (2 + 3) * 4; // result = 20 int a = 5;
(2+3) is evaluated first and then it is multiplied with 4. int result = ++a; // a becomes 6, (Right to Left)
1) 2+3=5 result = 6
2) 5*4=20 Multiplicative operators:
Multiplication (*), division (/), and modulo division (%) operators have higher precedence than additive
Postfix operators: operators.
Postfix operators like function calls and array subscripting have higher precedence than most other int result = 10 + 2 * 5; // result = 20 (multiplication is done first)
operators. Additive operators:
int arr[5] = {1, 2, 3, 4, 5}; Addition (+) and subtraction (-) operators are applied after the multiplicative operators.
int value = arr[2] * 3; // value = 9 int result = 10 - 2 + 5; // result = 13 (subtraction is done first) (Left to Right)
arr[2]=3
3*3=9

Operator Precedence Operator Precedence


Relational and equality operators: Logical operators:
These operators compare values and have higher precedence than logical operators. Logical AND (&&) and logical OR (||) operators are applied after relational and equality operators.
int result = 5 < 10 && 2 == 2; // result = 1 (true) int result = 5 < 10 || 2 > 5; // result = 1 (true)
Order of Evaluation Assignment operators:
1. 5<10 =>1(Hence 5 is less than 10) Assignment operators (=, +=, -=, *=, /=, %=) are applied after all other operators.
2. 2==2=>1 int a = 5;
3. Finally && is evaluated (1&&1)=1 a += 3; // a becomes 8
a=a+3;
a=5+3=>8
Conditional operator (ternary operator):
The conditional operator (?:) is evaluated after all other operators. It is used for conditional
expressions.
int a = 5; int result = (a > 10) ? a : 10; // result = 10
------------------------------------------------------------------------------------------------------------------

Downloaded by Abel (abelantony765@gmail.com)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy