Programming For Problem Solving Lecture Notes

sreedharchowdam1 1,639 views 151 slides Feb 10, 2022
Slide 1
Slide 1 of 151
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151

About This Presentation

Course: Programming for Problem Solving Lecture Notes.
Certain part of the information is grabbed from internet sources.


Slide Content

Syllabus, Introduction
PROGRAMMING FOR
PROBLEM SOLVING (PPS)
B.TechI SemCST

Course Outcomes
CO1: Understand fundamentals of problem solving concepts with
various data types and operators
CO2: Apply conditional and iterative statementsfor solving a
given problem
CO3: Illustrate the applications of functions and storage classes.
CO4: Apply the concepts of pointers and dynamic memory
managementin problem solving.
CO5: Understand the purpose of structures, unions and files.

Unit 1
General Problem Solving Concepts
Algorithm, Flowchart for problem solving with Sequential Logic Structure,
Decisions and Loops.
Imperative Languages
Introduction ; syntax and constructs of a specific language (ANSI C)–
Types Operator and Expressions with discussion of variable naming and
Hungarian Notation: Variable Names, Data Type and Sizes (Little
EndianBig Endian), Constants, Declarations, Arithmetic Operators,
Relational Operators, Logical Operators, Type Conversion, Increment
Decrement Operators, Bitwise Operators, Assignment Operators and
Expressions, Precedence and Order of Evaluation, Formatted input/output

Unit 2
Control Flow with discussion on structured and
unstructured programming
Statements and Blocks, If-Else-If, Switch,
Loops–while, do, for, break and continue, gotolabels,
structured and un-structured programming

Unit 3
Functions and Program Structure with discussion on
standard library
Basics of functions, parameter passing and returning
type, C main return as integer,
External, Auto, Local, Static, Register Variables,
Scope Rules, Block structure, Initialization,
Recursion, Pre-processor, Standard Library Functions and
return types.

Unit 4
Pointers and Arrays:
Pointers and address, dynamic memory management,
Pointers and Function Arguments, Pointers and Arrays,
Address Arithmetic, character Pointers and Functions,
Pointer Arrays,
Pointer to Pointer, Multi-dimensional array and Row/column
major formats, Initialization of Pointer Arrays, Command
line arguments, Pointer to functions, complicated declarations
and how they are evaluated

Unit 5
Structures and Unions:
Basic Structure, Structures and Functions,
Array of structures, Pointer of structures, Self-referral
structures, Table look up, typedef, Unions, Bit-fields.
Files:
Introduction to Files, Opening and Closing files, Reading
and Writing files, File I/O functions, Error Handling in files

Textbooks & References
1.The C Programming Language, B. W. Kernighan
and D. M. Ritchie, Second Edition, PHI.
2.Programming in C, B. Gottfried, Second Edition,
SchaumOutline Series.
1. C: The Complete Reference, Herbert Schildt,
Fourth Edition, McGraw Hill.
2. Let Us C, YashavantKanetkar, BPB Publications

PROGRAMING FOR PROBLEM
SOLVING LAB [PPS(P)]
CO1:Implementprograms using conditional and loop statements in C.
CO2:Develop programs using 1-Dimensional and 2-Dimensional arrays.
CO3:Perform Call by value, Call by reference and Recursion through
functions.
CO4:Implement programs using pointers.
CO5:Develop programs using structures and file concepts

List of Experiments
1. Conditional Statements:
Quadratic equations, usage of switch statement.
2. Loop Statements :
Adam Number, Cosine series
3. Arrays:
Max Min problem, standard deviation and variance.
4. Character Arrays:
Palindrome, implementation of string handling functions.

List of Experiments
5. Functions and Recursion :
Matrix operations, Towers of Hanoi, GCD
6. Pointers:
Interchanging problem,
implementation of dynamic memory allocation.
7. Structures:
Usage of structures in various applications.
8. Files:
Reading contents from files and writing contents to files

C is a programming
language developed
at Bell Laboratories of
USA in 1972 by Dennis
Ritchie

C is a programming language developed at Bell
Laboratories of USA in 1972 by Dennis Ritchie

Numbering System

Decimal to Binary

Decimal to Binary

Decimal to Binary
156
(10)
10011100
(2)

Binary representation (Decimal to Binary
Decimal no.= 123
Binary no. = 1111011
Decimal no. = 255
Binary no. = 1111 1111
Decimal no. = 486
Binary no. = 111100110

Binary to Decimal

Binary to Decimal

Binary to Decimal

Binary to Decimal

Binary to Decimal
Binary no. = 110011
Decimal no. = 51
Binary no. = 1111 0001
Decimal no. = 241

Unit 1
General Problem Solving Concepts
Algorithm, Flowchart for problem solving with Sequential Logic Structure, Decisions
and Loops.
Imperative Languages
Introduction ; syntax and constructs of a specific language (ANSI C)–Types
Operator and Expressions with discussion of variable naming and Hungarian
Notation: Variable Names, Data Type and Sizes (Little EndianBig Endian),
Constants, Declarations, Arithmetic Operators, Relational Operators, Logical
Operators, Type Conversion, Increment Decrement Operators, Bitwise Operators,
Assignment Operators and Expressions, Precedence and Order of Evaluation,
Formatted input/output

Algorithm
Algorithm is a finite set of instructions that if followed
accomplishes a particular task.
Algorithm
Input Output
Problem
Computer

Problem: Shortest distance
Input
n nodes
connecting nodes
distance between nodes
Output
Shortest distance: 18

Problem: Search

Problem: Search

Problem: Sort

Problem: Sort

Characteristics of Algorithm
Input
Output
Definiteness
Effectiveness
Finiteness
Input−An algorithm should have 0 or
more well-defined inputs.
Output−An algorithm should have 1 or
more well-defined outputs, and should
match the desired output.
Definiteness−Should be clear and
unambiguous. Each of its steps and their
inputs/outputs should be clear and must
lead to only one meaning.
Effectiveness−An algorithm should have
step-by-step directions, which should be
independent of any programming code
Finiteness−An algorithm must terminate
after a finite number of steps.

Characteristics of Algorithm
Input−Should have 0 or more well-defined inputs.
OutputShould have 1 or more well-defined outputs, and
should match the desired output.
Definiteness−Should be clear and unambiguous.
Effectiveness−Should have step-by-step directions, which
should be independent of any programming code.
Finiteness−Must terminate after a finite number of steps.

Program to display “Welcome to C”
#include<stdio.h>
intmain()
{
printf(“Welcome to C”);
return 0;
}

Problem 1: Addition of two numbers
Input :
two numbers (num1 = 4,
num2 = 6)
Output:
Sum = 10
Algorithm
Step 1: Start
Step 2: Read the first number(num1)
Step 3: Read second number(num2)
Step 4: Sum num1+num2
Step 5: Print Sum
Step 6: Stop
Sum = num1 + num2

Program to accept two numbers from the user and display the
sum using C language
/*
Program to accept two numbers and display the sum
Programmer : --Your name--
Roll no: --your roll number--
Date of compilation: 27Jan2021
Class : B.TechI Sem„CST'
*/

#include<stdio.h>
// Main function begins
intmain()
{
intnum1,num2,sum;
printf("Enter first value:");
scanf("%d",&num1);
printf("Enter Second value:");
scanf("%d",&num2);
sum=num1+num2;
printf(“Addition of %d and %d is: %d",num1,num2,sum);
return 0;
}

Problem 2: Algorithm to find the area of rectangle
Input :
two numbers. (length = 8
breadth = 4)
Output:
Area of rect= 32
Algorithm
Step 1: Start
Step 2: Read first number(length)
Step 3: Read second number (breadth)
Step 4: Area length * breadth
Step 5: Print “Area of rect”, Area
Step 6: Stop
Area = length * breadth

Ex3: Problem: Find greater of two no‟s
Algorithm:
Step 1: Start
Step 2: Declare variables A, B
Step 3: Accept two values from user and store in A and B
respectively.
Step 4: Check whether A > B; True: 4.1; False: 4.2
4.1 Yes Print A is greater
4.2 No Print B is greater
Step5: Stop

Ex4: Find Largest of three numbers
Step 1: Start
Step 2: Declare variables a,band c.
Step 3: Read variables a,band c.
Step 4: If a>b ; True: 4.1; False: 4.2
4.1 If a>c True: 4.1.1; False: 4.1.2
4.1.1 Display a is the largest number.
else
4.1.2 Display c is the largest number.
4.2 Else
If b>c True: 4.2.1; False: 4.2.2
4.2.1 Display b is the largest number.
else
4.2.2 Display c is the greatest number.
Step 5: Stop

Ex5: Calculate Gross, Net Salary
Problem:
Accept the employee details such as empidand
basic salary. Consider DA with 120% of basic, HRA
with 10% of basic. Calculate the gross salary and
net salary considering tax deduction of Rs. 2% of
gross.

Example: Gross, Net
Empid: 1001
Basic: 10000
DA: 120% of Basic=1.20*10000= 12000
HRA: 10% of Basic=0.1*10000 = 1000
Gross=Basic+DA+HRA= 10000+12000+1000=23000
Tax: 2% of Gross = 0.02*23000=460
Net = Gross-Tax = 23000-460 = 22540

Algorithm: Gross, Net
Step 1: Start
Step 2: Declare variables empid,basic,da,hra,tax,gross,net
Step 3: Print "Enter Employee ID"
Step 4: Accept empid
Step 5: Print "Enter basic salary"
Step 6: Accept basic
Step 7: Compute da=(120/100)*basic
Step 8: Compute hra=(10/100)*basic
Step 9: Compute gross=(basic+da+hra)
Step 10: Print "Gross Salary"
Step 11: Compute tax=(2/100)*gross
Step 12: net=gross-tax;
Step 13: Print "Net Salary"
Step 14: Stop

#include<stdio.h>
intmain()
{
intempid;
float basic,da,hra,tax,gross,net;
printf("Enter Employee id:");
scanf("%d",&empid);
printf("Enter Basic Salary:");
scanf("%f",&basic);
da=1.2*basic;
hra=0.1*basic;
gross=(basic+da+hra);
printf("Gross Salary=%f",gross);
tax=0.02*gross;
net=gross-tax;
printf("Net Salary=%f",net);
return 0;
}

Ex 6: Calculate Simple Interest
Si = (P * T * R) / 100

Flowchart
A Flowchart is a type of diagram (graphical or symbolic) that
represents an algorithm or process.
Each step in the process is represented by a different symbol
and contains a short description of the process step.
The flow chart symbols are linked together with arrows showing
the process flow direction. A flowchart typically shows the flow
of data in a process, detailing the operations/steps in a
pictorial format which is easier to understand than reading it in
a textual format.

Flowchart
Flowchart is the pictorial representation of an algorithm

49
Identify
What do each of the following symbols represent?
Terminal
Input/Output
Operation
Process
Decision
Connector
Module

Example 1: Algorithm & Flowchart
Problem: Display the Sum, Average, Product of
three given numbers
Algorithm
Step1: Start
Step 2: Read X, Y, Z
Step 3: Compute Sum (S) X + Y + Z
Step 4: Compute Average (A) S / 3
Step 5: Compute Product (P) as X xY x Z
Step 6: Print S, A, P
Step 7: Stop

Example 2: Algorithm & Flowchart
Problem: Display the largest of two given numbers
Algorithm
Step1: Start
Step 2: Read A, B
Step 3: If A is less than B
True: Assign A to BIG and B to SMALL
False: Assign B to BIG and A to SMALL
Step 6: Print S, A, P
Step 7: Stop

Control Structures
Sequence:A series of steps or statements that are executed in
the order they are written in an algorithm.
Selection:Defines two courses of action depending on the
outcome of a condition. A condition is an expression that is,
when computed, evaluated to either true or false. (ex: if, if
else, nested if)
Repetition/Loop:Specifies a block of one or more statements
that are repeatedly executed until a condition is satisfied. (Ex:
for, while, do while)

Ex: SequenceControl Structure
A series of steps or statements that are executed in the
order they are written in an algorithm.
The beginning and end of a block of statements can be
optionally marked with the keywords begin and end.
begin
statement 1
statement 2
statement n
.....
end

SequenceEx: Calculate Person‟s age

SequenceExample
intmain()
{
intfirst, second, temp;
printf("Enter first number: ");
scanf("%d", &first);
printf("Enter second number: ");
scanf("%d", &second);
temp = first;
first = second;
second = temp;
printf("After swapping, firstno. = %d\n", first);
printf("After swapping, secondno. = %d", second);
}
Swap two
numbers
using temp
var

SequenceExample
intmain()
{
inta, b;
printf("Enter a and b: ");
scanf("%d %d", &a, &b);
a = a -b;
b = a + b;
a = b -a;
printf("After swapping, a = %d\n", a);
printf("After swapping, b = %d", b);
return 0;
}
Swap two
numbers
without
using temp
var

Selection(Decision) Control structure
is
condition
Y N
Print
stmt1
Print
stmt2

Syntax: if
if (condition)
stmt1
else
stmt2
C programming
if (a>b)
printf(“a is greater than b”);
else
printf(“b is greater than a”);
Selection(Decision) Control structure

SelectionEx: Program to print the given
number is negative or positive using if else
intmain()
{
intnum;
printf("Enter a number to check.\n");
scanf("%d",&num);
if (num<0)
printf(“Given Number = %d is negative\n",num);
else
printf(“Given Number = %d is positive\n",num);
return 0;
}

SelectionEx:
Problem: Write an algorithm to determine a student‟s final grade
and display pass or fail. The final grade is calculated as the
average of four subject marks.
Algorithm
Step1: Start
Step 2: Input M1,M2,M3,M4
Step 3: GRADE (M1+M2+M3+M4)/4
Step 4: if (GRADE > 60) then Print “Pass” else “Fail”
Step 5: Stop

START
Input
M1,M2,M3,M4
GRADE(M1+M2+M3+M4)/4
IS
GRADE>60
STOP
YN
Print
“Fail”
Print
“Pass”
Algorithm
Step1: Start
Step 2: Input M1,M2,M3,M4
Step 3: GRADE (M1+M2+M3+M4)/4
Step 4: if (GRADE > 60) then Print “Pass” else “Fail”
Step 5: endif
Step 6: Stop
SelectionEx:

SelectionEx:
Program to check for odd or even
intmain()
{
intnum;
printf("Enter an integer: ");
scanf("%d", &num);
if (num % 2 == 0)
printf("%d is even.", num);
else
printf("%d is odd.", num);
return 0;
}

SelectionEx: Program to check odd or
even using ternary operator ? :
intmain()
{
intnum;
printf("Enter an integer: ");
scanf("%d", &num);
(num % 2 == 0) ?printf("%d is even.", num) :printf("%d is odd.", num);
return 0;
}

SelectionEx: Problem: Find greater of two no‟s
Algorithm:
Step 1: Start
Step 2: Declare variables A, B
Step 3: Accept two values from user and store in A and B
respectively.
Step 4: Check whether A > B; True: 4.1; False: 4.2
4.1 Yes Print A is greater
4.2 No Print B is greater
Step5: Stop

Selection

SelectionEx: Find Largest of three numbers
Step 1: Start
Step 2: Declare variables a,band c.
Step 3: Read variables a,band c.
Step 4: If a>b ; True: 4.1; False: 4.2
4.1 If a>c True: 4.1.1; False: 4.1.2
4.1.1 Display a is the largest number.
else
4.1.2 Display c is the largest number.
4.2 Else
If b>c True: 4.2.1; False: 4.2.2
4.2.1 Display b is the largest number.
else
4.2.2 Display c is the greatest number.
Step 5: Stop

intmain()
{
double n1, n2, n3;
printf("Enter three different numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);
if (n1 >= n2 && n1 >= n3)
printf("%.2f is the largest number.", n1);
if (n2 >= n1 && n2 >= n3)
printf("%.2f is the largest number.", n2);
if (n3 >= n1 && n3 >= n2)
printf("%.2f is the largest number.", n3);
return 0;
}
Selection: if

intmain()
{
double n1, n2, n3;
printf("Enter three numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);
if (n1 >= n2 && n1 >= n3)
printf("%.2lf is the largest number.", n1);
else if (n2 >= n1 && n2 >= n3)
printf("%.2lf is the largest number.", n2);
else
printf("%.2lf is the largest number.", n3);
return 0;
}
Selection: if else if

intmain()
{
double n1, n2, n3;
printf("Enter three numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);
if (n1 >= n2)
{
if (n1 >= n3)printf("%.2lf is the largest number.", n1);
else printf("%.2lf is the largest number.", n3);
}
else
{
if (n2 >= n3)printf("%.2lf is the largest number.", n2);
else printf("%.2lf is the largest number.", n3);
}
return 0;
}
Selection: nested if

Repetition: While condition

Loop: for
for(initialization, condition, incrementation)
{
code statements;
}
intmain()
{
inti;
for (i=0; i<10; i++)
{
printf("i=%d\n",i);
}
return 0;
}

Loop Example: Multiplication table
intmain()
{
intn, i;
printf("Enter no. to print multiplication table: ");
scanf("%d",&n);
for(i=1;i<=10;++i)
{
printf("%d * %d = %d\n", n, i, n*i);
}
}

for(i= 0; i< 5; i++)
{
printf("\t\t\t\t");
for(j = 0; j < 5; j++)
printf("* ");
printf("\n");
}

Practice Programs in Lab
1. Program to swap two numbers.
2. Program to accept student id (integer), marks of four subjects
and calculate the sum and average. If the average is greater than
60 Print “Pass” else “Fail”.
3. Program to display whether the given integer is odd or even.
4. Program to find simple interest.
5. Program to find the largest of three given numbers.
6. Program to accept two numbers and check whether both are
same.

ANSI C:
Syntax
and
constructs

C basic elements
Valid character set
Identifiers
Keywords
Basic data types
Constants
Variables

C Valid character set
uppercase English alphabets A to Z,
lowercase letters a to z,
digits 0 to 9,
certain special characters as building blocks to form
basic program elements viz. constants, variables,
operators, expressions and statements.

C Identifiers
Identifiers are names given to various items in the program, such as
variables, functions and arrays.
An identifier consists of letters and digits, in any order, except that the
first character must be a letter.
Both upper and lowercase letters are permitted.
C is a case sensitive, the upper case and lower case considered
different, for example code, Code, CODE etc. are different
identifiers.
The underscore character_can also be included.
Keywords like if, else, int, float, etc., have special meaning and they
cannot be used as identifier names.

Valid and invalid C identifiers
ANSI standard recognizes 31 characters
valid identifiers: A, ab123, velocity, stud_name,
circumference, Average, TOTAL.
Invalid identifiers:
1st
"Jamshedpur"
stud-name
stud name

C Data types

C Data types and sizes
Data type Description Size Range
char single character 1 byte 0 -255
int integer number 4 bytes
-2147483648 to
2147483647
float
single precision floating point
number (number containing
fraction & or an exponent)
4 bytes 3.4E-38 to 3.4E+38
double
double precision floating point
number
8 bytes 1.7E-308 to 1.7E+308

C Data types and sizes
Data type Size Range
short int 2 bytes-32768 to 32767
long int 4 bytes
-2147483648 to
2147483647
unsigned short int 2 bytes0 to 65535
unsigned int 4 bytes0 to 4294967295
unsigned long int 4 bytes0 to 4294967295
long double (extended precision)8 bytes1.7E-308 to1.7E+308

C Constants
C can be classified into four categories namely integer
constants, floating point constants, character constants
and string constants.
A character constant is written as for example -'A'
A normal integer constant is written as 1234.
A long intuses L (uppercase or lowercase) at the end of
the constant, e.g. 2748723L
C also supports octal and hexadecimal data. Ex: 0xC

Escape sequence characters
Character Escape SequenceASCII Value
Bell \a 007
Backspace \b 008
Null \0 000
Newline \n 010
Carriage return \r 013
Vertical tab \v 011
Horizontal tab \t 009
Form feed \f 012

Symbolic constants
#define PI 3.141593
#define TRUE 1
#define PROMPT "Enter Your Name :"

Accept name from the user
Method 1
char name[20];
printf("Enter your name:");
scanf("%s",name);
printf("Your name is: %s",name);
Method 2
char name[20]
printf(“Enter your name:”)
gets(name);
printf(“Your name is:”);
puts(name);

Accept name from the user
Method 3
#define MAX_LIMIT 20
intmain()
{
char name[MAX_LIMIT];
printf("Enter your name:");
fgets(name,MAX_LIMIT,stdin);
printf("Your name is: %s",name);
Method 4
char name[20];
printf("Enter your name:");
scanf("%[^\n]%*c",name);
printf("Your name is: %s",name);

Operators in C
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Misc operators

inta = 10, b = 20,c = 25,d = 25;
printf(“ %d" (a + b) );
printf(“%d" (a -b) );
printf(“%d “ (a * b) );
printf(“%d” (b / a) );
printf(“%d” (b % a) );
printf(“%d” (c % a) );
printf(“%d“ (a++) );
printf(“%d “ (a--) );
printf(“%d “ (d++) );
printf(“%d “ (++d) );
OUTPUT
30
-10
200
2
0
5
10
11
25
27

Example: Bitwise Operators
inta = 60;
intb = 13;
intc = 0;
c = a & b; printf(“%d" + c );
c = a | b; printf(“%d" + c );
c = a ^ b; printf(“%d" + c );
c = ~a; printf(“%d" + c );
c = a << 2; printf(“%d" + c );
c = a >> 2; printf(“%d" + c );
OUTPUT
a= 60 = 0011 1100
b= 13 = 0000 1101
c = a & b; 0000 1100
= 12
c = a | b; 0011 1101
= 61
c = a ^ b; 0011 0001
= 49
c = ~a; 1100 0011
= -61
c = a << 2; 1111 0000 =

Misc Operators
sizeof():Returns the size of the variable
& :Returns the address of a variable
* :Pointer variable
?: :Conditional / Ternary operator

Operator Precedence
e = (a + b) * c / d;
// Print value of e
e = ((a + b) * c) / d;
// Print value of e
e = (a + b) * (c / d);
// Print value of e
e = a + (b * c) / d;
// Print value of e
inta = 20, b = 10, c = 15, d = 5;
inte;
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
( 30 * 15 ) / 5
(30 * 15 ) / 5
(30) * (15/5)
20 + (150/5)
associativityof operators determines the direction in which an
expression is evaluated. Example, b = a;
associativityof the = operator is from right to left (RL).

OperatorDescription Associativity
()
[ ]
.

Parentheses (grouping)
Brackets (array subscript)
Member selection
Member selection via pointer
LR
++--
+-
!~
(type)
*
&
sizeof
Unary preincrement/predecrement
Unary plus/minus
Unary logical negation/bitwise
complement
Unary cast (change type)
Dereference
Address
Determine size in bytes
RL
= Assignment operator

Arithmetic Operators
Multiplication operator,Divide
by,Modulus
*, /, %LR
Add,Subtract +, –LR
Relational Operators
Less Than <
LR
Greater than >
Less than equal to <=
Greater than equal to >=
Equal to ==
Not equal !=
Logical Operators
AND &&LR
OR ||LR
NOT !RL
1 == 2 != 3
operators == and
!= have the same
precedence, LR
Hence, 1 == 2 is
executed first

Hungarian Notation
Hungarian is a naming convention for identifiers. Each identifier
would have two parts to it, a typeand a qualifier.
Each address stores one element of the memory array. Each
element is typically one byte.
For example, suppose you have a 32-bit quantity written as
12345678, which is hexadecimal.
Since each hex digit is four bits, eight hex digits are needed to
represent the 32-bit value. The four bytes are: 12, 34, 56, and 78.
There are two ways to store in memory: Bigendianand little endian

Endianness
The endiannessof a particular computer system is
generally described by whatever convention or set of
conventions is followed by a particular processor or
combination of processor/architecture and possibly
operating system or transmission medium for the
addressing of constants and the representations of
memory addresses.
Often referred to as byte order

Big Endianstorage
Big-endian: Stores most significant byte in smallest address.
The following shows how 12345678 is stored in big endian
Big EndianStorage
Address Value
1000 12
1001 34
1002 56
1003 78

Little Endianstorage
Little-endian: Stores least significant byte in smallest
address.
The following shows how 12345678 is stored in big
endian
Little EndianStorage
Address Value
1000 78
1001 56
1002 34
1003 12

For example 4A3B2C1D at address 100, they store
the bytes within the address range 100 through 103
in the following order:m

Type Casting
Type casting is a way to convert a variable from
one data type to another data type.
Implicit Conversions
Explicit Conversions

Implicit Conversions
intmain()
{
inti= 17;
char c = 'c'; /* asciivalue is 99 */
intsum;
sum = i+ c;
printf("Value of sum : %d\n", sum );
}

Explicit Conversions
General format / Syntax:
(type_name) expression
Example:
main()
{
intsum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %lf\n", mean );
}

Examples: Type Conversions
float a = 5.25;
intb = (int)a;
char c = ‟A‟;
intx = (int)c;
intx=7, y=5;
floatz;
z=x/y;
intx=7, y=5;
floatz;
z = (float)x/(float)y;

Loop Example: Multiplication table
intmain()
{
intn, i;
printf("Enter no. to print multiplication table: ");
scanf("%d",&n);
for(i=1;i<=10;++i)
{
printf("%d * %d = %d\n", n, i, n*i);
}
}

break Statement
ThebreakstatementinCprogramminglanguagehasthe
followingtwousages:
Whenthebreakstatementisencounteredinsidealoop,theloop
isimmediatelyterminatedandprogramcontrolresumesatthe
nextstatementfollowingtheloop.
Itcanbeusedtoterminateacaseintheswitchstatement
Ifyouareusingnestedloops,thebreakstatementwillstopthe
executionoftheinnermostloopandstartexecutingthenextline
ofcodeaftertheblock.
Syntax:
break;

inta = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
OUTPUT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

intnum =0;
while(num<=100)
{
printf("value of variable num is: %d\n", num);
if (num==2)
{
break;
}
num++;
}
printf("Out of while-loop");
Output:
value of variable num is: 0
value of variable num is: 1
value of variable num is: 2
Out of while-loop

intvar;
for (var=100; var>=10; var--)
{
printf("var: %d\n", var);
if (var==99)
{
break;
}
}
printf("Out of for-loop");
Output:
var: 100
var: 99
Out of for-loop

inta = 4;
while( a < 10 )
{
printf("value of a: %d\n", a);
++a;
if( a > 8)
{
break;
printf("Break\n");
}
printf("Hello\n");
}
printf("Out of While loop\n");
}

continue
The continuestatement in C programming
language works somewhat like the break
statement.
Instead of forcing termination, continue
statement forces the next iteration of the loop
to take place, skipping any code in between.

inta = 10;
do {
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 20 );
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

for (intj=0; j<=8; j++)
{
if (j==4)
{
continue;
}
printf("%d ", j);
}
Output:
0 1 2 3 5 6 7 8

intcounter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
printf("%d ", counter);
counter--;
}
Output:
10 9 8 6 5 4 3 2 1 0

inta = 10;
do
{
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 20 );

gotostatement
The gotostatement is used to alter the normal sequence of
program execution by transferring control to some other part of
the program unconditionally.
Syntax:gotolabel;
Control may be transferred to anywhere within the current
function.
The target statement must be labeled, and a colon must follow
the label.
label : statement;

intw;
printf("Enter the input 1 or 0:\n");
scanf("%d", &w);
if (w == 1)
gotoCST;
if (w == 0) printf("Value entered is 0\n");
return 0;
CST : printf("You belong to CST Section\n");
gotoend;
end : printf("Have a nice Day\n");
return 0;
}

Example: Nested Loop
inti, j;
for(i=2; i<10; i++)
{
for(j=2; j <= (i/j); j++)
if(!(i%j)) break;
if(j > (i/j)) printf("%d is prime\n", i);
}

Program to check alphabet, digit or special character
if((ch>= 'a' && ch<= 'z') || (ch>= 'A' && ch<= 'Z'))
printf("'%c' is alphabet.", ch);
else if(ch>= '0' && ch<= '9')
printf("'%c' is digit.", ch);
else
printf("'%c' is special character.", ch);
Alphabet: a to z (or) A to Z
Digit : 0 to 9
else it is special character

Program to check vowel of consonant
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' ||
ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U')
{
printf("'%c' is Vowel.", ch);
}
else if((ch>= 'a' && ch<= 'z') || (ch>= 'A' && ch<= 'Z'))
printf("'%c' is Consonant.", ch);
else printf("'%c' is not an alphabet.", ch);
Vowel : a (or)e (or)i(or)o (or)u
Consonant : a to z orA to Z
else: not an alphabet

Sum of digits of given number using while
sum = 0;
// Accept number and store in n
num = n;
while( n > 0 )
{
rem= n % 10;
sum += rem;
n /= 10;
}
printf("Sum of digits of %d is %d", num, sum);
OUTPUT
Enter a number: 456
Sum of digits of 456 is 15

Sum of digits of given number using while
sum = 0;
// Accept number and store in n
num = n;
while( n > 0 )
{
rem= n % 10;
sum += rem;
n /= 10;
}
printf("Sum of digits of %d is %d", num, sum);
OUTPUT
Enter a number: 456
Sum of digits of 456 is 15

Print all ODD numbers from 1 to N using while loop.
number=1;
while(number<=n)
{
if(number%2 != 0)
printf("%d ",number);
number++;
}

Print its multiplication table
i=1;
while(i<=10)
{
printf("%d\n",(num*i));
i++;
}

count total digits in a given integer using loop
do
{
count++;
num /= 10;
} while(num != 0);
printf("Total digits: %d", count);

Program to print numbers between 1 and 100 which
are multiple of 3 using the do while loop
inti= 1;
do
{
if(i% 3 == 0)
{
printf("%d ", i);
}
i++;
}while(i< 100);

find sum of odd numbers from 1 to n
for(i=1; i<=n; i+=2)
{
sum += i;
}
printf("Sum of odd numbers = %d", sum);

Exponential series
inti, n;
float x, sum=1, t=1;
// Accept x
// Accept n
for(i=1;i<=n;i++)
{
t=t*x/i;
sum=sum+t;
}
printf(“Exponential Value of %f = %.4f", x, sum);

Program to print its multiplication table
i=1;
while(i<=10)
{
printf("%d\n",(num*i));
i++;
}
i=1;
do
{
printf("%d\n",(num*i));
i++;
}while(i<=10);
for(i=1;i<=10;i++)
{
printf("%d\n",(num*i));
}

k = 1;
for(i=1; i<=rows; i++)
{
for( j=1; j<=cols; j++, k++)
{
printf("%-3d", k);
}
printf("\n");
}
Print number patternas shown

intmain()
{
inti;
for (i=0; i<10; i++)
{
printf("i=%d\n",i);
}
return 0;
}

Factorial using for loop
fact=1;
for(i=num; i>=1; i--)
fact=fact*i;
printf("Factorial of %d is = %ld",num,fact);

Sum of n natural no‟s using for
sum = 0;
for(i= 1; i<= n; i++)
sum += i;
printf("Sum is: %d\n", sum);

Program to print its multiplication table
i=1;
while(i<=10)
{
printf("%d\n",(num*i));
i++;
}
i=1;
do
{
printf("%d\n",(num*i));
i++;
}while(i<=10);
for(i=1;i<=10;i++)
{
printf("%d\n",(num*i));
}

Ex: 2: Nested for loop
for (int i=0; i<2; i++)
{
for (intj=0; j<4; j++)
{
printf("%d, %d\n",i ,j);
}
}

Ex: 3: Nested for loop
k=1;
for (i=0; i<2; i++)
{
for (j=0; j<4; j++,k++)
{
printf("%d, %d, %d\n",i ,j, k);
}
}

Print number pattern as shown
Output:
1
12
123
1234
for(i=1; i<=rows; i++)
{
for( j=1; j<=i; j++)
printf("%d", j);
printf("\n");
}

Structured vsUnstructured Programming
Structured Programming is a
programming paradigm which divides
the code into modules or function.
Unstructured Programming is the
paradigm in which the code is
considered as one single block.
Readability
Structured Programming based
programs are easy to read.
Unstructured Programming based
programs are hard to read.
Purpose
Structured Programming is to make the
code more efficient and easier to
understand.
Unstructured programming is just to
program to solve the problem. It does
not create a logical structure.
Complexity
Structured Programming is easier
because of modules.
Unstructured programming is harder
when comparing with the structured
programming

Application
Structured programming can be used for
small and medium scale projects.
Unstructured programming is not applicable
for medium and complex projects.
Modification
It is easy to do changes in Structured
Programming.
It is hard to do modifications in Unstructured
Programming.
Data Types
Structured programming uses many data
types.
Unstructured programming has a limited
number of data types.
Code Duplication
Structured programming avoids code
duplication.
Unstructured programming can have code
duplication.
Testing and Debug
It is easy to do testing and debugging in
Structured Programming.
It is hard to do testing and debugging in
Unstructured programming.

Palindrome number
rev=0
origin=n;
while (n != 0)
{
rem= n % 10;
rev = rev * 10 + rem;
n /= 10;
}
if (orig== rev) printf("%d is a palindrome.“,orig);
else printf("%d is not a palindrome.", orig);

inti, j;
for(i= 2; i<100; i++)
{
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
Print Prime numbers upto100

Fibonacci series
for(i=3;i<=n;i++)
{
trm=prv+pre;
printf("% 5d",trm);
prv=pre;
pre=trm;
}
printf("\n");

Palindrome number
rev=0
origin=n;
while (n != 0)
{
rem= n % 10;
rev = rev * 10 + rem;
n /= 10;
}
if (origin == rev) printf("%d is a palindrome.“,orig);
else printf("%d is not a palindrome.", orig);

gotostatement: Unstructured programming
The gotostatement is used to alter the normal sequence
of program execution by transferring control to some
other part of the program unconditionally.
Syntax:gotolabel;
Control may be transferred to anywhere within the
current function.
The target statement must be labeled, and a colon must
follow the label.
label : statement;
Tags