0% found this document useful (0 votes)
21 views71 pages

Problem Solving Using C NVG

The document provides an overview of the C programming language, including its history, features, and importance in modern programming. It covers fundamental concepts such as algorithms, pseudocode, flowcharts, data types, variables, and operators in C. Additionally, it discusses the structure of a C program, comments, keywords, and the types of variables available.

Uploaded by

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

Problem Solving Using C NVG

The document provides an overview of the C programming language, including its history, features, and importance in modern programming. It covers fundamental concepts such as algorithms, pseudocode, flowcharts, data types, variables, and operators in C. Additionally, it discusses the structure of a C program, comments, keywords, and the types of variables available.

Uploaded by

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

PROBLEM SOLVING USING C

Subject Code : UGCA1903

Course Instructor : Navkiran Kaur Gill


Email : [email protected]

PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY 1


TIMELINE

1960 1967 1969 1972

ALGOL BCPL B C

Algorithmic Language Basic Combined


Programming Language

PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY 2


➢ General purpose programming language
➢ Developed by Dennis Ritchie in 1972
➢ Created at Bell Labs, USA
➢ Originally designed for UNIX development

3
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
WHY SHOULD I LEARN C PROGRAMMING ?
➢ Foundation for Other Modern Languages
➢ System Level Programming
➢ Embedded Systems Development
➢ Core to Software Development
➢ Scientific and Engineering Libraries

4
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
FEATURES
OF C
LANGUAGE

5
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
6
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
ALGORITHM

An algorithm is a finite set of unambiguous instructions which, when


executed, performs a task correctly.

7
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
EXAMPLE
ALGORITHM ADD TWO NUMBERS

Step 0 : START
Step 1 : INPUT first number into variable A
Step 2 : INPUT second number into variable B
Step 3 : COMPUTE SUM = A + B
Step 4 : DISPLAY SUM
Step 5 : END

8
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
PSEUDOCODE
It is a means to represent an algorithm in coded form.

➢ Informal way of writing a program


➢ Written in English
➢ Cannot be compiled or interpreted
➢ Does not follow any syntax

9
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
EXAMPLE
PSEUDOCODE SUM OF TWO NUMBERS

SUM_TWO {
PRINT “Enter a value for number A : “
SCAN A
PRINT “Enter a value for number B : “
SCAN B
SUM A + B
PRINT “The sum is : “, SUM

10
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
PSEUDOCODE
ADVANTAGES DISADVANTAGES

● Easier to write ● Lacks graphical or visual

● Takes less time and effort


representation
● Bridge between algorithm and

program ● Lack of standardization

● Changes in logic can be easily


● Difficult to implement for beginners
modified 11
FLOWCHART

It is the graphical representation of an algorithm.

12
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
NOTATIONS USED IN FLOWCHART
SYMBOL
NAME

Terminal Symbol

Input / Output Box

Process Box

Decision Box

Arrows

Connector

Off-Page Connector
13
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
EXAMPLE
Start

Input A

FLOWCHART Input B
ADD TWO NUMBERS

SUM = A + B

Display SUM

End

14
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
FLOWCHART
ADVANTAGES DISADVANTAGES

● Easier technique to understand logic ● Time consuming

● Easy to draw ● Difficult to modify

● Easy to identify logical errors ● Difficult to draw for huge programs

● Makes testing & debugging easier


15
TRANSLATORS
1. COMPILER

➢ Translates the whole program


➢ Detects all errors at once

2. INTERPRETER
➢ Translates line by line
➢ Detects errors in current line

16
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
THE C COMPILER
➢ The source code written in the source file is the human-readable version
of your program

➢ It needs to be “compiled” into machine language

➢ The compiler compiles the source code into final executable program

17
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
18
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
STRUCTURE OF A C PROGRAM

19
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
C PROGRAM STRUCTURE
A C program basically consists of the following parts
➢ Preprocessor Commands

➢ Functions

➢ Variables

➢ Statements & Expressions

➢ Comments

20
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
COMMENTS
➢ Used to explain code, make it more readable
➢ Prevent execution when testing alternative code
➢ Comments can be classified as follows :
■ Single - line
○ Starts with two forward slashes - //
■ Multi - line
○ Starts with /* and ends with */
21
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
EXAMPLE OF COMMENTS
➢ // This is a single line comment
printf(“HELLO WORLD !”);
➢ /*
This is a multi line comment :
This code will print the words HELLO WORLD ! to the screen
*/
printf(“HELLO WORLD!”);
22
CHARACTER SET
➢ Set of all valid characters that can be used in source program

to form words, expressions, etc.

➢ C provides support to about 256 characters

23
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
CHARACTER SET INCLUDES
1. Alphabetical Characters
➢ Uppercase Letters : A - Z
➢ Lowercase Letters : a - z
2. Digits
➢ 0-9

24
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
CHARACTER SET INCLUDES
3. Special Characters

➢ !, ", #, $, %, &, ', (, ), *, +, ,, -, . /', :, ;, <, =, >,

?, @, [, `, ], ^, _, `, {, |, }, ~

4. Whitespaces

➢ Blank Space
➢ New Line
➢ Tab 25
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
ASCII
AMERICAN STANDARD CODE FOR INFORMATION INTERCHANGE

➢ Used to represent characters in standardized way


➢ Every character is associated with a unique numerical value
➢ Like
● A = 65, B = 66 , ..
● a = 97 , b = 98 , ..
● 0 = 48 , 1 = 49 , ..
26
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
KEYWORDS IN C

➢ Keywords are reserved words

➢ They have a special meaning to the compiler

➢ They cannot be used as identifiers

27
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
KEYWORDS IN C
There are 32 keywords in C Language

28
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
IDENTIFIERS IN C
➢ Names used to identify variables, functions, etc.

➢ Rules for naming identifiers are as follows :

○ Must begin with a letter or underscore ( _ )

○ Can contain alphabets, digits or underscores

○ Case-sensitive

○ No special characters except underscore are allowed

○ No reserved words or keywords can be used

○ No white spaces are allowed 29


QUIZ
Determine if the following identifiers are valid or invalid according to
C programming rules .

1. _count 6. float

2. highScore 7. float_number_1

3. total_value_ 8. sum#

4. _number_ 9. number 1

5. 2ndNumber 10. intValue1_


30
QUIZ
Determine if the following identifiers are valid or invalid according to
C programming rules .
1. _count VALID 6. float INVALID

2. 2ndNumber INVALID 7. float_number_1 VALID

3. total_value_ VALID 8. sum# INVALID

4. number 1 INVALID 9. _number_1 VALID

5. highScore VALID 10. intValue1_ VALID


31
DATA TYPES IN C
➢ Used to specify the type of data a variable can hold

➢ Types are as follows :

○ Primary Data Types - int, float, char, double

○ Derived Data Types - arrays, pointers, structures, unions

○ User-defined Data Types - enum

32
PRIMARY DATA TYPES
1. INT
➢ Used to store integers ( both positive and negative )
➢ Each int variable takes upto 4 bytes of memory ( 32 bits )
➢ Int can be classified as :
a. Signed
○ Range : -2,147,483,648 to 2,147,483,647
b. Unsigned :
○ Range : 0 to 4,294,967,295
➢ short int ( 2 bytes )
➢ long int ( 8 bytes ) 33
PRIMARY DATA TYPES
2. FLOAT
➢ Used to store single precision floating-point numbers (decimals)
➢ Size : 4 bytes of memory ( 32 bits )
➢ Precision : 6 - 7 decimal digits

3. DOUBLE
➢ Size : 8 bytes
➢ Precision : 15 - 16 decimal digits
➢ long double ( 10, 12 or 16 bytes )
34
PRIMARY DATA TYPES
4. CHAR
➢ Used to store a single character
➢ Each char variable takes upto 1 byte of memory ( 8 bits )
➢ Char can be classified as :
a. Signed
○ Range : -128 to 127
b. Unsigned :
○ Range : 0 to 255

35
VARIABLES IN C

➢ Variable is a name of the memory location

➢ It is used to store data

➢ Its value can be changed

➢ It can be reused

36
TYPES OF VARIABLES IN C

1. LOCAL VARIABLES

➢ Definition : Declared inside a function or block

➢ Scope : Accessible only within that function or block

➢ Lifetime : Exist only during the execution of that function

or block
37
TYPES OF VARIABLES IN C

2. GLOBAL VARIABLES

➢ Definition : Declared outside of all functions, usually at top

➢ Scope : Accessible from any function within the program

➢ Lifetime : Exist for the entire duration of the program’s

execution
38
TYPES OF VARIABLES IN C
3. STATIC VARIABLES

➢ Definition : Declared with the ‘ static ’ keyword

➢ Scope : Accessible from

○ within the function or block ( STATIC LOCAL )

○ within the program ( STATIC GLOBAL )

➢ Lifetime : Retain their value between function calls, and exist

for the duration of the program 39


TYPES OF VARIABLES IN C
4. AUTOMATIC VARIABLES

➢ Variables that are automatically created and destroyed when a

block is entered or exited

➢ All variables declared inside a block ( LOCAL ) are automatic by

default

➢ Declared using ‘ auto ‘ keyword

40
TYPES OF VARIABLES IN C
5. EXTERNAL VARIABLES

➢ Variables declared outside of a function and intended to be

shared across multiple files

➢ Accessible from any file where it is declared using ‘ extern ‘

keyword

➢ Exist for the entire duration of the program


41
TYPES OF VARIABLES IN C

6. REGISTER VARIABLES

➢ Variables stored in CPU registers for faster access

➢ Local to block or function where they are declared

➢ Declared using ‘ register ‘ keyword

42
CONSTANTS IN C

➢ Fixed values that do not change during program execution

➢ Declared using ‘ const ‘ keyword

➢ Eg const int roll_no = 2026601 ;

43
SYMBOLIC CONSTANTS IN C

➢ Constants defined using ‘ #define ‘ directive

➢ Replaced by their definition before compilation

➢ Eg #define PI 3.14159 ;

➢ It improves code modifiability and understandability

44
OPERATORS IN C
➢ Symbols that tell the compiler to perform specific operations

➢ Operations are performed on variables and values

➢ Used to manipulate data

➢ Can control the flow of the program

➢ Values and variables used with operators are called operands


45
TYPES OF OPERATORS IN C
C operators can be classified into a number of categories :

1. Arithmetic Operators 5. Increment & Decrement Operators

2. Relational Operators
6. Conditional Operators
3. Logical Operators

7. Bitwise Operators
4. Assignment Operators

46
ARITHMETIC OPERATORS
1. + (Addition) : Adds two operands
2. - (Subtraction) : Subtracts the second operand from the first
3. * (Multiplication) : Multiplies two operands
4. / (Division) : Divides first operand by the second
The result is an integer if both operands are integers
5. % ( Modulus ) : Returns the remainder of the division

47
RELATIONAL OPERATORS
These operators compare two operands (values) and return either
‘ true ’ ( 1 ) or ‘ false ‘ ( 0 )

1. == ( Equal to ) : Checks if two operands are equal

2. != ( Not equal to ) : Checks if two operands are not equal

3. > ( Greater than ) : Checks if first operand is greater than second

48
RELATIONAL OPERATORS
These operators compare two operands (values) and return either
‘ true ’ ( 1 ) or ‘ false ‘ ( 0 )

4. < ( Less than ) : Checks if first operand is less than second

5. >= ( Greater than or equal to ) : Checks if first operand is greater than or


equal to second

6. <= ( Less than or equal to ) : Checks if first operand is less than or equal
to
second
49
LOGICAL OPERATORS
These operators are used to combine multiple conditions.
They are essential for decision making based on multiple criteria.

1. && ( AND ) : Returns ‘ true ‘ if both conditions are true

2. || ( OR ) : Returns ‘ true ‘ if atleast one conditions is true

3. ! ( NOT ) : Inverts the truth value of a single condition.

50
ASSIGNMENT OPERATORS
These operators are used to assign the value or result of an expression to a variable.

1. = ( Assign ) : Assigns the value of right-hand operator to the left

Shorthand Assignment Operators

2. += : Adds right operand to left and assigns result to the left operand

3. -= : Subtracts right operand from left and assigns result to left operand

4. *= : Multiplies right operand with left and assigns result to the left operand

5. /= : Divides left operand by right and assigns result to the left operand

6. %= : Takes modulus of left operand with right and assigns result to the left operand
51
INCREMENT & DECREMENT
OPERATORS
1. ++ ( INCREMENT ) : Increase the value of the operand by 1

i. Pre-increment (++a)

ii. Post-increment(a++)

2. -- ( DECREMENT ) : Decreases the value of the operand by 1

i. Pre-increment (--a)

ii. Post-increment(a--)
52
CONDITIONAL OPERATORS
This operator allows you to make decision within a single line of code.

condition ? expression_true : expression_false ;

• condition : expression to evaluate ( returns true or false )


• expression_true : value or expression that is executed if condition is true
• expression_false : value or expression that is executed if condition is false
53
BITWISE OPERATORS
These operators work on binary representation of int, performing operations bit by bit.

1. & ( Bitwise AND ) : Perform AND operation on corresponding bits of two integers

2. | ( Bitwise OR ) : Perform OR operation on corresponding bits of two integers

3. ^ ( Bitwise XOR ) : Perform XOR operation on corresponding bits of two integers

4. ~ ( Bitwise NOT ) : Flips all the bits of an integer, turning ‘1’ to ‘0’ and vice versa

5. << ( Left Shift ) : Shifts the bits of a number to the left by specified no. of positions

6. >> ( Right Shift ) : Shifts the bits of a number to the right by specified no. of positions

54
QUIZ
Determine whether the following statements are True or False.

1. The assignment operator = is used to compare two values in C.

2. The ++ operator increments the value of a variable by 1.

3. The expression 7 / 2 in C will return 3.5.

4. The << operator is used for left bitwise shifting in C.

5. The ! operator is used to negate a boolean expression in C.


55
QUIZ
Determine whether the following statements are True or False.

6. The | operator is used to perform logical OR operations.

7. In C, the expression 5 % 2 will return 2.

8. The && operator is used to perform bitwise AND operations in C.

9. The ! operator is used to negate a boolean expression in C.

10. The / operator performs integer division when both operands are integers.
56
LIBRARY FUNCTIONS
➢ Pre-defined functions provided by C libraries

➢ Simplify programming by providing reusable code

➢ Increase efficiency by using optimized and tested functions

➢ Save time by avoiding writing common functions from scratch

➢ Accessible by including the corresponding header files


57
EXAMPLES OF C LIBRARIES

➢ stdio.h : Standard Input and Output library.

➢ stdlib.h : Standard Library for general utilities.

➢ string.h : String handling library.

➢ math.h : Mathematical functions library.

➢ time.h : Date and time utility functions.

➢ ctype.h : Character handling functions. 58


FUNCTIONS IN “ STDIO.H ” LIBRARY
1. printf : Prints formatted output to the screen.

2. scanf : Reads formatted input from the keyboard.

3. fprintf : Prints formatted output to a file.

4. fscanf : Reads formatted input from a file.

5. getchar : Reads a single character from standard input.

6. putchar : Writes a single character to standard output.


59
FUNCTIONS IN “ MATH.H ” LIBRARY
1. sqrt : Calculates the square root of a number.

2. pow : Raises a number to a power.

3. sin, cos, tan : Trigonometric functions.

4. abs : Returns the absolute value of an integer.

5. fmod : Returns the remainder of x divided by y.

6. ceil : Rounds x up to the nearest integer.

7. floor : Rounds x down to the nearest integer.


60
FUNCTIONS IN “ CTYPE.H ” LIBRARY
1. isdigit : Checks if a character is a digit.

2. isalpha : Checks if a character is alphabetic.

3. isalnum : Checks if a character is alphanumeric.

4. toupper : Converts a character to uppercase.

5. tolower : Converts a character to lowercase.


61
FORMATTED INPUT / OUTPUT
➢ Handles input and output with specific formatting rules

➢ Uses specifiers like %d, %f, %s to control data representation

➢ Formatted Input Functions : scanf , fscanf

➢ Formatted Output Functions : printf , fprintf

➢ Performs error checking for format specifier mismatches


62
UNFORMATTED INPUT / OUTPUT
➢ Handles raw input and output without specific formatting

➢ No format specifiers needed

➢ Formatted Input Functions : getchar , gets , fgets

➢ Formatted Output Functions : putchar , puts , fputs

➢ Deals directly with data, often with minimal error checking


63
64
65
66
67
68
69
70
71

You might also like