SlideShare a Scribd company logo
1 of 151
Download to read offline
Syllabus, Introduction
PROGRAMMING FOR
PROBLEM SOLVING (PPS)
B.Tech I Sem CST
Course Outcomes
 CO1: Understand fundamentals of problem solving concepts with
various data types and operators
 CO2: Apply conditional and iterative statements for solving a
given problem
 CO3: Illustrate the applications of functions and storage classes.
 CO4: Apply the concepts of pointers and dynamic memory
management in 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
Endian Big 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, goto labels,
 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,
Schaum Outline Series.
 1. C: The Complete Reference, Herbert Schildt,
Fourth Edition, McGraw Hill.
 2. Let Us C, Yashavant Kanetkar, 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 Endian Big 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.
 Output Should 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>
int main()
{
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.Tech I Sem „CST'
*/
#include<stdio.h>
// Main function begins
int main()
{
int num1,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,b and c.
Step 3: Read variables a,b and 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 empid and
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>
int main()
{
int empid;
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 x Y 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: Sequence Control 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
Sequence Ex: Calculate Person‟s age
Sequence Example
int main()
{
int first, 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. = %dn", first);
printf("After swapping, secondno. = %d", second);
}
Swap two
numbers
using temp
var
Sequence Example
int main()
{
int a, b;
printf("Enter a and b: ");
scanf("%d %d", &a, &b);
a = a - b;
b = a + b;
a = b - a;
printf("After swapping, a = %dn", 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
Selection Ex: Program to print the given
number is negative or positive using if else
int main()
{
int num;
printf("Enter a number to check.n");
scanf("%d",&num);
if (num<0)
printf(“Given Number = %d is negativen",num);
else
printf(“Given Number = %d is positiven",num);
return 0;
}
Selection Ex:
 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
Y
N
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
Selection Ex:
Selection Ex:
Program to check for odd or even
int main()
{
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num % 2 == 0)
printf("%d is even.", num);
else
printf("%d is odd.", num);
return 0;
}
Selection Ex: Program to check odd or
even using ternary operator ? :
int main()
{
int num;
printf("Enter an integer: ");
scanf("%d", &num);
(num % 2 == 0) ? printf("%d is even.", num) : printf("%d is odd.", num);
return 0;
}
Selection Ex: 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
Selection Ex: Find Largest of three numbers
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and 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
int main()
{
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
int main()
{
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
int main()
{
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;
}
int main()
{
int i;
for (i=0; i<10; i++)
{
printf("i=%dn",i);
}
return 0;
}
Loop Example: Multiplication table
int main()
{
int n, i;
printf("Enter no. to print multiplication table: ");
scanf("%d",&n);
for(i=1;i<=10;++i)
{
printf("%d * %d = %dn", n, i, n*i);
}
}
for(i = 0; i < 5; i++)
{
printf("tttt");
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 bytes 0 to 65535
unsigned int 4 bytes 0 to 4294967295
unsigned long int 4 bytes 0 to 4294967295
long double (extended precision) 8 bytes 1.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 int uses 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 Sequence ASCII 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
int main()
{
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
int a = 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
int a = 60;
int b = 13;
int c = 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
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
int a = 20, b = 10, c = 15, d = 5;
int e;
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)
associativity of operators determines the direction in which an
expression is evaluated. Example, b = a;
associativity of the = operator is from right to left (RL).
Operator Description 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 type and 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: Bigendian and little endian
Endianness
 The endianness of 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 Endian storage
 Big-endian: Stores most significant byte in smallest address.
 The following shows how 12345678 is stored in big endian
Big Endian Storage
Address Value
1000 12
1001 34
1002 56
1003 78
Little Endian storage
 Little-endian: Stores least significant byte in smallest
address.
 The following shows how 12345678 is stored in big
endian Little Endian Storage
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
int main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %dn", sum );
}
Explicit Conversions
General format / Syntax:
(type_name) expression
Example:
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %lfn", mean );
}
Examples: Type Conversions
float a = 5.25;
int b = (int)a;
char c = ‟A‟;
int x = (int)c;
int x=7, y=5 ;
float z;
z=x/y;
int x=7, y=5;
float z;
z = (float)x/(float)y;
Loop Example: Multiplication table
int main()
{
int n, i;
printf("Enter no. to print multiplication table: ");
scanf("%d",&n);
for(i=1;i<=10;++i)
{
printf("%d * %d = %dn", n, i, n*i);
}
}
break Statement
The break statement in C programming language has the
following two usages:
When the break statement is encountered inside a loop, the loop
is immediately terminated and program control resumes at the
next statement following the loop.
It can be used to terminate a case in the switch statement
If you are using nested loops, the break statement will stop the
execution of the innermost loop and start executing the next line
of code after the block.
Syntax:
break;
int a = 10;
while( a < 20 )
{
printf("value of a: %dn", 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
int num =0;
while(num<=100)
{
printf("value of variable num is: %dn", 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
int var;
for (var =100; var>=10; var --)
{
printf("var: %dn", var);
if (var==99)
{
break;
}
}
printf("Out of for-loop");
Output:
var: 100
var: 99
Out of for-loop
int a = 4;
while( a < 10 )
{
printf("value of a: %dn", a);
++a;
if( a > 8)
{
break;
printf("Breakn");
}
printf("Hellon");
}
printf("Out of While loopn");
}
continue
 The continue statement 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.
int a = 10;
do {
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %dn", 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 (int j=0; j<=8; j++)
{
if (j==4)
{
continue;
}
printf("%d ", j);
}
Output:
0 1 2 3 5 6 7 8
int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
printf("%d ", counter);
counter--;
}
Output:
10 9 8 6 5 4 3 2 1 0
int a = 10;
do
{
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %dn", a);
a++;
} while( a < 20 );
goto statement
 The goto statement is used to alter the normal sequence of
program execution by transferring control to some other part of
the program unconditionally.
 Syntax: goto label;
 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;
int w;
printf("Enter the input 1 or 0:n");
scanf("%d", &w);
if (w == 1)
goto CST;
if (w == 0) printf("Value entered is 0n");
return 0;
CST : printf("You belong to CST Sectionn");
goto end;
end : printf("Have a nice Dayn");
return 0;
}
Example: Nested Loop
int i, 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 primen", 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 or A 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("%dn",(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
int i = 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
int i, 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("%dn",(num*i));
i++;
}
i=1;
do
{
printf("%dn",(num*i));
i++;
}while(i<=10);
for(i=1;i<=10;i++)
{
printf("%dn",(num*i));
}
k = 1;
for(i=1; i<=rows; i++)
{
for( j=1; j<=cols; j++, k++)
{
printf("%-3d", k);
}
printf("n");
}
Print number pattern as shown
int main()
{
int i;
for (i=0; i<10; i++)
{
printf("i=%dn",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: %dn", sum);
Program to print its multiplication table
i=1;
while(i<=10)
{
printf("%dn",(num*i));
i++;
}
i=1;
do
{
printf("%dn",(num*i));
i++;
}while(i<=10);
for(i=1;i<=10;i++)
{
printf("%dn",(num*i));
}
Ex: 2: Nested for loop
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
printf("%d, %dn",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, %dn",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 vs Unstructured 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);
int i, 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 primen", i);
}
Print Prime numbers upto 100
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);
goto statement: Unstructured programming
 The goto statement is used to alter the normal sequence
of program execution by transferring control to some
other part of the program unconditionally.
 Syntax: goto label;
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;
Programming For Problem Solving Lecture Notes

More Related Content

What's hot

Strings in c
Strings in cStrings in c
Strings in cvampugani
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
language , grammar and automata
language , grammar and automatalanguage , grammar and automata
language , grammar and automataElakkiyaS11
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in cPrabhu Govind
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, RecursionSreedhar Chowdam
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Saket Pathak
 
358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6sumitbardhan
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and outputOnline
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)swapnac12
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structureSajid Marwat
 
Practical File of C Language
Practical File of C LanguagePractical File of C Language
Practical File of C LanguageRAJWANT KAUR
 

What's hot (20)

Strings in c
Strings in cStrings in c
Strings in c
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Basic Input and Output
Basic Input and OutputBasic Input and Output
Basic Input and Output
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
language , grammar and automata
language , grammar and automatalanguage , grammar and automata
language , grammar and automata
 
Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
 
358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
 
Strings
StringsStrings
Strings
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structure
 
Practical File of C Language
Practical File of C LanguagePractical File of C Language
Practical File of C Language
 

Similar to Programming For Problem Solving Lecture Notes

Similar to Programming For Problem Solving Lecture Notes (20)

C material
C materialC material
C material
 
GE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdfGE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdf
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
 
3 algorithm-and-flowchart
3 algorithm-and-flowchart3 algorithm-and-flowchart
3 algorithm-and-flowchart
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 
17 pcds syllabus
17 pcds syllabus17 pcds syllabus
17 pcds syllabus
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
GE3151_PSPP_All unit _Notes
GE3151_PSPP_All unit _NotesGE3151_PSPP_All unit _Notes
GE3151_PSPP_All unit _Notes
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02
 
Problem solving methodology
Problem solving methodologyProblem solving methodology
Problem solving methodology
 
C++
C++C++
C++
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).ppt
 
Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
C program
C programC program
C program
 
Programming for problem solving ppts unit 1
Programming for problem solving ppts unit 1Programming for problem solving ppts unit 1
Programming for problem solving ppts unit 1
 
Visual Basic Review - ICA
Visual Basic Review - ICAVisual Basic Review - ICA
Visual Basic Review - ICA
 
C AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDYC AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDY
 
Lecture 3.2.4 C pointer to Structure.pptx
Lecture 3.2.4 C pointer to Structure.pptxLecture 3.2.4 C pointer to Structure.pptx
Lecture 3.2.4 C pointer to Structure.pptx
 

More from Sreedhar Chowdam

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesSreedhar Chowdam
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Sreedhar Chowdam
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPSreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer NetworksSreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer NetworksSreedhar Chowdam
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operationsSreedhar Chowdam
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem SolvingSreedhar Chowdam
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsSreedhar Chowdam
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfSreedhar Chowdam
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming StringsSreedhar Chowdam
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021Sreedhar Chowdam
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Sreedhar Chowdam
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library databaseSreedhar Chowdam
 
Er diagram for library database
Er diagram for library databaseEr diagram for library database
Er diagram for library databaseSreedhar Chowdam
 

More from Sreedhar Chowdam (20)

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCP
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
 
DCCN Unit 1.pdf
DCCN Unit 1.pdfDCCN Unit 1.pdf
DCCN Unit 1.pdf
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Big Data Analytics Part2
Big Data Analytics Part2Big Data Analytics Part2
Big Data Analytics Part2
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming Strings
 
Python Programming
Python Programming Python Programming
Python Programming
 
Big Data Analytics
Big Data AnalyticsBig Data Analytics
Big Data Analytics
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library database
 
Er diagram for library database
Er diagram for library databaseEr diagram for library database
Er diagram for library database
 
Dbms ER Model
Dbms ER ModelDbms ER Model
Dbms ER Model
 

Recently uploaded

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 

Recently uploaded (20)

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 

Programming For Problem Solving Lecture Notes

  • 1. Syllabus, Introduction PROGRAMMING FOR PROBLEM SOLVING (PPS) B.Tech I Sem CST
  • 2. Course Outcomes  CO1: Understand fundamentals of problem solving concepts with various data types and operators  CO2: Apply conditional and iterative statements for solving a given problem  CO3: Illustrate the applications of functions and storage classes.  CO4: Apply the concepts of pointers and dynamic memory management in problem solving.  CO5: Understand the purpose of structures, unions and files.
  • 3. 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 Endian Big 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
  • 4. 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, goto labels,  structured and un-structured programming
  • 5. 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.
  • 6. 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
  • 7. 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
  • 8. 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, Schaum Outline Series.  1. C: The Complete Reference, Herbert Schildt, Fourth Edition, McGraw Hill.  2. Let Us C, Yashavant Kanetkar, BPB Publications
  • 9. 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
  • 10. 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.
  • 11. 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
  • 12. C is a programming language developed at Bell Laboratories of USA in 1972 by Dennis Ritchie
  • 13.  C is a programming language developed at Bell Laboratories of USA in 1972 by Dennis Ritchie
  • 14.
  • 18. Decimal to Binary 156 (10) 10011100 (2)
  • 19. Binary representation (Decimal to Binary Decimal no.= 123 Binary no. = 1111011 Decimal no. = 255 Binary no. = 1111 1111 Decimal no. = 486 Binary no. = 111100110
  • 24. Binary to Decimal Binary no. = 110011 Decimal no. = 51 Binary no. = 1111 0001 Decimal no. = 241
  • 25. 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 Endian Big 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
  • 26. Algorithm  Algorithm is a finite set of instructions that if followed accomplishes a particular task. Algorithm Input Output Problem Computer
  • 27. Problem: Shortest distance Input n nodes connecting nodes distance between nodes Output Shortest distance: 18
  • 32. 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.
  • 33. Characteristics of Algorithm  Input − Should have 0 or more well-defined inputs.  Output Should 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.
  • 34. Program to display “Welcome to C” #include<stdio.h> int main() { printf(“Welcome to C”); return 0; }
  • 35. 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
  • 36. 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.Tech I Sem „CST' */
  • 37. #include<stdio.h> // Main function begins int main() { int num1,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; }
  • 38. 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
  • 39. 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
  • 40. Ex4: Find Largest of three numbers Step 1: Start Step 2: Declare variables a,b and c. Step 3: Read variables a,b and 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
  • 41. Ex5: Calculate Gross, Net Salary  Problem:  Accept the employee details such as empid and 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.
  • 42. 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
  • 43. 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
  • 44. #include<stdio.h> int main() { int empid; 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; }
  • 45. Ex 6: Calculate Simple Interest  Si = (P * T * R) / 100
  • 46. 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.
  • 47. Flowchart  Flowchart is the pictorial representation of an algorithm
  • 48. 49 Identify  What do each of the following symbols represent? Terminal Input/Output Operation Process Decision Connector Module
  • 49. 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 x Y x Z  Step 6: Print S, A, P  Step 7: Stop
  • 50. 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
  • 51. 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)
  • 52. Ex: Sequence Control 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
  • 53. Sequence Ex: Calculate Person‟s age
  • 54. Sequence Example int main() { int first, 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. = %dn", first); printf("After swapping, secondno. = %d", second); } Swap two numbers using temp var
  • 55. Sequence Example int main() { int a, b; printf("Enter a and b: "); scanf("%d %d", &a, &b); a = a - b; b = a + b; a = b - a; printf("After swapping, a = %dn", a); printf("After swapping, b = %d", b); return 0; } Swap two numbers without using temp var
  • 56. Selection (Decision) Control structure is condition Y N Print stmt1 Print stmt2
  • 57. 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
  • 58. Selection Ex: Program to print the given number is negative or positive using if else int main() { int num; printf("Enter a number to check.n"); scanf("%d",&num); if (num<0) printf(“Given Number = %d is negativen",num); else printf(“Given Number = %d is positiven",num); return 0; }
  • 59. Selection Ex:  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
  • 60. START Input M1,M2,M3,M4 GRADE(M1+M2+M3+M4)/4 IS GRADE>60 STOP Y N 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 Selection Ex:
  • 61. Selection Ex: Program to check for odd or even int main() { int num; printf("Enter an integer: "); scanf("%d", &num); if (num % 2 == 0) printf("%d is even.", num); else printf("%d is odd.", num); return 0; }
  • 62. Selection Ex: Program to check odd or even using ternary operator ? : int main() { int num; printf("Enter an integer: "); scanf("%d", &num); (num % 2 == 0) ? printf("%d is even.", num) : printf("%d is odd.", num); return 0; }
  • 63. Selection Ex: 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
  • 65. Selection Ex: Find Largest of three numbers Step 1: Start Step 2: Declare variables a,b and c. Step 3: Read variables a,b and 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
  • 66. int main() { 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
  • 67. int main() { 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
  • 68. int main() { 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
  • 70. Loop: for for(initialization, condition, incrementation) { code statements; } int main() { int i; for (i=0; i<10; i++) { printf("i=%dn",i); } return 0; }
  • 71. Loop Example: Multiplication table int main() { int n, i; printf("Enter no. to print multiplication table: "); scanf("%d",&n); for(i=1;i<=10;++i) { printf("%d * %d = %dn", n, i, n*i); } }
  • 72.
  • 73. for(i = 0; i < 5; i++) { printf("tttt"); for(j = 0; j < 5; j++) printf("* "); printf("n"); }
  • 74. 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.
  • 76. C basic elements  Valid character set  Identifiers  Keywords  Basic data types  Constants  Variables
  • 77. 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.
  • 78. 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.
  • 79. 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
  • 81. 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
  • 82. 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 bytes 0 to 65535 unsigned int 4 bytes 0 to 4294967295 unsigned long int 4 bytes 0 to 4294967295 long double (extended precision) 8 bytes 1.7E-308 to1.7E+308
  • 83. 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 int uses L (uppercase or lowercase) at the end of the constant, e.g. 2748723L  C also supports octal and hexadecimal data. Ex: 0xC
  • 84. Escape sequence characters Character Escape Sequence ASCII 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
  • 85. Symbolic constants  #define PI 3.141593  #define TRUE 1  #define PROMPT "Enter Your Name :"
  • 86. 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);
  • 87. Accept name from the user Method 3 #define MAX_LIMIT 20 int main() { 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);
  • 88. Operators in C  Arithmetic operators  Relational operators  Logical operators  Bitwise operators  Assignment operators  Misc operators
  • 89.
  • 90. int a = 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
  • 91.
  • 92.
  • 93.
  • 94.
  • 95. Example: Bitwise Operators int a = 60; int b = 13; int c = 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
  • 96.
  • 97. Misc Operators sizeof() : Returns the size of the variable & : Returns the address of a variable * : Pointer variable ?: : Conditional / Ternary operator
  • 98. 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 int a = 20, b = 10, c = 15, d = 5; int e; 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) associativity of operators determines the direction in which an expression is evaluated. Example, b = a; associativity of the = operator is from right to left (RL).
  • 99. Operator Description 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
  • 100. 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
  • 101. Hungarian Notation  Hungarian is a naming convention for identifiers. Each identifier would have two parts to it, a type and 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: Bigendian and little endian
  • 102. Endianness  The endianness of 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
  • 103. Big Endian storage  Big-endian: Stores most significant byte in smallest address.  The following shows how 12345678 is stored in big endian Big Endian Storage Address Value 1000 12 1001 34 1002 56 1003 78
  • 104. Little Endian storage  Little-endian: Stores least significant byte in smallest address.  The following shows how 12345678 is stored in big endian Little Endian Storage Address Value 1000 78 1001 56 1002 34 1003 12
  • 105.  For example 4A3B2C1D at address 100, they store the bytes within the address range 100 through 103 in the following order:m
  • 106. Type Casting  Type casting is a way to convert a variable from one data type to another data type.  Implicit Conversions  Explicit Conversions
  • 107. Implicit Conversions int main() { int i = 17; char c = 'c'; /* ascii value is 99 */ int sum; sum = i + c; printf("Value of sum : %dn", sum ); }
  • 108. Explicit Conversions General format / Syntax: (type_name) expression Example: main() { int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean : %lfn", mean ); }
  • 109. Examples: Type Conversions float a = 5.25; int b = (int)a; char c = ‟A‟; int x = (int)c; int x=7, y=5 ; float z; z=x/y; int x=7, y=5; float z; z = (float)x/(float)y;
  • 110. Loop Example: Multiplication table int main() { int n, i; printf("Enter no. to print multiplication table: "); scanf("%d",&n); for(i=1;i<=10;++i) { printf("%d * %d = %dn", n, i, n*i); } }
  • 111. break Statement The break statement in C programming language has the following two usages: When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. Syntax: break;
  • 112. int a = 10; while( a < 20 ) { printf("value of a: %dn", 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
  • 113. int num =0; while(num<=100) { printf("value of variable num is: %dn", 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
  • 114. int var; for (var =100; var>=10; var --) { printf("var: %dn", var); if (var==99) { break; } } printf("Out of for-loop"); Output: var: 100 var: 99 Out of for-loop
  • 115. int a = 4; while( a < 10 ) { printf("value of a: %dn", a); ++a; if( a > 8) { break; printf("Breakn"); } printf("Hellon"); } printf("Out of While loopn"); }
  • 116. continue  The continue statement 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.
  • 117. int a = 10; do { if( a == 15) { a = a + 1; continue; } printf("value of a: %dn", 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
  • 118. for (int j=0; j<=8; j++) { if (j==4) { continue; } printf("%d ", j); } Output: 0 1 2 3 5 6 7 8
  • 119. int counter=10; while (counter >=0) { if (counter==7) { counter--; continue; } printf("%d ", counter); counter--; } Output: 10 9 8 6 5 4 3 2 1 0
  • 120. int a = 10; do { if( a == 15) { a = a + 1; continue; } printf("value of a: %dn", a); a++; } while( a < 20 );
  • 121. goto statement  The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally.  Syntax: goto label;  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;
  • 122. int w; printf("Enter the input 1 or 0:n"); scanf("%d", &w); if (w == 1) goto CST; if (w == 0) printf("Value entered is 0n"); return 0; CST : printf("You belong to CST Sectionn"); goto end; end : printf("Have a nice Dayn"); return 0; }
  • 123. Example: Nested Loop int i, 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 primen", i); }
  • 124. 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
  • 125. 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 or A to Z else: not an alphabet
  • 126. 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
  • 127. 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
  • 128. Print all ODD numbers from 1 to N using while loop. number=1; while(number<=n) { if(number%2 != 0) printf("%d ",number); number++; }
  • 129. Print its multiplication table i=1; while(i<=10) { printf("%dn",(num*i)); i++; }
  • 130. count total digits in a given integer using loop do { count++; num /= 10; } while(num != 0); printf("Total digits: %d", count);
  • 131. Program to print numbers between 1 and 100 which are multiple of 3 using the do while loop int i = 1; do { if(i % 3 == 0) { printf("%d ", i); } i++; }while(i < 100);
  • 132. 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);
  • 133. Exponential series int i, 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);
  • 134. Program to print its multiplication table i=1; while(i<=10) { printf("%dn",(num*i)); i++; } i=1; do { printf("%dn",(num*i)); i++; }while(i<=10); for(i=1;i<=10;i++) { printf("%dn",(num*i)); }
  • 135. k = 1; for(i=1; i<=rows; i++) { for( j=1; j<=cols; j++, k++) { printf("%-3d", k); } printf("n"); } Print number pattern as shown
  • 136. int main() { int i; for (i=0; i<10; i++) { printf("i=%dn",i); } return 0; }
  • 137. Factorial using for loop fact=1; for(i=num; i>=1; i--) fact=fact*i; printf("Factorial of %d is = %ld",num,fact);
  • 138. Sum of n natural no‟s using for sum = 0; for(i = 1; i <= n; i++) sum += i; printf("Sum is: %dn", sum);
  • 139. Program to print its multiplication table i=1; while(i<=10) { printf("%dn",(num*i)); i++; } i=1; do { printf("%dn",(num*i)); i++; }while(i<=10); for(i=1;i<=10;i++) { printf("%dn",(num*i)); }
  • 140. Ex: 2: Nested for loop for (int i=0; i<2; i++) { for (int j=0; j<4; j++) { printf("%d, %dn",i ,j); } }
  • 141. Ex: 3: Nested for loop k=1; for (i=0; i<2; i++) { for (j=0; j<4; j++,k++) { printf("%d, %d, %dn",i ,j, k); } }
  • 142. 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"); }
  • 143. Structured vs Unstructured 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
  • 144. 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.
  • 145.
  • 146. 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);
  • 147. int i, 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 primen", i); } Print Prime numbers upto 100
  • 149. 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);
  • 150. goto statement: Unstructured programming  The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally.  Syntax: goto label; 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;