SlideShare a Scribd company logo
1 of 295
1
Programming
in
C
Presented by:
Suhaib Rehman
Trainer
2
ST-1
3
Introduction to ProblemSolving
4
Stages of Problem solving
“Computer programmers are problem solvers”
Problem-Solving: It is the act of identifying the problems and implementing the best possible
solutions.
It is the job of the programmer to write down the solution
To solve a problem with one needs to pass through certain stages/steps.
Steps in Problem-Solving:
•Identify the problem
•Define the context of the problem
•Explore possible strategies
•Act on the best solution
•Coding and implementation.
•Look back and learn
5
•Identify the problem
Define Problem
The first step in solving a problem is understanding what that problem actually is. You need
to be sure that you're dealing with the real problem.
To really solve the problem, it's important to find out what started it all. This is called
identifying the root cause
However, defining a problem doesn't mean deciding how to solve it straight away. It's
important to look at the issue from a variety of perspectives. If you commit yourself too early,
you can end up with a short-sighted solution
As you define your problem, you'll often discover just how complicated it is.
•Define the context of the problem
6
Problem-solving steps
A.Use of specific Example:
Focusing on a particular problem can give us the foothold we need for making a start on
the solution to the general problem.
B. Similarities among problems:
 Check similarities between the current problem and past problems which we have solved
 more experience one has with tools and techniques, more efficiently he/she can tackle the given
problem.
 But sometimes it blocks us from discovering a desirable or better solution to the
problem
C. Working backward from the solution:
We have a solution to a problem and then try to work backward to the starting point.
The “Work Backward” method works well for problems where a series of operations is done on an
unknown number and you’re only given the result.
Explore the strategies
7
Problem-solving steps
Working backward from the solution: Example
Sam’s mom left a plate of cookies on the counter. Sam ate 2 of them, his dad ate 3 of them and they
gave 12 to the neighbor. At the end of the day, only 4 cookies were left on the plate. How many cookies
did she make altogether?
8
General Problem solving Strategies
Problem-solving strategies don’t guarantee a solution, but they do help guide you through the process
of finding a resolution.
Often we phrase a problem in one of the following strategies:
1. trial and error. In other words, you try different solutions until you find one that works.
2. Divide and Conquer: E.g Merge Sort
9
Representation of Algorithm
10
Flow chart Pseudocode
11
Coding and implementation.
A flowchart is a diagram that depicts a process, system or computer algorithm. They are widely
used in multiple fields to document, study, plan, improve and communicate often complex processes in
clear, easy-to-understand diagrams
Start/End Symbol
The terminator
symbol marks the
starting or ending
point of the
system. It usually
contains the word
"Start" or "End."
Action or Process
Symbol
A box can represent a
single step ("add two
cups of flour"), or an
entire sub-process
("make bread") within a
larger process.
Document
Symbol
A printed
document or
report
Multiple
Documents
Symbol
Represents
multiple
documents in
the process
Decision Symbol
A decision or branching
point. Lines representing
different decisions
emerge from different
points of the diamond.
12
Input/Output Symbol
Represents material or
information entering or
or leaving the system,
such as customer order
order (input) or a
product (output).
Preparation Symbol
Represents a set-up to
another step in the
process.
Connector Symbol
Indicates that the flow
continues where a
matching symbol
(containing the same
letter) has been placed
Delay Symbol
Indicates a delay in the
process.
Database Symbol
Indicates a list of information with a standard
structure that allows for searching and sorting
Display Symbol
Indicates a step that
displays informatio
13
14
15
What is an Algorithm?
A sequence of steps to solve a given problem is called as algorithm. Thus, an algorithm
is a step-by-step procedure developed for solving a given problem. An algorithm consists
of sequences, iterations, selections, etc
What is a Pseudocode?
Pseudocode is an informal method of developing an algorithm. Thus, computer programmers
use simple informal language to write a pseudocode. It does not have any specific syntax to
follow.
The main difference between an algorithm and a pseudocode is that an algorithm is a step-by-step
procedure to solve a given problem while a pseudocode is a method of writing an algorithm.
Yes, algorithms can be known as pseudocodes. They are sometimes considered as pseudocodes.
Whereas pseudocodes can not be considered as algorithms as they might not carry exact information
required to carryout the solution to the problem
16
1. Start from the leftmost element of arr[] and one by one compare x with
each element of arr[].
2. 2. If x matches with an element, return the index.
3. 3. If x doesn’t match with any of elements, return -1.
Algorithm of linear search
Pseudocode for Linear Search :
FUNCTION linearSearch(list, searchTerm):
FOR index FROM 0 -> length(list):
IF list[index] == searchTerm THEN
RETURN index
ENDIF
ENDLOOP
RETURN -1
END FUNCTION
In here, we haven’t used any specific programming language but wrote the steps
of a linear search in a simpler form which can be further modified into a proper
program
17
Algorithm vs Pseudocode vs Program:
1.An algorithm is defined as a well-defined sequence of steps that provides a
solution for a given problem, whereas a pseudocode is one of the methods that
can be used to represent an algorithm.
2.While algorithms are generally written in a natural language or plain English
language, pseudocode is written in a format that is similar to the structure of a
high-level programming language. Program on the other hand allows us to
write a code in a particular programming language.
18
Test and
Debug
Debugging •Debugging: Debugging is the process of finding and resolving
defects or problems within a computer program that prevent correct
operation of computer software or a system. •
19
Programming errors
Syntax errors
:
•misspelling a statement, eg writing prit instead of print
•using a variable before it has been declared
•missing brackets, eg opening a bracket, but not closing it
Logic errors
• A logic error is an error in the way a program works. The
program can run but does not do what it is expected to do.
• unintentionally creating a situation where an infinite loop may
occur
Runtime errors
A runtime error is an error that takes place during the running of
a program.
An example is writing a program that tries to access the sixth item
in an array that only contains five items. A runtime error is likely
to crash the program.
20
Introduction
to
C
What is a programming language? 21
To communicate with a person, we need a specific
language.
Language is a mode of communication that is used
to share ideas, opinions with each other.
Language?
A programming language is a computer language that is used to
communicate with computers..
Programming Language?
What is a programming language? 22
A programming language is used to develop software programs,
or
A programming language contains sets of instructions for computers to execute.
A programming language is mainly used to develop desktop applications, websites, and
mobile applications, system programs etc.
23
Types of programming language
Low level
programming language
Assembly
Language
Machine
Language
High level
programming language
Procedural
Oriented
programming
language
Object Oriented
Programming
Language
C C++ Java PHP Android Java script Python
24
Machine code or object code: Computers directly understand the machine language
program.
The lowest level of software is machine code.
Other programming languages are converted to machine code before being executed
by the computer.
Machine code consists of the CPU’s directly comprehensible binary instructions.
Binary is the most common format.
Machine Code
For example, take ASCII, the ‘01000001’ bit pattern represents the ‘A’ letter.
ASCII, abbreviated from American Standard Code for Information Interchange: Character encoding standard
for electronic communication.
25
The assembler language is the symbolic programming language that lies close to the
machine language in form and content. The assembler language is useful when:
->You need to control your program closely, down to the byte and even the bit level.
->Assembly Language is expressed in a more human readable form than the binary instructions
Assembly Language
.
MOV A,[1]
MOV B,[2]
ADD A,B
MULT A,B
26
High-level programming language (HLL) is designed for developing user-friendly
software programs and websites.
This programming language requires a compiler or interpreter to translate the
program into machine language (execute the program).
Example: Python, Java, JavaScript, PHP, C#,
High level Programming Language
27
Middle-level programming language lies between the low-level programming
language and high-level programming language.
It is also known as the intermediate programming language or pseudo-language.
A middle-level programming language's advantages are that it supports the features of
high-level programming i.e. it is a user-friendly language, and closely related to
machine language and human language.
Example: C language
Middle-level programming
language
C programming supports Inline assembly language programs. We can directly access
system registers with the help of inline assembly language feature in C.
C programming is used to access memory directly using a pointer.
The actual Linux kernel code is only in C and Assembly.
28
History of C
Date Language
1960 ALGOL International group
1967 BCPL Martin Richards
1970 B Ken Thompson
1972 TRADITIONAL C Dennis Ritchie at Bell Laboratories
1978 K&R C Kernighan and Ritchie
1989 ANSI C ANSI Committee
1990 ANSI/ISO C ISO Committee
1999 C99 Standardization Committee
29
ALGOL: Algorithmic Language
BCPL:Basic Combined Programming Language.
C: become more popular after the publication of the book “ The C Programming
Language” by Kernighan and Dennis Ritchie in 1978. and language was known as K&R
C.
Growth of C led to development of different version of the language that were similar but
often incompatible.
To assure that C remains standard, in 1983, American National Standards Institute(ANSI)
appointed a technical committee to define standard for C.
IT was then approved by the International Standards Organization(ISO) in 1990.
C++ and Java were evolved out of C, and then few features of C++ and Java were added
to C. This version is usually referred to as C99.
History of C
30
Features of C
It is machine independent
A function can
call itself again
and again
until certain
criteria is met
Pointers are memory variables which
stores the address of another variable
instead of storing a value.
It easily manages memory during
runtime And during compile time.
It is easy to learn
It can be extended
easily to add new
features
Libraries include
number of pre-
defined functions
which can be used
directly in a
program
It’s syntax is similar to
machine
language as well as
human
language
It follows a block structured approach
in which set similar statements are written
inside two curly brackets { }
FEATURES OF C LANGUAGE
 C language is used for creating computer applications
 Used in writing Embedded software
 Firmware for various electronics, industrial and communications products which use micro-controllers.
 It is also used in developing verification software, test code, simulators etc. for various applications and hardware products.
 For Creating Compiler of different Languages which can take input from other language and convert it into lower level machine
dependent language.
 C is used to implement different Operating System Operations.
 VLC media player is an open-source software and a cross-platform media player and streaming media server. This application
is written using a combination of C, C++ and Objective – C programming languages.
 Microsoft Office Suit- Originally written in C programming language, most of it’s portion is now switched on to C++ programming
language for the object oriented programming paradigm shift.
 Adobe has rolled out some of the world-class products in animation domain. We have some amazing tools that have been
developed in C programming language such as Adobe Photoshop, Adobe Illustrator, Adobe Premier, Adobe Image Ready and
others.
31
REAL WORLD APPLICATIONS OF C PROGRAMING LANGUAGE
32
Structure OF C Program
33
Structure of C program is defined by set of rules called
protocol, to be followed by programmer while writing C
program. All C programs are having sections/parts which
are mentioned below.
suitor
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype/ declaration section
6. Main function
7. User defined function definition section
Structure OF C Program
34
Structure OF C Program
Documentation Section: consists of set of comment lines, name of program, author and other details
Link Section: provides instructions to the compiler to link functions from the system library.
Definition Section: defines all symbolic constants.
Global Declaration section: Variable that are declare in the global declaration section that can be
accessed to all functions. This section also declares all the user-defined functions.
Main function: Every program must have one main() function section. This section also contains two
parts, declaration part and executable part. All the statements in the declaration and executable part end
with a semicolon ;
Subprogram section: contains all the user defined functions and are called in main function
Note: All sections , except the main function section may be absent when they are not required
35
Creating the Program
Windows
Integrated development environment Software
•Save the file with “.c” extension.
•Open cmd and write “gcc first.c -o first.exe”
command.
•To execute, enter first
•Here “first.c” is the source code file name and
first.exe is the name of the exe file that the
compiler will create.
•Save the file with “.c” extension.
•Cc first.c
•The compiled and linked program is called executable object
code and is stored automatically file named a.out.
•To execute, enter command a.out
• create your own executable file:
cc –o name source-file
If you are using text
editor then install
GCC compiler first.
Add bin path to
system path
-check installed or
not enter gcc -v
36
Compilation OF C Program
37
Character Set
Character set:- The character set is the fundamental raw material of any language and they are used
to represent information. These characters are used to form words, numbers and expressions.
Like natural languages, computer language will also have well defined character set, which is useful to
build the programs.
38
ALPHABETS
Uppercase letters A-Z
Lowercase letters a-z
DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
SPECIAL CHARACTERS
~ tilde % percent sign | vertical bar @ at symbol + plus sign < less than
_ underscore - minus sign > greater than ^ caret # number sign = equal to
& ampersand $ dollar sign / slash ( left parenthesis * asterisk  back slash
) right parenthesis ′ apostrophe : colon [ left bracket " quotation mark ; semicolon
] right bracket ! exclamation mark , comma { left flower brace ? Question mark . dot operator
} right flower brace
WHITESPACE CHARACTERS
b blank space t horizontal tab v vertical tab r carriage return f form feed n new line
 Back slash ’ Single quote " Double quote ? Question mark 0 Null a Alarm (bell)
Character Set
The characters in C are grouped into the following :
39
C Token
Smallest individual units are known as tokens.
E.G in a passage of text, individual words and punctuation marks are called tokens
C programs are written using these tokens and the syntax of the language
C Tokens
Keywords Constants Strings Operators
Identifiers Special Symbols
Float
while
-15.5
100 “ABC”
+ -
amount [], {}
40
Keywords: have fixed meaning and cannot be changed.
Identifiers: User-defined names (names of variables, functions, arrays)
Keywords and Identifiers
Keywords in C Programming
auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while
Rules of Identifiers:
 First character must be an alphabet or
underscore.
 Must consists of only letters, digits or underscore
 Cannot use a keyword
 Must not contain white space
41
Constant in C refers to fixed value that do not change during the execution of a program
Constants
Numeric Constants Character Constants
Integer Constants
Real constants
Single character
Constants
String Constants
Constants
Integer Constants: Refers to sequence of digits E.g. 123
->decimal integer 0-9
-> octal integers 0-7 with leading 0 e.g. 037 0435
-> hex decimal integers 0-9, A-F. e.g. 0X9F
Note: embedded spaces, commas, and non-digit characters are not permitted. E.G. 20,000
42
Real constants
Real Constants: Quantities that contain fractional parts like 17.34. Such numbers are called real or
floating point constants.
Note: Integers are inadequate to represent quantities that vary continuously such as distance ,
height ,temperature .
A real number may also be expressed in exponential (or scientific notation).
E.G. 215.45 may be written as 2.1545e2 where e2 means multiple by 102
Single character constants String constants
Character constant contains characters
closed within a pair of single quote
E.G ‘5’, ‘X’
String Constant is a sequence of
characters enclosed in double quotes
E.G “Hello”
Character constants
43
Variables
A variable is a data name that may be used to store a data value.
A variable may take different values a different times during execution.
ANSI (American National Standards Institute) standard recognizes a length of 31
characters. However the length should not be more than eight characters, since only
the first eight are treated as significant by many compilers.
In c99 , at least 63 characters are significant.
-remember Abc is not same as abc
First_tag valid
Char invalid (keyword)
Prices$ invalid (Dollar sign is illegal)
Com sci  invalid (blank space)
44
Data types
C language is rich in its data types.
Data type specifies the type of data that the variable can store like integer, character, floating,
double, etc.
Each variable in C has an associated data type.
Each data type requires different amounts of memory and has some specific operations which
can be performed over it.
C99 adds three more data types :- _Bool, _complex and imaginary
45
Primitive/Fundamental data type: Each data type requires different amounts of
memory and has some specific operations which can be performed over it.
Derived data type : These data types are defined by user itself. User specifies the
amount of space it is going to take and the type of operation .
Derived data types are created from basic data types such as int, float, char, etc.
User Defined Data type: the programmer can invent his/her own data types in C
programming.
it is called a user-defined data type is that the variables of different types are clubbed together under a
single structure user-Defined
46
Procedures for Binary Subtraction by 1’s Complement
•Write the 1’s complement of the subtrahend  change 0 to 1 and vice varsa.
•Then add the 1’s complement subtrahend with the minuend
•If the result has a carryover, then add that carry over in the least significant bit
•If there is no carryover, then take the 1’s complement of the resultant, and it is negative.
10-5 =5
Binary of 10= 1010
Binary of 5=0101
1010
- 0101
+ 101
5-10 =-5
Binary of 5= 0101
Binary of 10=1010
0101
- 1010
--------
1’s compliment of 10(subtrahend) = 1010 0101 add
this to binary of 5(minuend) 0101
5 0101
100101
+______
1010 no carry take 1’s compliment of result
and it is negative 0101 -5
Whenever a number with minus
sign is encountered, the number
(ignoring minus sign) is converted
to its binary equivalent. Then the
two’s complement of the number
is calculated. That two’s
complement is kept at place
allocated in memory and the sign
bit will be set to 1 because the
binary being kept is of a negative
number. Whenever it comes on
accessing that value firstly the
sign bit will be checked if the sign
bit is 1 then the binary will be
two’s complemented and
converted to equivalent decimal
number and will be represented
47
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 8 bytes or (4bytes
for 32 bit OS)
-9223372036854775808 to 9223372036854775807
unsigned long 8 bytes 0 to 18446744073709551615
Primary Data types
48
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
Floating-Point Types
Data types
49
Character Types
Void Types
Characters are usually stored in 8bits.
The qualifier signed and unsigned may explicitly applied to char
The void type has no values.
Usually used to specify the type of function.
A function is said to be void when it doesn’t return any value to the calling function
Data types
50
Data type Variable_Name =constant;
Int a=100;
Char b=‘x’;
Float =75.8
The process of giving initial values to variables is called initialization.
C permits initialization of more than one variable in one statement using multiple
assignment operator E.G. a=b=c=0;
Assigning values to variables
51
scanf() function
Another way of assigning values to variables is to input data from keyboard using scanf funtion
1.scanf(“control string",&variable1, &variable 2……);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.
Printing data to console
printf() function
The printf() function is used for output. It prints the given statement to the console.
The syntax of printf() function is given below:
1.printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) ,%.12lf( long float to 12
decimals) etc.
Reading data from Keyboard
Printing data to console
printf() function
The printf() function is used for output. It prints the given statement to the console.
The syntax of printf() function is given below:
1.printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) ,%.12lf( long float to 12
decimals) etc.
52
Type Size (bytes) Format Specifier
int at least 2, usually 4 %d, %i
char 1 %c
float 4 %f
double 8 %lf
short int 2 usually %hd
unsigned int at least 2, usually 4 %u
long int at least 4, usually 8 %ld, %li
long long int at least 8 %lld, %lli
unsigned long int at least 4 %lu
unsigned long long
int
at least 8 %llu
signed char 1 %c
unsigned char 1 %c
long double at least 10, usually 12 or 16 %Lf
53
Interpreter
Language Translators
1. Scans whole program in one go
2. Errors are shown in one go
3. It does not require source code for later
execution.
4. IT takes a large amount of time for
analyzing the source code
5. Object code is generated
6. Programming languages like C, C++,
Java use compilers.
7. Compiler is based on translation
linking-loading model,
8. A linker program that takes the object
files, produced by compiler, join them
into a single executable file.
9. It is special program that takes input of
executable files from linker, loads it to
main memory, and prepares this code
for execution by computer
1. It translates only one statement of the
program at a time.
2. Errors are shown line by line.
3. It require source code for later
execution.
4. Interpreters take less time for analyzing
the source code.
5. No object code is generated
6. Debugging is easy
Programming languages like JavaScript,
Python,PHP Ruby use interpreters.
Compiler
Printing data to console
54
The compilation process in C involves four steps: pre-processing,
compiling, assembling, and linking.
All the statements starting with the # symbol in a C program are processed by the pre-processor,
and it converts our program file into an intermediate file with no # statements
Pre processing
Source Program
Expanded source
code
Assembly code Object code
Preprocessing Compiling
Linking
Exe code
assembling
first.i abc.s
first.c abc.obj/abc.o
abc.exe/abc.out
55
System Ready
Enter program
Program Code
Edit Source program
C compiler
Syntax
Error
Link with system Library
Execute object code
Logic and
Data
Errors
Correct Output
Compile Source Program
System Library
Input Data
Stop
No errors
Logic errors
Data error
No
Source Program
Yes
Object Code
Executable object code
Process of compiling and running a C Program
56
Comments in C
Single-line comments start with two forward slashes (//).
Multi-line comments start with /* and ends with */.
Let us play with char data type
57
you must use the char type and create an array
Strings are used for storing text/characters
String in C
C does not have a String type to create string variables
char university[] = “chitkara";
printf("%c", university[0]);
char university[] = “chitkara";
printf("%s", university);
58
String in C
Take Input of a String in C Without Spaces
The scanf() function is probably the easiest way to string input in C. We just need the access
specifier %s
Hence, the scanf() function should be preferred when we know the string we want to input doesn't
contain white spaces and that it will not exceed the memory buffer.
gets() function
The working of gets() is such that it keeps reading the input stream until it encounters a
newline character: n. Hence, even if the string input in C has spaces in it, all of them get
included as input until n doesn't occur.
But gets() doesn't care about the size of the character array passed to it and would lead to buffer over
flow
A buffer overflow (or buffer overrun) occurs when the
volume of data exceeds the storage capacity of the
memory buffer The gets() method is no longer a standard
function according to the C11 standard ISO/IEC
9899:2011. But it is still available in libraries
and will continue to be available for
compatibility reasons.
59
String in C
Take Input of a String in C With
Spaces
fgets() can take string input in C from both the standard input stream or from
some file
fgets(char_array, size, stdin);
1.{%[^n]%*c} inside scanf
•%*[^n] scans everything until a n, but doesn't scan in
the n. The asterisk(*) tells it to discard whatever was
scanned.
•%*c scans a single character, which will be the n left
over by %*[^n] in this case. The asterisk
instructs scanf to discard the scanned character.
In scanf function you can use regular expressions to
restrict or validate the char you are going to read, here in
your question [^n] is regular expression that will
exclude n i.e in other words scanf will read all char until
you hit enter button.
Now coming to %*c , * is used to indicate don’t assign
60
#include <stdio.h>
int main() {
int i = 10;
char c = 'a';
int add;
add= i + c;
printf("Value of sum : %dn", add );
}
Integer promotion:
C is converted in ascii
int main() {
char i = '1';
char c = 'a';
int add;
add= i + c;
printf("Value of sum : %dn", add );
}
61
Type Casting in C
Converting the value of one data type to another type is known as type conversion.
C permits the mixing of constants and variables of different types in an expression.
C automatically converts any intermediate values to the proper type without losing any
significance._________IMPLICIT TYPE CONVERSION.
RULE: Lower type is converted into a higher type
All short and char are converted to int.
I. if one operand is long double the other will be converted long double.
II. If one operand is double the other is converted to double and result will be double.
III. --------------------float the ----------------------float and -----------------float.
IV. ---------------------long int----------------------long int and --------------long int.
The final result of an expression is converted to type of variable on the left of
assignment sign before assigning value to it.
Following changes are introduced
Float to int cause truncation of fractional part.
Double to float cause loss of rounding digits.
Long int to int cause dropping of excess higher order bits
62
x= 1/i + i*f - d
int Float
int i,x;
float f;
double d;
long int 1;
int double
long
long
long float Float
int
double
int
float
float
double
An expression is a combination of operators and
operands which reduces to a single value.
63
Type Casting in C
EXPLICIT TYPE CONVERSION:
When we want to force type conversion.
Ratio =quantity1/quantity2;
If quantity1 and quantity2 are declare integers then decimal part of the result would be
lost.
Ratio=(float)qualtity1/quantity2
The operator (float) converts the quantity1 number to floating point for the evaluation.
The type of quantity1 remains as int in other parts of the program.
Z=(int)3.4;
A=(int)21.3/(int)4.5
64
Operators and Expressions
Operators: Operators are used in programs to manipulate data and variables.
C operators are classified into a number of categories:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
An expression is sequence of operators and operands that reduces to
a single value. E.G 10+15;
65
Operators
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo Division
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
Arithmetic operators
Relation operators
Relational operators help
in making a relationship or
comparison between two
operands with which they
are used
An arithmetic operator is
used to perform
arithmetic/mathematical
operations on operands.
66
Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Operator Meaning
Syntax: V op=exp
V=variable, op= operator, exp=expression
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a%b a%=b
Logical operators (used to test more than one condition)
Assignment Operators( used to assign the result of an expression to a variable)
The logical operators are
used when we want to
check or test more than
one condition and make
decisions.
An assignment operator is
used to assign values to
the operands.
67
Operators
Operator Meaning
++ ++ adds 1 to the operand
- - -- subtracts 1 from the operand
Postfix(a++) and prefix(++a)
a++(postfix) and ++a(prefix) mean the same thing but they form the
statements independently, they behave differently.
 Increment and decrement operators are unary operators.
 a=5 a=5
 b=++m b=a++
Increment and Decrement operators
Unary operators: are
operators that act upon a
single operand to produce a
new value.
Types of unary operators:
1.unary minus(-)
2.increment(++)
3.decrement(- -)
4.NOT(!)
5.Addressof operator(&)
6.sizeof()
The minus operator changes the sign of its argument. A positive number becomes negative, and a negative
number becomes positive.
unary minus is different from the subtraction operator, as subtraction requires two operands.
68
Operator Meaning
For manipulating data at bit level.
 Bitwise operators are not applied to float or double
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< shift left
>> Shift right
Bitwise Operators
Conditional Operators
Operator Meaning
Exp1? Exp2:exp3
Exp1 is evaluated first, if it is nonzero (true) then exp2 is evaluated otherwise
exp3 is evaluated
Operators
69
Operator Meaning
,
Used to link the related
expressions together
Comma
& Address Operator
sizeof() sizeof
Special Operators
Operators
int main() {
int value;
int x,y;
value = (x=10, y=5);
printf("%d %d",x,y);
return 0;
70
Arithmetic Expression
Operator Description Associativity Rank
() Left to right 1
+,-,++,--
,!,~,*,&
sizeof(),
Right to Left 2
*,/,% Left to right 3
+ - Left to right 4
<< ,>> Left to right 5
<,<=,>,>= Left to right 6
==, != Left to right 7
71
Arithmetic Expression
Operator Description Associativity Rank
& Bitwise AND Left to right 8
^ Bitwise XOR Right to Left 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional expression Right to left 13
=,*=,/=,%=,+=,-= Assignment operators Right to left 14
, Comma operator Left to Right 15
72
Operator Precedence in C is used to determine the sequence in
which different operators will be evaluated if two or more
operators are present in an expression.
The associativity of operators: is used to determine whether an
expression will be evaluated from left-to-right or from right-to-
left if there are two or more operators of the same precedence.
E.G c=a*5/5 ------------Here
 a-b/3+c*2-1
a=9, b=12, c=3
 a-b/(3+c)*2-1
1. Parentheses have the highest precedence among all
operators in C.
Operator Precedence
73
printf("%d", 1 == 3 != 5);
Operator Precedence
Z=++a * (3 + 8) % 35 - 28 / 7;
z = a++ + ++a;
a > b > c
74
Macros in C
The macro in C language is known as the piece of code which can
be replaced by the macro value.
The macro is defined with the help of #define preprocessor
directive and the Macro doesn’t end with a semicolon(;).
Whenever the compiler encounters the macro, it replaces the macro
name with the macro value.
e.g #define PI 3.14
#: preprocessor directive
PI macro name
3.14 Macro Value
Q: Write a program to calculate the area of a circle with a macro
definition for PI( Given that diameter of the circle is 16 cm)
#define MARKS 100
#define MIN 1
#define G 9.8
75
Sr. No. Macro Feature
1 __LINE__ Macro
It contains the current line
number on which this macro is
used.
2 __FILE__ Macro
It contains the name of the file
where the current program is
present.
3 __DATE__ Macro
It contains the current date in
MMM DD YYYY format.
4 __TIME__ Macro
It contains the current time in
HH:MM format.
5 __STDC__ Macro
It is defined as 1 when there is a
successful compilation.
Predefined Macros and their features:
76
IF Statement:
The if statement is a simple decision-making and branching
statement and it is used to control the flow of the program
execution.
IF Statement
It means depending on the condition the control is transferred either to the
true block or false block. It is also called a control statement.
Condition
check
True
False
77
if(expression)
#include<stdio.h>
int main()
{
int a=10;
float b=50;
if(a>b)
{
printf("yes %d",a);
}
return 0;
}
#include<stdio.h>
int main()
{
char a=‘1’;
float b=50;
if(a>b)
{
printf("yes %d",a);
}
return 0;
}
78
int main()
{
int a=10;
int b=50;
int c=500;
if(a>b>c)
{
printf("yes %d",a);
}
return 0;
}
#include<stdio.h>
int main()
{
int a=10;
int b=5;
int c=0;
if(a>b>c)
{
printf("yes %d",a);
}
printf("outside if statement");
return 0;
79
Types of If Statements
if statement may be implemented in different
forms depending on the complexity of testing
conditions to be evaluated.
•Simple if Statement
•if-else Statement
•Nested if-else Statement
•else-if Ladder
Condition
check
True
False
If Block
Else
block
80
Program to check whether a person is eligible to vote or not. Given that age must be
equal to or greater than 18
Q. Write a program that takes integer input from the user. Based on that input you have to
decide whether the integer input is an even or odd number
Find out the given number is even or not using Ternary Operator in C.
(num % 2 == 0)
81
If Else Ladder
if(condition) { }
else if(condition) {
// this else if will be executed when condition in if is false and //
the condition of this else if is true }....
// once if-else ladder can have multiple else if else { // at the end
we put else }
if()
{
}
Else if()
{
}
Else if()
{
}
else
Write a program to Check whether a number is positive,
negative or 0
Calculate Grade According to marks using if else ladder.
Given that:
marks less than 100 and marks greater or equal 90 --A
marks less than 90 and marks greater or equal 70 --B
marks less than 70 and marks greater or equal 50 --C
marks less than 50 and marks greater or equal 40 --D
marks less than 40 and marks greater or equal 0 --F
other than this marks are not valid
82
if (condition 1) {
//if the second condition holds
if (condition 2)
{ do something }
//if the second condition does not hold
else { do something else }
}
// if the first condition does not hold
else{ //if the third condition holds
if (condition 3)
{ do something }
//if the third condition does not hold
else
{ do something else }
}
Nested If Else Statement
Write a program to find Which number is greatest among the three numbers that
the user has received as input
83
Write a program to analyze if the number is even or odd, and then if it is even, whether it is divisible by 4
or not, and if it is odd, whether it is divisible by 3 or not
Write to program to Check if a year is a leap year
Write a program to find Which number is greatest among the three numbers that the
user has received as input
4
100
400
Write a program to multiple variable with a constant without using multiplication
operator.
84
Every year that is evenly divisible by four is a leap year except for years
that are evenly divisible by 100 and 20For example, 2014, 2015, 2017,
and 2018 are not leap years because they are not evenly divisible by
four, 2012, 2016, 2020, and 2024 are leap years because they are evenly
divisible by four and not evenly divisible by 100, 1800, 1900, 2100, and
2200 are not leap years because they are evenly divisible by 100 and not
evenly divisible by 400, and 1600, 2000, and 2400 are leap years
because they are evenly divisible by 400. All these rules makes the
average calendar year 365.2425 days, which is fairly close to the actual
time it takes for Earth to orbit the sun, which is slightly less than 365.2422
days
85
The math.h header defines various mathematical functions and one macro. All the functions
available in this library take double as an argument and return double as the result.
double ceil(double x): The C library function double ceil (double x) returns the smallest integer
value greater than or equal to x.
double floor(double x): The C library function double floor(double x) returns the largest integer
value less than or equal to x.
double fabs(double x): The C library function double fabs(double x) returns the absolute value of x
double fmod(double x, double y) : The C library function double fmod(double x, double y)
returns the remainder of x divided by y.
sqrt(double x): The C library function double sqrt(double x) returns the square root of x
double pow(double x, double y): The C library function double pow(double x, double y) returns
x raised to the power of y i.e. xy.
86
The term b2; - 4ac is known as
the discriminant of a quadratic
equation. It tells the nature of the roots.
If the discriminant is greater than 0, the
roots are real and different.
If the discriminant is equal to 0, the
roots are real and equal.
•If the discriminant is less than 0, the
roots are complex and different.
Write a program to find roots of a quadratic equations
87
88
#include<stdio.h>
int main()
{
int i,j;
i=10;
j=10;
if(i==1)
{
printf("how are you");
}
else if(i==10)
{
printf("yes");
}
else if(i==10)
{
printf("no");
}
return 0;
}
#include<stdio.h>
int main()
{
int i,j;
i=10;
j=10;
if(i==1)
{
printf("how are you");
}
else if(i==10)
{
printf("yes");
}
else if(j==10)
{
printf("no");
}
return 0;
}
89
C program to count the total number of notes in a given amount
Int a=5;
Printf(%d %d %d %d %d”, a,--a,--a,--a,--a);
Printf(%d %d %d %d %d”, a, a++,a++,a++,a++);
C program to swap two numbers using temporary variable?
C program to swap two numbers without using a temporary
variable?
90
Formatted output
Printf(“%d”,9876)
Printf(“%6d”,9876)
Printf(“%2d”,9876)
Printf(“%-6d”,9876)
Printf(“%06d”,9876)
9 8 7 6
9 8 7 6
9 8 7 6
9 8 7 6
0 0 9 8 7 6
91
Formatted output
Printf(“%7.4f”,98.7654)
Printf(“%7.2f”, 98.7654)
Printf(“%-7.2f”, 98.7654)
Printf(“%f”, 98.7654)
9 8 . 7 6 5 4
9 8 . 7 7
9 8 . 7 6 5 4
9 8 . 7 7
92
int main()
{
printf(" %d", printf("%s", “how are you"));
getchar();
}
int main()
{
int a ;
int z= scanf("%d ", &a);
printf(" %d",z );
getchar();
}
X=Printf(“hello”);
Printf(“%d”, x);
93
Getchar(): Reading a single character can be done using the function getchar
Variable_name=getchar();
C Supports many other similar functions which are contained in the filetype
ctype.h
#include<ctype.h>
 Isalnum(c)
 Isalpha(c)
 Isdigit(c)
 Islower(c)
 Ispunct(c)
 Isspace(c)
 Isupper(c)
94
Like getchar, there is an analogous function putchar for writing charactrs one at a time
to the terminal
Putchar(variable_name)
e.g
putchar(toupper(alphabet));
Write a program that reads a character from the keyboard and then prints the reverse case. That
is if the input is lower case output will be upper case and vice versa without using predefined
functions
Write a program that reads a character from the keyboard and then prints the reverse case. That
is if the input is lower case output will be upper case and vice versa using predefined functions
95
96
int main()
{
char a;
a= getch();
printf("%c", a);
return 0;
}
getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers
like Turbo C.
It reads also a single character from the keyboard. But it does not use any buffer, so the entered character is
immediately returned without waiting for the enter key.
97
int main()
{
char a;
a= getc(stdin);
printf("%c", a);
return 0;
}
getc():
It reads a single character from a given input stream and returns the corresponding integer value (typically
ASCII value of read character) on success. It returns EOF on failure.
98
getchar():
The difference between getc() and getchar() is getc() can read from any input stream,
but getchar() reads from standard input. So getchar() is equivalent to getc(stdin)..
int main()
{
printf("%c", getchar());
return 0;
}
99
int main()
{
char a[10];
gets(a);
puts(a);
}
100
Switch in C
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple
operations for the different possibles values of a single variable called switch variable.
Switch(Expression)
{
case value1:
block1
break;
case value2:
block2
break
Default:
default block
break;
}
In a switch statement, the “case
value” can be of “char” and “int”
type
101
The expression provided in the switch should result in a constant value otherwise it would not
be valid.
For example:
Valid expressions for switch –
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions –
switch(ab+cd)
switch(a+b+c)
The default statement is optional, if you don’t have a default in the program, it would run just
fine without any issues. However it is a good practice to have a default statement so that the
default executes if no case is matched.
102
#include <stdio.h>
int main() {
int number=1;
switch (number) {
case 1:
case 2:
case 3:
printf("One, Two, or Three.n");
break;
case 4:
case 5:
case 6:
printf("Four, Five, or Six.n");
break;
default:
printf("Greater than Six.n");}}
Create a grading system using a switch case
100-90->A
80 -90->B
60-80->C
40-60->D
30-40->E
<30->F
103
104
Range
case 75 ... 100:
105
106
We consider the following program in which the user to type his class group
Number(15,17,19), if the Group ID (15,17,19)is valid it will ask him to enter his Roll NO(1-
5), if the Roll No is correct the program will print message “ Welcome to CSE” to the user,
otherwise ,the program will print Incorrect Roll NO and if the Group ID does not exist , the
program will print Incorrect Group ID.
Please Enter Your Group ID: 17
Enter your RollNO: 15
Incorrect Roll NO
Please Enter Your Group ID: 17
Enter your RollNO: 5 Welcome to
CSE
Please Enter Your Group ID: 20
Incorrect Group ID
107
Write a program to convert the given two-digit number into English word format with the help
of a switch case.
e.g 7-> seven
Using the switch case, write a program in which the user selects any operator among +,-,*,/ then
the program asks for two integers, and after that performs the required operation on given two
integers.
108
Necessary Use switch case and/or if else if required, Write a program that asks for two inputs
year and month number(1-12). Based on the year and month number, calculate the total number
of days from the Month Jan
E.G year:2020
month: 3
total days= 91
109
Necessary Use switch case and/or if else if required, Write a program that asks for two inputs
year and month number(1-12). Based on the year and month number, calculate the total number
of days from the Month Jan
E.G year:2020
month: 3
total days= 91
110
A computer manufacturing company has the following monthly compensation policy to
their sales persons:
Minimum base salary: 1500
Bonus for every computer sold :200
Commission on the total monthly sales :2 percent (0.02)
The sales price of each computer is fixed at the beginning of every month.
Write a program to compute a sales persons gross salary
Hint gross salary=Base salary+bonus+comissions
Test Case
Input number sold and price
5 20430.00
Bonus= 1000.00
Comission=2045
Gross salary =4545.00
111
A electric power distribution company charges its domestic consumers as follows
Consumption Units Rate of charge
0-200 Rs 0.50 per unit
201-400 Rs 100 plus Rs 0.65 per unit excess of 200
401-600 Rs 230 plus Rs 0.80 per unit excess of 400
601 and above Rs 390 plus 1.00 per unit excess of 600
Write a program that reads customer number, power consumed, and print amount paid
by customer.
Test Case:
input
Customer N0 :101
Units consumer : 202
Output :
Charges 116
112
ST-2
113
C supports the goto statement to branch unconditionally from one point to another in the
program.
The goto statement requires a label in order to identify the places where the branch is to be
made.
The label is any valid variable name and must follow a colon:
Goto label;
Label:
Statement;
Label:
Statement;
Goto label;
Forward jump
Backward jump
114
#include<stdio.h>
int main()
{
int i=0;
count:
i=i+1;
printf("%dt",i);
if(i<100)
goto count;
return 0;
}
115
Loop
In looping, a sequence of statements is executed until some conditions for terminations of the
body of the loop and others known as control statements.
Control Statements: tests certain conditions and directs the repeated execution of the
statements contained in the body of the loop.
Test
conditions
Body of loop
Entry controlled loop
Test
condition
s
Body of loop
Exit controlled loop
entry entry
False
true
False
true
Pre-test Post test
116
Based on the nature of the control variable and the kind of value assigned to it for testing the
control expression, the loops may be classified into two general categories:
1. Counter-controlled loops: when we know in advance exactly how many times the loop will be
executed
2. Sentinel-controlled loops: a special value called sentinel value is used to change the loop
control expression from true or false
117
While(test condition)
{
Body of the loop
}
While loop is an entry controlled loop statement
Sum=0;
n=1;
while(n<=10)
{
Sum=sum+n*n;
n=n+1;
}
Printf(“sum=%d”, sum);
Character =‘’
While(character!= ‘y’)
Character=getchar();
//sentinel control loop
While Loop
118
The do-while loop is a post tested loop
do{
1.//code to be executed
2.}
3.while(condition);
1 2 3 4 5 5 7 8 9 10
----------------------
1
2
3
4
5
6
7
8
9
10
Do While Loop
119
Write a program to find the factorial of number using while loop
Write a program to reverse a given number e.g 123 -> 321
Write a program using while loop and print the following:
1 1
2 2
3 3
4 4
5 5
6 6
120
Write a program using a while loop and print the following pattern:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
121
Write an interactive program to demonstrate the process of multiplication. The program
should ask the user to enter two-digit integers and print the product of integers as
shown below
37x45 is ------------------------------ 45
x 37
---------
315
135
-------------
add them 1665
--------------
Jump in loops 122
Break: When a break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following the loop
Goto: An important use of goto is to exit from deeply next loops when an error occurs. A
simple break statement would not work here.
123
124
Skipping a part in loops 125
Continue: The continue statement causes the loop to be continued with the next
iteration after skipping any statements in between
SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH NEXT ITERATIONS
continue;
126
#include<stdio.h>
int i=1;
int main()
{
while(i<10)
{
if(i==5)
{
printf("This is %dn",i);
continue;
printf("cant print it");
}
printf("hello %dn",i);
i++;
}
}
for(i=0;i<10;i++)
{
printf("the value of i is %d",i);
if(i==7)
{
printf("the value now is %d",i);
continue;
}
printf(" this should be printedn");
}
}
127
For(initialization; test-condition;increment/decrement)
{
Body of loop
}
FOR Loop
 Initialization of the control variables is done first, using an assignment statement such as i=1.
 The value of the control variable is tested using the test condition. The test condition is a
relational expression such as i<2 that determines whether the n loop terminates
 When the body of the loop is executed, the control is transferred back to for statement after
evaluating the last statement in the loop.
 Now control variable is incremented using an assignment statement such as i=i+1
128
for(x=0;x<=10;x=x+1)
{
Printf(“%d”,x)
}
FOR Loop
Additional features of For loop
 More than one variable can be initialized at a time in the for loop
for(n=0,p=1;n<10;n++)
 The test condition may have a compound relation and increment section may also have more
than one part
Sum=0;
For(i=1,j=1; i<20 &&sum<100; ++i,++j)
{
sum=sum+I;
j=j+I;
printf(“%d %d ”,j,sum);
}
129
FOR Loop
Additional features of For loop

m=5;
for( ; m!=50 ;)
we can omit one or more sections of for loop if necessary
130
For(initialization; test-condition;increment/decrement)
{
For(initialization; test-condition;increment/decrement)
{
}
}
for(i=1; i<=5;++i)
{
for(j=1; j<=5;++j)
{
}
}
Nested FOR Loop
131
For(initialization; test-condition;increment/decrement)
{
For(initialization; test-condition;increment/decrement)
{
For(initialization; test-condition;increment/decrement)
{
}
}
}
for(i=1; i<=5;++i)
{
for(j=1; j<=5;++j)
{
for(z=1; z<=5;++z)
{
}
}
}
Nested FOR Loop
132
For Columns loop2
For
Rows
Loop1
For Pattern printing loop3
133
12345678910 11111
22222
33333
44444
55555
1
2
3
4
5
6
7
8
9
10
*****
*****
*****
*****
12345
12345
12345
12345
12345
987654321
*
* * *
* * * * *
* * * * * * *
1
12
123
1234
12345
12345
1234
123
12
1
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
* * * * * * *
* * * * *
* * *
*
1 2 3 4 5 6 7
1 2 3 4 5
1 2 3
1
- - - -1
- - - 2 3
- - 3 4 5
- 4 5 6 7
5 6 7 8 9
LEVEL 1
LEVEL 2
LEVEL 3
S S S S S
S S
S S
S S
S S S S S
134
Write a function in c that Converts Binary Numbers to Decimal
Write a program to find Prime Numbers Between Two Integers
 Pre-condition check:
 if number 1> number 2 swap the two numbers.
135
Write a program to check whether a number is a prime number or not
*without using function*
Write a program to find Prime Numbers Between Two Integers
 Pre-condition check:
 if number 1> number 2 swap the two numbers.
Write a program to find whether a number is an Armstrong number or not
Write a program to print Fibonacci Series
 User specifies the total number of elements to
be printed
The Fibonacci numbers are the numbers in the following integer
sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
ARMSTRONG NUMBER
136
1634, 8208, 9474
Write a program to find whether a number is an Armstrong number or not
137
C Program to draw pascal triangle
LAB WORK
138
FIND ODD NUMBER BETWEEN 1 AND 100
FIND THE SUM OF N NATURAL NUMBERS
FIND THE SUM OF THE FIRST N ODD NUMBERS
FIND THE SUM OF FIRST N EVEN NUMBERS
LAB WORK
C Program to convert decimal numbers to binary
C Program to Convert Binary Numbers to Decimal
139
Functions
140
User Defined Functions
C functions can be classified into two categories, namely:
 Library functions
 User-defined functions
*main is an example of user-defined functions.
If a program is divided into functional parts, independently codes a program called subprograms, in C such
subprograms are called functions.
Function: A function is a self-contained block of code that performs a particular task.
Once a function has been designed it is treated as a black box that takes some data from the main
program and returns a value.
The inner details of operations are invisible to the rest of the program
141
Elements of User DefinedFunctions
 Like variables functions have types (such as int) associated with them
 Like variables, function names and their types must be declared and defined before they are used in the
program.
We need to established three elements that are related to functions
 Function definition
 Function call
 Function declaration
Void printl(void); /*declaration */
Main()
{
printl();
}
Void printl(void)
{
statements……….
------------------------
}
142
Functions definitions
Function definition: A function definition, also known as function implementation shall include the
following elements.
 Function name;
 Function type;
 List of parameters
 Local variables declarations
 Function statements
 Return statement.
Function_type function_name(parameter list)
{
Local variables declaration;
Executable statement;
-------------------
------------------
Return statement;
}
143
Function type
Function type specifies the type of value(like float and double) that the function is expected to return to
the program calling the function.
 if the return type is not explicitly specified , C will assume that it is a integer type.
 if function is not returing anything then we need to specify the return type as
void
Void is one of the fundamental data type in C.
144
Formal parameters List
The parameter list declares the variables that will receive the data sent by the calling program.
They serve as input data to the function to carry out the specified task.
Since they represent actual input values they are called as formal parameters.
The parameters list contains the declaration of variables separated by commas and surrounded by
parentheses.
Float quadratic(int a, int b, int c)
double power(double x, int n)
float mul(float x,floaty)
int sum(int a, int b)
Int sum(int a,b)
Is illegal
145
void
If function has no formal parameters, to indicate the parameter list is empty, we use keyword void
between the parentheses as in
Void printl(void)
{
}
Many compilers accept an empty set of parentheses, without specifying anything as in
void printl()
But is a good programming style to use void to indicate a nill parameter list
146
Function Body
The function body contains:
 Local declaration that specifies the variables
 Function statements
 A return-type statement
*if the function can’t return we can omit the return statement. However, its return type should be
specified as void.
When a function reaches its return statement, the control is transferred back to the calling
program,-----------in Absence of a return statement, the closing brace acts as a void return;
A local variable is a variable that is defined inside a function and used without having any role in the
communication between functions.
Float mul(float x, float y)
{
Float result; /*local variable*/
Result=x*y;
Result(result);
}
147
Return Values and their types
The return type can take one of the following forms:
1) Return; -----------Doesn’t return any value and acts much as closing brace of the function
in C99, if a function is specified as returning a value, the return value must have value associated
with it
Or
2)Return (expression)
The function can return only one value per call
Int product (void)
{
Return (2.33* 5.1)
}
will return the value of 7 (automatically casted to function type)
148
Function calls
A function can be called by simply using the function name followed by list of actual prameters
(or arguments)
Int main()
{
Int y;
Y=mul(5,3);
}
Int mul(int x, int y)
{
Int z;
Z=x*y;
Return (z);
}
Printf(“%d”, mul(p,q));
A function that return values can
be used in expressions like:
If(mul(p,q)>total)
149
Function declaration
All functions in a c program must be declared before they are involved.
A prototype declaration may be placed in two places in a program
 Above all the functions including the main(global prototype)
 Inside a function definition. (local prototype)
The place of declaration of a function defines a region in a program in which the function may
be used by other functions. This region is known as the scope of the functions.
char pri(void);
int main()
{
char x;
x= pri();
printf("%c",x);
}
char pri(void)
{
return 'a';
}
150
int main()
{
char x;
pri();
printf("Fine");
}
void pri(void)
{
printf("how are you");
}
#include<stdio.h>
void swap(int,int);
void main( )
{
int n1,n2;
printf("Enter the two numbersn");
scanf("%d%d",&n1,&n2);
printf("nThe values of n1 and n2 before calling the swap function
are n1=%d n2=%d",n1,n2);
swap(n1,n2);
printf("nThe values of n1 and n2 after calling the swap function
are n1=%d n2=%d",n1,n2);}
151
152
void swap(int n1,int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
printf("nThe values of n1 and n2 after swapping are n1=%d
n2=%d",n1,n2);
}
153
#include<stdio.h>
void prn(int,int);
;
int main()
{
int a,b
int x=10,y=12;
printf("a= %d and b= %d",x,y);
prn(x,y);
}
void prn(int x , int y)
{
a=x+1;
b=y+1;
printf("value of a=%d and value of b=",a,b);
}
154
Write a user-defined function to calculate the Volume of the cylinder where another user-
defined function returns the square of the net radius.
Given that the outer radius is the cylinder is 16cm and the inner radius is 8cm and the height of the
cylinder is 25cm
Write a user-defined function that returns the age in years of a person.
Enter Date of birth details
Day:
month:
Year:
Enter current day:
Enter current month:
Enter current year:
155
Storage classes
156
Storage classes
In some programming languages, variable retains its value throughout the program like BASIC
PROGRAM.
But that is not the case with C programming
It depends on the storage class a variable may assume.
In C , variable not only have data types but the storage classes.
Following are the storage classes , relevant to functions
1. Automatic variables
2. Register variables
3. Static variables
4. External variables
157
Storage classes
Variable have scope, visibility and longevity
Scope: determines over what region of the program a variable is actually available
The scope of a variable is determined at compile-time only
In Simple words, if you use a variable out of its scope compiler will throw an error
Longevity: refers to the period during which a variable retains a given value during execution of a
program
Visibility refers to the accessibility of a variable from the memory
Default definition value:
Memory allocation does not happen in the declaration whereas in definition memory gets
allocated to the variable.
158
Variable declaration is useful when the programmer uses multiple files and when he defines
the variables in one of the files. They are available when linking the program. He can use the
variable in any place. Even though it is possible to declare a variable multiple times in
it only once such as in a file or a function.
What is a Definition in C
The definition of a variable indicates the compiler where and how much storage to create for
the variable. A variable definition defines the data type and a set of one or more variables of
that type. Below is an example of a declaration.
int a, b;
159
Automatic Variables
Automatic Variables: are declared inside a function in which they are utilized,
They are created and destroyed automatically when the function is exited.
They are also called local or internal variables
A variable declared inside a function without storage class specification is by default an automatic
variable
Main()
{
Int number
}
_____________________________________________________________
Main()
{
Auto number
}
#include<stdio.h>
auto int max; //Error, illegal to declare auto with global scope.
int main()
{
auto int min; // Legal syntax
}
10
100
1000
160
Void fun1(void);
Void fun2(void);
Main()
{
Int m=1000;
Fun2();
printf(%d ,m);
}
Void fn1(void)
{
Int m=10;
Printf(“%d”,m);
}
Void fun2(void)
{
Int m=100;
Fun1();
Printf(“%d”, m);
}
161
Register Variables
Register Variables: tells the compiler that the variable should be kept in one of the machine’s registers,
instead of kept in the memory(where normal variables are stored). Since register access is faster than
memory access, keeping the frequently accessed variables (e.g loop variables in the register will lead to
faster execution of programs.
Register int count;
Some compilers allow only int and char variables but ANSI standard doesn’t restrict its
application
C will automatically convert register variables into non-Register variables once the limit is reached
162
Static Variables
Static Variables: the value of static variables persists until the end of the program.
A static variable is declared using static keyword
Static int x;
Static float y;
Internal Static variables are similar to auto variables except they remain in existence (alive)
through out the remainder of the program.
internal static variable can be used to retain values between function calls.
163
#include<stdio.h>
static int out;
// Global static variable implicitly initialized to 0.
void main()
{
static int in = 10;//local static variable explicitly initialized to 10
printf("global: %d, local: %d", out, in);
}
two static variables with the same definition in two different functions refer to two
different memory locations and hence they are not be assumed as a single variable.
For example in the below code,
void fun1()
{ static sInt = 100; }
void fun2()
{ static sInt = 10; }
164
Void stat(void);
Int main()
{
Int I;
For(i=1;i<=3;i++)
{
stat();
}
}
Void stat(void)
{
Int x=0;
x=x+1;
Printf(“%dn, x);
}
Void stat(void);
Int main()
{
Int I;
For(i=1;i<=3;i++)
{
stat();
}
}
Void stat(void)
{
Static Int x=0;
x=x+1;
Printf(“%dn, x);
}
165
#include<stdio.h>
void stat(void);
int main()
{
int i;
for(i=1;i<=3;i++)
{
stat();
}
printf("%d",x);
}
void stat(void)
{
int x=0;
x=x+1;
printf("%dn", x);
}
#include<stdio.h>
void stat(void);
int main()
{
int i;
for(i=1;i<=3;i++)
{
stat();
}
printf("%d",x);
}
void stat(void)
{
static int x=0;
x=x+1;
printf("%dn", x);
}
166
External Variables
External variables: variables that are both alive and active throughout the entire program are known as
external variables. They are also known as global variables.
In case a local variable and global variable have the same name, the Local variable has precedence over
the global variable.
Int fun1(void);
Int x; /*global */
Main()
{
X=10;
Printf(“%d”,x);
Printf(“%d,fun1());
}
Fun1(void)
{
x=x+10;
}
167
External Variables
Global variables available only from the point of declaration to the end of the program.
• Main()
• {
• y=5;
• }
• Int y; /*global declaration*/
• func1()
• {
• y=y+1;
• }
Global variables are initialized with
zero by default
168
Extern Variables
Declare the storage class with the extern.
Main()
{
Extern int y;
}
IT informs the compiler that y is an integer type defined somewhere else in the program
extern declaration doesn’t allocate storage space for variable
Extern keyword:
The extern keyword is used to declare a global variable, it is just a reference to the compiler
that the variable definition is somewhere in the program or in another file
169
#include<stdio.h>
void main() {
extern int m;
m=15;
printf("%d",m);
}
int max;
Extern variables are useless when used in the same
file. They are mainly designed to export global
variables from another file.
#include<stdio.h>
int x;
int main()
{
int y;
printf(“%d %d”, x, y);
}
170
171
#include<stdio.h>
Void main()
{
Extern int i=10;
Printf(“%d”,i);
}
#include<stdio.h>
void main()
{
extern i;
i=10;
printf("%d",i);
}
int i=20;
#include<stdio.h>
void main()
{
extern i;
printf("%d",i);
}
int i=20;
172
Storage Class Scope Lifetime Initial Value
Storage
Location
Auto
Within the
block, in which
it is declared.
Within the
block, in which
it is declared.
Initialized with
garbage value.
RAM
Register
Within the
block, in which
it is defined.
Same as auto,
within the
block in which
it is declared.
Initialized with
garbage value.
Register
Static
Within the
block, in which
it is defined.
Throughout
the main
program.
Zero. RAM
Extern
Global scope,
unbound by
any function.
Same as static,
till the end of
the main
program.
Zero. RA
173
Arrays
C Supports derived data type called array that can be used to store, process ,
print and manipulate large amount of data.
Array is a fixed-sized sequenced collection of elements of the same data type.
The array is classified as one of the data structures in the C
A data structure is a specialized format for organizing, processing, retrieving and storing data.
174
Arrays
Declaration of Array : int number[10]; This declaration is also called as vector
The computer reserves five storage locations:
3
4
1
2
8
Number[0]
Number[1]
Number[2]
Number[3]
Number[4] Subscripts of an array begin with 0 and can
be integer constant, inter variables, or
expression that yields to integers
An array is allocated block of memory for the specified no.
of elements in contiguous or continuous locations by the
compiler.
175
Arrays
Any reference to the array outside the declared limits would not necessarily cause an error. Rather
it might result in unpredictable program results.
C language treats character strings simply as an array of characters.
Char name[10];
“Welcome to”
‘W’ ‘E’ ‘L’ ‘C’ ‘O’ ‘M’ ‘E’ ‘ ’ ‘T’ ‘O’ ‘/0’
float marks[5] = {67, 89.5, 45.8, 60, 48.6};
/* marks contains 5 floats */
Let’s see how these 5 floats are organised in marks,
marks[0] = 67;
marks[1] = 89.5;
marks[2] = 45.8;
marks[3] = 60;
marks[4] = 48.6;
176
Initialization Arrays
Array can be initialized at either of following stages:
At compile time
At run time
Compile Time Initialization
Int number[5]={1,2,3,4,5};
Float marks[5]={1.2,3.5,5.5} // the remaining two elements to
zero in case of number and null in case of character array
The size may be omitted, in such cases, the compiler allocates enough space for all
initialized elements.
int number[ ]={1,2,3,};
177
Initialization Arrays
Char name[ ]={‘c’,’h’,’I’,’t’,’k’,’r’,’a’};
An alternative way is char name [ ]=“chitkara”;
Int number [3]={10,20,30,40};
#include<stdio.h>
int main()
{
char number[3]={'j','o','m','p','i'};
printf("%c",number[3]);
}
178
#include<stdio.h>
int main()
{
int number[3]={1,2};
printf("%d",number[2]);
}
#include<stdio.h>
int main()
{
int number[3]={1,2};
printf("%d",number[3]);
}
#include<stdio.h>
int main()
{
char number[3]={'j','o'};
printf("%c",number[2]);
}
#include<stdio.h>
int main()
{
char number[3]={'j','o'};
printf("%s",number[2]);
}
179
Initialization Arrays
Run Time Initialization
Passing array to a function 180
#include <stdio.h>
void display(int r1, int r2)
{
printf("%dn", r1);
printf("%dn", r2); }
int main()
{
int rollno[] = {2, 8, 4, 12}
display(rollno[0], rollno[1]);
return 0;
}
181
float calculateSum(float num[]);
int main()
{
float rollno[] = {2, 5, 6, 3, 4, 8};
result = cadd(rollno);
}
float calculateSum(int abc[])
{
}
WRITE A PROGRAM TO SORT AN N-ELEMENTS ARRAY
182
WRITE A C PROGRAM FOR LINEAR SEARCH IN C
FIND THE LARGEST ELEMENT IN AN ARRAY
FIND THE SUM OF ALL THE ELEMENTS IN AN ARRAY
NOTE : PASS ARRAY TO A FUNCTION WHICH CALCULATES THE SUM OF THE ARRAY
STORE THE ELEMENTS OF ONE ARRAY IN OTHER ARRAY BUT IN REVERSE
ORDER
C PROGRAM TO INSERT AN ELEMENT IN AN ARRAY
183
String in C
The string can be defined as the one-dimensional array of characters terminated by a
null ('0’).
There are two ways to declare a string in c language.
1.By char array
char ch[8]={‘C', ’h', ’i’, ’t', ’k', ’a', ’r', ’a', '0'};
By string literal
Char ch[]=“chitkara”;
We need to add the null character '0' at the end of the array by ourself whereas, it is appended
internally by the compiler in the case of the character array.
184
String functions (strlen)
strlen() function:The strlen() function returns the length of the given string
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'c', 'h', 'i', 't', 'k', 'a', 'r', 'a','0', 'n'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
185
String functions (strcpy) and
strncpy
The strcpy(destination, source) function copies the source string in destination.
1.#include<stdio.h>
2.#include <string.h>
3.int main(){
4. char name[4]={‘c’,’a’,’n’,’t’};
5. char name2[4];
6. strcpy(name2,name);
7. printf("Value of second string is: %s",name2);
8. return 0;
9.}
strncpy
strncpy(s1, s2, n) copies the first ‘n’ characters of the second string s2 to the first string s1
186
String functions (strcat)
The strcat(first_string, second_string) function concatenates two strings and result is returned
to first_string
#include<stdio.h>
#include <string.h>
int main(){
char ch[6]={'h', 'e', 'l', 'l', 'o'};
char ch2[3]={'c','i'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
187
String functions (strncat)
strncpy
strncpy(s1, s2, n) copies the first ‘n’ characters of the second string s2 to the first string s1.
char s2[ ]= "Hello";
char s1[10];
strncpy(s1, s2, 2);
188
String functions (strcmp)
strcmp
strcmp(s1, s2) compares two strings and finds out whether they are same or different.
It compares the two strings character by character till there is a mismatch.
If the two strings are identical, it returns a 0.
If not, then it returns -1.
strncmp
strncmp(s1, s2, n) compares the first ‘n’ characters of s1 and s2.
If the two strings are identical, it returns a 0.
If not, it may return the difference between the ASCII values of the first non-matching pair of
characters.
189
#include <stdio.h>
#include <string.h>
int main()
{
char s1[ ]= "Healo";
char s2[ ]= "Hebld";
int i, j;
i = strcmp(s1, "Hello");
j = strncmp(s1,s2,3);
printf("%d n %dn", i, j);
return 0;
}
-1
-1
#include <stdio.h>
#include <string.h>
int main()
{
char s1[ ]= "Heblo";
char s2[ ]= "Heald";
int i, j;
i = strcmp(s1, "Hello");
j = strncmp(s1,s2,3);
printf("%d n %dn", i, j);
return 0;
}
-1
1
190
String functions __
The strrev(string) function returns reverse of the given string.
The strlwr(string) function returns string characters in lowercase. Let's see a simple example
of strlwr() function.
The strupr(string) function returns string characters in uppercase. Let's see a simple example
of strupr() function.
Memory Layout of C program
191
192
193
C program contains five segments
these are :
text segment.
DS (Data Segment) and
BSS (block started by symbol),
heap segment,
the stack segment
194
Text Segment
 A text segment, also known as a code segment or simply as text, which contains executable
instructions.(compiled program instructions)
 text segment may be placed below the heap or stack(low memory address) in order to
prevent heaps and stack overflows from overwriting it.
 the text segment is sharable so that only a single copy needs to be in memory for frequently
executed programs, the text segment is often read-only, to prevent a program from
accidentally modifying its instructions
195
Data Segment
DS(Initialized data segment):
•It contains the explicitly initialized global and static variables.
•The size of this segment is determined by the size of the values in the program’s source code and does
not change at run time.
•It has read-write permission so the value of the variable of this segment can be changed at run time.
int global_var = 50; //read write permission
const int global_var2 = 30 //read-only permission
196
BSS Segment
BSS _[block staring segment](Uninitialized data segment): //block starting symbol
•It contains all uninitialized global and static variables.
•All variables in this segment initialized by the zero(0) and pointer with the null pointer.
•The program loader allocates memory for the BSS section when it loads the program.
197
Heap Segment
Heap:
•It is used to allocate the memory at run time.
•Heap area managed by the memory management functions like malloc, calloc, free, etc which may
internally use the brk and sbrk system calls to adjust its size.
198
Stack Segment
•It is located at a higher address and grows and shrinks opposite to the heap segment.
•The stack contains local variables from functions and related book-keeping data.
•Each function has one stack frame.
•Stack frames contain the function’s local variables arguments and return value.
•The stack contains a LIFO structure. Function variables are pushed onto the stack when called and
functions variables are popped off the stack when return.
•SP(stack pointer) register tracks the top of the stack.
199
#include<stdio.h>
int main()
{
return 0;
}
Text Segment
200
#include<stdio.h>
int main()
{
return 0;
}
Text Segment
201
#include<stdio.h>
int x=10;
int main()
{
return 0;
}
Data segment
202
#include<stdio.h>
Int y;
int x=10;
int main()
{
return 0;
}
BSS segment
203
Stack
Heap
Bss Segment
Data segment
Text segment
#include<stdio.h>
int a=10;
int b=10;
int c=10;
int main()
{
int vol=volume();
printf("the volume =%d“,vol);
}
int volume()
{
int ar=area(a,b);
int volume= ar*c;
return volume;
}
int area(int x, int y)
{
int area=x*y;
return area;
}
a=10
b=10
C=10
Main()
Int vol
Printf()
return
Volume()
ar, volume
return
area()
X,y,area
return
Pointers
204
205
 Pointer is a derived data type
• Pointer contains the memory addresses
• Pointer are used to manipulate the data stored in the memory
Pointers are most efficient in handling arrays
Pointers can be used to return multiple values from a function via function arguments.
Pointers allow c to support dynamic memory allocation
Pointers reduce the length and complexity of programs.
They increase execution speed
Each cell , commonly known as byte has
number called address
206
Int quantity =179;
The system finds a location for the integer variable quantity and puts the value
179 in that location
let us suppose system chose the address 5000 for quantity
179
quantity
5000
v
a
r
i
a
b
l
e
a
d
d
r
e
s
s
v
a
l
u
e
Same like house name with house number
We can access
value with
quantity or
address
207
Since memory address is like number we can assign it to variable and save it in memory.
Such variable that hold memory address are called pointer variables
A pointer variable is a variable that holds the address, which is
the location of another variable in memory
variable value address
quantity 179 5000
p 5000 5078
Since the value of variable p is the address of the variable
quantity we may access the value of quantity by using the
value of p
The variable p points to variable quantity thus p gets the name
pointer
208
Pointer constant: Memory address within a computer are called pointer
constant. We can not change them; we can use them to store data values
Pointer values: we can not save the value of memory address directly. We
can obtain value through variable stored there using address operator &.
The value thus obtained is called pointer value
Pointer Variable: After getting pointer value, it can be stored into another
variable called pointer variable
209
Accessing the Address of a variable
1. The actual location of a variable is machine dependent
p=&quantity
Would assign the address(say 5000) to p
& operator can be used with simple variables or the element of an array.
Illegal use of & operator:
1. &125
2. Int x[30]
&x;
3. &(x+y)
Program………
210
Declaring a pointer variable
1. Every variable must be declared for its type.
1. Pointer variable contains the address that belong to separate data type they must be
declared as pointer.
211
Datatype *pointer_name;
Int *p;
declares the variable p as a pointer variable that points to an integer data type
Important: int refers to the data type of the variable being pointed to by p
Float *x;
X as a pointer to floating point variable;
The declaration cause the compiler to allocate memory locations for the pointer variables p and x.
since the memory location have not been assigned any values, these location may contain some
unknown values
212
Int *p p
? Unknown location
Int* p;
Int *p;
Int * p;
213
Initialization of pointer variable
1. The process of assigning the address of a variable to a pointer variable is called
initialization.
Int *p;
p=&quantity;
Or
Int *p=&quantity;
214
Float a,b;
Int x, *p;
p=&a //wrong
We declare pointer as int type, the system assumes that any address that the pointer will hold
will point to an integer variable.
Compiler doesn’t detect such errors. So be careful to avoid wrong pointer assignment
We can also define
pointer variable with NULL
or 0.
Int *p=NULL
Or
Int *p=0;
215
Accessing a variable through its pointer
1. How to access the value of the variable using pointer?
This can be done using unary operator *(asterisk)
Int quantity, *p, n;
Quantity=10;
p=&quantity;
n=*p
n=*&quantity
216
Symbol Name Description
& Address of operator
Used to find the
address of a variable
∗ Indirection operator
Used to access the
value at an address
217
#include<stdio.h>
int main()
{
int x,*p1, **p2;
x=100;
p1=&x;
p2=&p1;
printf("%dn",p1);
printf("%d",*p2);
printf("%d",**p2);
}
218
Chain of pointers
It is possible to make a pointer to point to another pointer, thus creating a chain of pointers.
Address
2
Address
1
value
p2 variable
p1
This is knows a multiple indirections
Int **p2
This declaration tells the compiler that p2 is a pointer
to a pointer of int type. P2 is pointer to a integer but
pointer to an integer pointer
219
Pointer Expression
Like other variables , pointe variables can be used in
expression, e.g if p1 and p2 are properly initialized
then
Y=*p1 * p2;
Z=*p2/ *p1;
C allows us to add and subtract integers from pointers.
 P1+4;
 P2-2;
 P1-p2 are allowed if both pointer are of same array.
-then p1-p2 gives the number of elements b/w p1
and p2;
P1>p2 or p1==p2, are allowed , if they don’t refer to separate and
un realted variables.
P1/p2 or p1*p2 or p1/5 are
not allowed
a=2
b7=
Z=8
220
Write a program to illustrate the use of pointer in arithmetic operations
int main()
{
int a, b, *p1, *p2, x,y,z;
a=12;
b=4;
p1=&a;
p2=&b;
x=*p1 * *p2 -6;
y= 4* -*p2/ *p1 +10;
*p2=*p2+3;
*p1=*p2 -5;
z=*p1 * *p2 -6;
printf( "a= %d ,b =%dn",a,b);
printf("z=%d",z);
}
221
Pointer increment and Scale factor
P2=P2+2;
P1=p1+1;
It will cause the pointer say p1 to next value of its type,
e.g if p1 has value 62280 the after increment by 1 new value will be
62284;
Its value is increase by length of data type called the scale factor
222
#include<stdio.h>
int main()
{
int a, b, *p1, *p2, x,y,z;
a=12;
b=4;
p1=&a;
p2=&b;
x=*p1 * *p2 -6;
y= 4* -*p2/ *p1 +10;
*p2=*p2+3;
*p1=*p2 -5;
z=*p1 * *p2 -6;
printf( "a= %d ,b =%dn",a,b);
printf("z=%d",z);
printf("-------------------------n");
printf("%dn",p1);
p1=p1+1;
printf("%dn",p1);
}
223
Pointers and Arrays
When array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations.
The base address is the location of first element
1 2 3 4 5 6 7
1000 1004 1008 1012 1016 1020 1024
Address of x[4]=Base address + (4 X scale of data type)
1000+4X4= 1016;
Now instead of using index we
can use now pointer to access
the array elements;
P+4;
Which is faster than using
indexing
#include<stdio.h>
int main()
{
int *p ,sum;
int x[5]={5,9,6,3,7};
int i=0;
p=x;
printf("Elements value address");
while(i<5)
{
printf("x[%d] %d %un",i,*p,p);
sum=sum + *p;
i++,p++;
}
printf("n sum= %dn",sum);
printf("n x[0]= %un",&x[0]);
printf("p= %u",p);
ret
224
Write a program using pointers to compute the sum of all elements stored in an array
225
Pointers and character Strings
String are treated like character arrays and therefore they are declared and initialized as follows :
Char str[5]=“hello” ;
Compiler automatically inserts null character ‘0’ at end of string.
Alternative method C supports :
Char *str=“good”;
IT stores address in the pointer variable str.
H E L L O 0
str
226
Run time Assignment:
Char *string1;
String1=“good”;
To print the content of string String1:
Printf(“%s”,string1)
No need to used indirection operator * here
#include<stdio.h>
int main()
{
char *name;
int length;
name="hello";
char *cptr=name;;
printf("%sn",name);
printf("%dn",name);
printf("%dn",cptr);
while(*cptr != '0')
{
printf("%c is stored at %un",*cptr,cptr);
cptr++;
}
length=cptr-name;
printf("n length of string =%d",length);
return 0;
}
227
With the help of pointers, sort an array?
5,7,3,8,9,2
Write a program using pointers to determine the length of characters In string
228
int main()
{int prime[5] = {2,3,5,7,11};
printf("Result using &prime = %dn",&prime);
printf("Result using prime = %dn",prime);
printf("Result using &prime[0] = %dn",&prime[0]);
}
int main()
{
int prime[5] = {2,3,5,7,11};
printf("Result using &prime = %dn",&prime + 1);
printf("Result using prime = %dn",prime + 1);
printf("Result using &prime[0] = %dn",&prime[0] + 1);
}
229
Pointer as function arguments
When we pass the address to a function, the parameters receiving the addresses should be pointer.
The process of calling a function using pointers to pass the address of variable is known as call by
reference.
The function which is called by reference can change the value of the variable used in the
call
Int main()
{
Show(&x);
}
Change(int *p)
{
}
#include<stdio.h>
int main()
{
int x,y;
x=100;
y=200;
printf("before exhange x=%d,y=%dn",x,y);
swap(&x,&y);
printf("After exhange x=%d,y=%dn",x,y);
}
void swap(int *a, int *b)
{
int temp =*a;
*a=*b;
*b=temp;
}
Write a function using pointer to exchange the values stored in two location in memory
230
Function returning pointers
THE FUNCTION CAN RETURN MULTIPLE VALUES THROUGH POINTER PARAMETER. WE
CAN FORCE A FUNCTION TO RETURN A POINTER TO THE CALLING FUNCTION
231
Main()
{
Int a=10;
Int b=20;
Int *p;
P=larger(&a,&b)
Print(“%d”,*p);
Int *larger(int *x , int *y)
{
If(*x>*y)
Return x ; //address of x
}
Else
Return y; //address of y
#include <stdio.h>
void greatestOfAll( int *p){
int max = *p;
for(int i=0; i < 5; i++){
if(*(p+i) > max)
max = *(p+i);
}
printf("The largest element is %dn",max);
}
main(){
int myNumbers[5] = { 34, 65, -456, 0, 3455};
greatestOfAll(myNumbers);
/* Prints :The largest element is 3455" */
}
232
Create a function and Find the largest element in the array by passing address of array to the function(take help of
pointer/s. Also find the size of array both in main function using sizeof operator
233
234
Write a program in c That passes array as a parameter to function and then adds value
3 to the each element in array using pointers and then updated array is printed in
the main function
Int main()
{
Define array
Call function(array name)
Prints updated array;
}
Function(-------)
{
Adds 3 to each element
}
Given that Elements of array are: 5 6 4 3 2 7
After adding 3: 8,9,7,6,5,10
235
Use sizeof operator find the size of an integer array
236
Pointers to Functions
#include <stdio.h>
int main()
{
printf("Address of main() function is %p",&main);
return 0;
}
237
Pointers to Functions
A function like variable has type and address location in the memory.
it is possible to declare a pointer to a function, which can then be used as a
argument in another function
A pointer to function is decalred as:
Type (*fptr) ();
This tells compiler that fptr is a pointer to a function, which return type value. The
parentheses around around *fptr are necessary .
Statement type *large() would declare large as function returning a pointer to
type
238
int mul(int, int);
Int (*p) ();
P1=mul; //p1 to point mul
We can use the pointer p1 with list of parameters that is
(*p1)(x,y); is same as mul(x,y)
239
1.include <stdio.h>
2.void func1(void (*ptr)());
3.void func2();
4.int main()
5.{
6. func1(func2);
7. return 0;
8.}
9.void func1(void (*ptr)())
10.{
11. printf("Function1 is called");
12. (*ptr)();
13.}
14.void func2()
15.{
16. printf("nFunction2 is called");
17.}
Passing a function's address as an argument to other function
240
#include<stdio.h>
#define PI 3.14
double y(double);
double table(double(*f)(),double, double,double);
int main()
{
printf("Table of y(x)=2*x*x-x+1nn");
table(y,0.0,2.0,0.5);
table(cos,0.0,PI,0.5);
}
double table(double (*f)(), double min, double max,double step)
{
double a,value;
for(a=min; a<=max;a+=step)
{
value=(*f)(a);
printf("%lfn",value);
}
}
double y(double x)
{
return (2*x*x-x+1);
}
241
#include<stdio.h>
int length(int (*fp)(),int l,int b);
int volume();
int main()
{
int l=10;
int b=20;
length(volume,l,b);
}
int length(int (*fp)(),int l,int b)
{
int z=(*fp)();
printf("%d",z*l*b);
}
int volume()
{
return 30;
}
242
#include<stdio.h>
int *add(int*, int*);
int main()
{
int a=10;
int b=12;
int* (*fp)();
fp=add;
int *z=(*fp)(&a,&b);
z=z+20;
printf("%d",z);
}
int *add(int *x, int *y)
{
*x=*x+*y;
printf("%dn",*x);
return x;
}
243
Create a function and swap two arrays with the help of pointers
244
const Pointer in C
A constant pointer in C cannot change the address of the
variable to which it is pointing, i.e., the address will remain
constant. Therefore, we can say that if a constant pointer is
pointing to some variable, then it cannot point to any other
variable.
int *const ptr;
1. int *const ptr;
2. ptr=&a;
3. ptr=&b
245
Pointer to Constant
A pointer to constant is a pointer through which the value of the variable that the
pointer points cannot be changed. The address of these pointers can be changed,
but the value of the variable that the pointer points cannot be changed.
1.const int* ptr;
2. ptr=&b;
3. *ptr=10;
246
Constant Pointer to a Constant
A constant pointer to a constant is a pointer, which is a combination
of the above two pointers. It can neither change the address of the
variable to which it is pointing nor it can change the value placed at
this address.
1. const int* const ptr=&a;
2. *ptr=12;
3. ptr=&b;
4. printf("Value of ptr is :%d",*ptr);
247
void pointer in C
if we declare the int pointer, then this int pointer cannot point to the float variable or some other type of
variable
A pointer to void means a generic pointer that can point to any data type
•Dereferencing a void pointer in C
we print the value of the variable which is pointed by the void pointer 'ptr' by using the
statement given below:
*(int*)ptr;
5 marks question
248
The company was established in 2010 and it was decided that 5 employees were going
to work in the company, So a programmer hired at that time to develop a program for
the company decided to declare an array of size 5 that contains the integer employee id
greater than zero, but, only 3 persons joined the company having employee id 12,13,14
and the vacancy of two employees is still pending. As now you are hired in the same
company as a programmer you are requested to display the current content of the
same array and also the total number of elements(current employees) without
modifying the previous array(size/empid)
Given :
Int empid[5]={12,13,14}
Constraint: As the vacancy of two employees is pending, if they joined their entry is to be done in the same
array and your program must display all the empid’s and count(i.e 5) without changing any line of code.
10 marks question
249
Q1 Write a c program to copy one array to another using pointers
Q2 Write a program to find the reverse of a string using pointers;
Q3 A company needs a program that can manage its inventory of products. Each product has a
name, ID number, price, and quantity in stock. Write a C program that can perform the
following tasks:
1. Add a new product to the inventory by accepting input for the name, ID number, price, and
quantity in stock.
2. Display the current inventory by listing all products and their corresponding information. 3.
Search for a product by ID number and display its information.
4. Exit the program
250
suppose the input list contains the following integer values:
[10, 20, 30, 20, 40, 10, 50, 30]
The program should recognize that the values 10, 20, and 30 are duplicates, and discard all
but one of them, resulting in the following list:
[10, 20, 30, 40, 50]
suppose the input list contains the following integer values:
[10, 20, 30, 20, 40, 10, 50, 30]
The program should recognize that the values 10, 20, and 30 are duplicates, and discard all
of them, resulting in the following list:
[30, 40, 50]
251
2D Arrays
252
2D array will store the data in table form like matrix
consisting of rows and columns
Type Array_name[row size][column size]
253
12 [0][0] 14[0][1] 12[0][2]
34[1][0] 45[1][1] 67[1][2]
23[2][1] 45[2][1] 67[2][1]
Col 0 Col 1 Col 2
Row 0
Row 1
Row 2
254
Initialization of 2D Array in C
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
255
1.Int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
2.for(i=0;i<4;i++){
3. for(j=0;j<3;j++){
4. printf("arr[%d] [%d] = %d n",i,j,arr[i][j]);
Write a program that do the Sum of two matrices of
size 2x2 and stores the result in third matrix
256
Write a program and Transport the matrix
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 6 9
257
258
For example:
#include <stdio.h>
int main(void) {
int m,n; int arr[] = {4, 3, 1, 2};
int *p = arr;
}
Now suppose we want a pointer to point to a 2D array. We saw a single pointer can point to
an entire 1D array. So all we need to do is create a pointer for each row/column of the 2D
array.
#include <stdio.h>
int main(void) {
int arr[2][3] = {{3, 2, 1}, {8, 9, 10}};
int *p[2];
p[0] = arr[0]; //Pointer points to first row of 2D array
p[1] = arr[1]; //Pointer points to second row of 2D array
}
Address of 3 Address of 4
3 2 1 4 3 1 2
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx
C programming .pptx

More Related Content

What's hot

Os Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual MemoryOs Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual Memorysgpraju
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing fileskeeeerty
 
Floating point representation
Floating point representationFloating point representation
Floating point representationmissstevenson01
 
Operating system Memory management
Operating system Memory management Operating system Memory management
Operating system Memory management Shashank Asthana
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonAhmed Salama
 
National 5 Computing Science - Testing
National 5 Computing Science - TestingNational 5 Computing Science - Testing
National 5 Computing Science - TestingForrester High School
 
Paging and Segmentation in Operating System
Paging and Segmentation in Operating SystemPaging and Segmentation in Operating System
Paging and Segmentation in Operating SystemRaj Mohan
 
Error Correction And Hamming Code Ibrar
Error Correction And Hamming Code IbrarError Correction And Hamming Code Ibrar
Error Correction And Hamming Code Ibraribrar562
 
Operating system 11 system calls
Operating system 11 system callsOperating system 11 system calls
Operating system 11 system callsVaibhav Khanna
 

What's hot (20)

Hashing
HashingHashing
Hashing
 
File operations
File operationsFile operations
File operations
 
Os Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual MemoryOs Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual Memory
 
Pci,usb,scsi bus
Pci,usb,scsi busPci,usb,scsi bus
Pci,usb,scsi bus
 
Ca basic computer organization
Ca basic computer organizationCa basic computer organization
Ca basic computer organization
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 
Memory Organization
Memory OrganizationMemory Organization
Memory Organization
 
Floating point representation
Floating point representationFloating point representation
Floating point representation
 
Operating system Memory management
Operating system Memory management Operating system Memory management
Operating system Memory management
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
File system vs DBMS
File system vs DBMSFile system vs DBMS
File system vs DBMS
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
National 5 Computing Science - Testing
National 5 Computing Science - TestingNational 5 Computing Science - Testing
National 5 Computing Science - Testing
 
Paging and Segmentation in Operating System
Paging and Segmentation in Operating SystemPaging and Segmentation in Operating System
Paging and Segmentation in Operating System
 
Error Correction And Hamming Code Ibrar
Error Correction And Hamming Code IbrarError Correction And Hamming Code Ibrar
Error Correction And Hamming Code Ibrar
 
Instruction format
Instruction formatInstruction format
Instruction format
 
Operating system 11 system calls
Operating system 11 system callsOperating system 11 system calls
Operating system 11 system calls
 
Hamming code checksum
Hamming code  checksumHamming code  checksum
Hamming code checksum
 
Linker and Loader
Linker and Loader Linker and Loader
Linker and Loader
 
LISP: Introduction to lisp
LISP: Introduction to lispLISP: Introduction to lisp
LISP: Introduction to lisp
 

Similar to C programming .pptx

Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)TejaswiB4
 
Fundamentals of programming with C++
Fundamentals of programming with C++Fundamentals of programming with C++
Fundamentals of programming with C++Seble Nigussie
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfMMRF2
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsOMWOMA JACKSON
 
Programming_Lecture_1.pptx
Programming_Lecture_1.pptxProgramming_Lecture_1.pptx
Programming_Lecture_1.pptxshoaibkhan716300
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 
Stnotes doc 5
Stnotes doc 5Stnotes doc 5
Stnotes doc 5Alok Jain
 
10th class computer science notes in english by cstechz
10th class computer science notes in english by cstechz10th class computer science notes in english by cstechz
10th class computer science notes in english by cstechzShahbaz Ahmad
 
Computer Programming Computer Programming
Computer Programming Computer ProgrammingComputer Programming Computer Programming
Computer Programming Computer Programmingarifhasan88
 
Program design and problem solving techniques
Program design and problem solving techniquesProgram design and problem solving techniques
Program design and problem solving techniquesDokka Srinivasu
 
TOPIC-1-Introduction and Preliminaries.pdf
TOPIC-1-Introduction and Preliminaries.pdfTOPIC-1-Introduction and Preliminaries.pdf
TOPIC-1-Introduction and Preliminaries.pdfEjazAlam23
 
PCCF UNIT 1.pptx
PCCF UNIT 1.pptxPCCF UNIT 1.pptx
PCCF UNIT 1.pptxDivyaKS12
 

Similar to C programming .pptx (20)

Lecture 1-3.ppt
Lecture 1-3.pptLecture 1-3.ppt
Lecture 1-3.ppt
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)
 
Problem solving methodology
Problem solving methodologyProblem solving methodology
Problem solving methodology
 
Algorithm to programs.pptx
Algorithm to programs.pptxAlgorithm to programs.pptx
Algorithm to programs.pptx
 
Fundamentals of programming with C++
Fundamentals of programming with C++Fundamentals of programming with C++
Fundamentals of programming with C++
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdf
 
01 Programming Fundamentals.pptx
01 Programming Fundamentals.pptx01 Programming Fundamentals.pptx
01 Programming Fundamentals.pptx
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentals
 
Programming_Lecture_1.pptx
Programming_Lecture_1.pptxProgramming_Lecture_1.pptx
Programming_Lecture_1.pptx
 
Introduction.pptx
Introduction.pptxIntroduction.pptx
Introduction.pptx
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
3 algorithm-and-flowchart
3 algorithm-and-flowchart3 algorithm-and-flowchart
3 algorithm-and-flowchart
 
Stnotes doc 5
Stnotes doc 5Stnotes doc 5
Stnotes doc 5
 
10th class computer science notes in english by cstechz
10th class computer science notes in english by cstechz10th class computer science notes in english by cstechz
10th class computer science notes in english by cstechz
 
Computer Programming Computer Programming
Computer Programming Computer ProgrammingComputer Programming Computer Programming
Computer Programming Computer Programming
 
Program design and problem solving techniques
Program design and problem solving techniquesProgram design and problem solving techniques
Program design and problem solving techniques
 
Computer programming
Computer programmingComputer programming
Computer programming
 
TOPIC-1-Introduction and Preliminaries.pdf
TOPIC-1-Introduction and Preliminaries.pdfTOPIC-1-Introduction and Preliminaries.pdf
TOPIC-1-Introduction and Preliminaries.pdf
 
PCCF UNIT 1.pptx
PCCF UNIT 1.pptxPCCF UNIT 1.pptx
PCCF UNIT 1.pptx
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

C programming .pptx

  • 4. 4 Stages of Problem solving “Computer programmers are problem solvers” Problem-Solving: It is the act of identifying the problems and implementing the best possible solutions. It is the job of the programmer to write down the solution To solve a problem with one needs to pass through certain stages/steps. Steps in Problem-Solving: •Identify the problem •Define the context of the problem •Explore possible strategies •Act on the best solution •Coding and implementation. •Look back and learn
  • 5. 5 •Identify the problem Define Problem The first step in solving a problem is understanding what that problem actually is. You need to be sure that you're dealing with the real problem. To really solve the problem, it's important to find out what started it all. This is called identifying the root cause However, defining a problem doesn't mean deciding how to solve it straight away. It's important to look at the issue from a variety of perspectives. If you commit yourself too early, you can end up with a short-sighted solution As you define your problem, you'll often discover just how complicated it is. •Define the context of the problem
  • 6. 6 Problem-solving steps A.Use of specific Example: Focusing on a particular problem can give us the foothold we need for making a start on the solution to the general problem. B. Similarities among problems:  Check similarities between the current problem and past problems which we have solved  more experience one has with tools and techniques, more efficiently he/she can tackle the given problem.  But sometimes it blocks us from discovering a desirable or better solution to the problem C. Working backward from the solution: We have a solution to a problem and then try to work backward to the starting point. The “Work Backward” method works well for problems where a series of operations is done on an unknown number and you’re only given the result. Explore the strategies
  • 7. 7 Problem-solving steps Working backward from the solution: Example Sam’s mom left a plate of cookies on the counter. Sam ate 2 of them, his dad ate 3 of them and they gave 12 to the neighbor. At the end of the day, only 4 cookies were left on the plate. How many cookies did she make altogether?
  • 8. 8 General Problem solving Strategies Problem-solving strategies don’t guarantee a solution, but they do help guide you through the process of finding a resolution. Often we phrase a problem in one of the following strategies: 1. trial and error. In other words, you try different solutions until you find one that works. 2. Divide and Conquer: E.g Merge Sort
  • 9. 9
  • 11. 11 Coding and implementation. A flowchart is a diagram that depicts a process, system or computer algorithm. They are widely used in multiple fields to document, study, plan, improve and communicate often complex processes in clear, easy-to-understand diagrams Start/End Symbol The terminator symbol marks the starting or ending point of the system. It usually contains the word "Start" or "End." Action or Process Symbol A box can represent a single step ("add two cups of flour"), or an entire sub-process ("make bread") within a larger process. Document Symbol A printed document or report Multiple Documents Symbol Represents multiple documents in the process Decision Symbol A decision or branching point. Lines representing different decisions emerge from different points of the diamond.
  • 12. 12 Input/Output Symbol Represents material or information entering or or leaving the system, such as customer order order (input) or a product (output). Preparation Symbol Represents a set-up to another step in the process. Connector Symbol Indicates that the flow continues where a matching symbol (containing the same letter) has been placed Delay Symbol Indicates a delay in the process. Database Symbol Indicates a list of information with a standard structure that allows for searching and sorting Display Symbol Indicates a step that displays informatio
  • 13. 13
  • 14. 14
  • 15. 15 What is an Algorithm? A sequence of steps to solve a given problem is called as algorithm. Thus, an algorithm is a step-by-step procedure developed for solving a given problem. An algorithm consists of sequences, iterations, selections, etc What is a Pseudocode? Pseudocode is an informal method of developing an algorithm. Thus, computer programmers use simple informal language to write a pseudocode. It does not have any specific syntax to follow. The main difference between an algorithm and a pseudocode is that an algorithm is a step-by-step procedure to solve a given problem while a pseudocode is a method of writing an algorithm. Yes, algorithms can be known as pseudocodes. They are sometimes considered as pseudocodes. Whereas pseudocodes can not be considered as algorithms as they might not carry exact information required to carryout the solution to the problem
  • 16. 16 1. Start from the leftmost element of arr[] and one by one compare x with each element of arr[]. 2. 2. If x matches with an element, return the index. 3. 3. If x doesn’t match with any of elements, return -1. Algorithm of linear search Pseudocode for Linear Search : FUNCTION linearSearch(list, searchTerm): FOR index FROM 0 -> length(list): IF list[index] == searchTerm THEN RETURN index ENDIF ENDLOOP RETURN -1 END FUNCTION In here, we haven’t used any specific programming language but wrote the steps of a linear search in a simpler form which can be further modified into a proper program
  • 17. 17 Algorithm vs Pseudocode vs Program: 1.An algorithm is defined as a well-defined sequence of steps that provides a solution for a given problem, whereas a pseudocode is one of the methods that can be used to represent an algorithm. 2.While algorithms are generally written in a natural language or plain English language, pseudocode is written in a format that is similar to the structure of a high-level programming language. Program on the other hand allows us to write a code in a particular programming language.
  • 18. 18 Test and Debug Debugging •Debugging: Debugging is the process of finding and resolving defects or problems within a computer program that prevent correct operation of computer software or a system. •
  • 19. 19 Programming errors Syntax errors : •misspelling a statement, eg writing prit instead of print •using a variable before it has been declared •missing brackets, eg opening a bracket, but not closing it Logic errors • A logic error is an error in the way a program works. The program can run but does not do what it is expected to do. • unintentionally creating a situation where an infinite loop may occur Runtime errors A runtime error is an error that takes place during the running of a program. An example is writing a program that tries to access the sixth item in an array that only contains five items. A runtime error is likely to crash the program.
  • 21. What is a programming language? 21 To communicate with a person, we need a specific language. Language is a mode of communication that is used to share ideas, opinions with each other. Language? A programming language is a computer language that is used to communicate with computers.. Programming Language?
  • 22. What is a programming language? 22 A programming language is used to develop software programs, or A programming language contains sets of instructions for computers to execute. A programming language is mainly used to develop desktop applications, websites, and mobile applications, system programs etc.
  • 23. 23 Types of programming language Low level programming language Assembly Language Machine Language High level programming language Procedural Oriented programming language Object Oriented Programming Language C C++ Java PHP Android Java script Python
  • 24. 24 Machine code or object code: Computers directly understand the machine language program. The lowest level of software is machine code. Other programming languages are converted to machine code before being executed by the computer. Machine code consists of the CPU’s directly comprehensible binary instructions. Binary is the most common format. Machine Code For example, take ASCII, the ‘01000001’ bit pattern represents the ‘A’ letter. ASCII, abbreviated from American Standard Code for Information Interchange: Character encoding standard for electronic communication.
  • 25. 25 The assembler language is the symbolic programming language that lies close to the machine language in form and content. The assembler language is useful when: ->You need to control your program closely, down to the byte and even the bit level. ->Assembly Language is expressed in a more human readable form than the binary instructions Assembly Language . MOV A,[1] MOV B,[2] ADD A,B MULT A,B
  • 26. 26 High-level programming language (HLL) is designed for developing user-friendly software programs and websites. This programming language requires a compiler or interpreter to translate the program into machine language (execute the program). Example: Python, Java, JavaScript, PHP, C#, High level Programming Language
  • 27. 27 Middle-level programming language lies between the low-level programming language and high-level programming language. It is also known as the intermediate programming language or pseudo-language. A middle-level programming language's advantages are that it supports the features of high-level programming i.e. it is a user-friendly language, and closely related to machine language and human language. Example: C language Middle-level programming language C programming supports Inline assembly language programs. We can directly access system registers with the help of inline assembly language feature in C. C programming is used to access memory directly using a pointer. The actual Linux kernel code is only in C and Assembly.
  • 28. 28 History of C Date Language 1960 ALGOL International group 1967 BCPL Martin Richards 1970 B Ken Thompson 1972 TRADITIONAL C Dennis Ritchie at Bell Laboratories 1978 K&R C Kernighan and Ritchie 1989 ANSI C ANSI Committee 1990 ANSI/ISO C ISO Committee 1999 C99 Standardization Committee
  • 29. 29 ALGOL: Algorithmic Language BCPL:Basic Combined Programming Language. C: become more popular after the publication of the book “ The C Programming Language” by Kernighan and Dennis Ritchie in 1978. and language was known as K&R C. Growth of C led to development of different version of the language that were similar but often incompatible. To assure that C remains standard, in 1983, American National Standards Institute(ANSI) appointed a technical committee to define standard for C. IT was then approved by the International Standards Organization(ISO) in 1990. C++ and Java were evolved out of C, and then few features of C++ and Java were added to C. This version is usually referred to as C99. History of C
  • 30. 30 Features of C It is machine independent A function can call itself again and again until certain criteria is met Pointers are memory variables which stores the address of another variable instead of storing a value. It easily manages memory during runtime And during compile time. It is easy to learn It can be extended easily to add new features Libraries include number of pre- defined functions which can be used directly in a program It’s syntax is similar to machine language as well as human language It follows a block structured approach in which set similar statements are written inside two curly brackets { } FEATURES OF C LANGUAGE
  • 31.  C language is used for creating computer applications  Used in writing Embedded software  Firmware for various electronics, industrial and communications products which use micro-controllers.  It is also used in developing verification software, test code, simulators etc. for various applications and hardware products.  For Creating Compiler of different Languages which can take input from other language and convert it into lower level machine dependent language.  C is used to implement different Operating System Operations.  VLC media player is an open-source software and a cross-platform media player and streaming media server. This application is written using a combination of C, C++ and Objective – C programming languages.  Microsoft Office Suit- Originally written in C programming language, most of it’s portion is now switched on to C++ programming language for the object oriented programming paradigm shift.  Adobe has rolled out some of the world-class products in animation domain. We have some amazing tools that have been developed in C programming language such as Adobe Photoshop, Adobe Illustrator, Adobe Premier, Adobe Image Ready and others. 31 REAL WORLD APPLICATIONS OF C PROGRAMING LANGUAGE
  • 32. 32 Structure OF C Program
  • 33. 33 Structure of C program is defined by set of rules called protocol, to be followed by programmer while writing C program. All C programs are having sections/parts which are mentioned below. suitor 1. Documentation section 2. Link Section 3. Definition Section 4. Global declaration section 5. Function prototype/ declaration section 6. Main function 7. User defined function definition section Structure OF C Program
  • 34. 34 Structure OF C Program Documentation Section: consists of set of comment lines, name of program, author and other details Link Section: provides instructions to the compiler to link functions from the system library. Definition Section: defines all symbolic constants. Global Declaration section: Variable that are declare in the global declaration section that can be accessed to all functions. This section also declares all the user-defined functions. Main function: Every program must have one main() function section. This section also contains two parts, declaration part and executable part. All the statements in the declaration and executable part end with a semicolon ; Subprogram section: contains all the user defined functions and are called in main function Note: All sections , except the main function section may be absent when they are not required
  • 35. 35 Creating the Program Windows Integrated development environment Software •Save the file with “.c” extension. •Open cmd and write “gcc first.c -o first.exe” command. •To execute, enter first •Here “first.c” is the source code file name and first.exe is the name of the exe file that the compiler will create. •Save the file with “.c” extension. •Cc first.c •The compiled and linked program is called executable object code and is stored automatically file named a.out. •To execute, enter command a.out • create your own executable file: cc –o name source-file If you are using text editor then install GCC compiler first. Add bin path to system path -check installed or not enter gcc -v
  • 37. 37 Character Set Character set:- The character set is the fundamental raw material of any language and they are used to represent information. These characters are used to form words, numbers and expressions. Like natural languages, computer language will also have well defined character set, which is useful to build the programs.
  • 38. 38 ALPHABETS Uppercase letters A-Z Lowercase letters a-z DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 SPECIAL CHARACTERS ~ tilde % percent sign | vertical bar @ at symbol + plus sign < less than _ underscore - minus sign > greater than ^ caret # number sign = equal to & ampersand $ dollar sign / slash ( left parenthesis * asterisk back slash ) right parenthesis ′ apostrophe : colon [ left bracket " quotation mark ; semicolon ] right bracket ! exclamation mark , comma { left flower brace ? Question mark . dot operator } right flower brace WHITESPACE CHARACTERS b blank space t horizontal tab v vertical tab r carriage return f form feed n new line Back slash ’ Single quote " Double quote ? Question mark 0 Null a Alarm (bell) Character Set The characters in C are grouped into the following :
  • 39. 39 C Token Smallest individual units are known as tokens. E.G in a passage of text, individual words and punctuation marks are called tokens C programs are written using these tokens and the syntax of the language C Tokens Keywords Constants Strings Operators Identifiers Special Symbols Float while -15.5 100 “ABC” + - amount [], {}
  • 40. 40 Keywords: have fixed meaning and cannot be changed. Identifiers: User-defined names (names of variables, functions, arrays) Keywords and Identifiers Keywords in C Programming auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Rules of Identifiers:  First character must be an alphabet or underscore.  Must consists of only letters, digits or underscore  Cannot use a keyword  Must not contain white space
  • 41. 41 Constant in C refers to fixed value that do not change during the execution of a program Constants Numeric Constants Character Constants Integer Constants Real constants Single character Constants String Constants Constants Integer Constants: Refers to sequence of digits E.g. 123 ->decimal integer 0-9 -> octal integers 0-7 with leading 0 e.g. 037 0435 -> hex decimal integers 0-9, A-F. e.g. 0X9F Note: embedded spaces, commas, and non-digit characters are not permitted. E.G. 20,000
  • 42. 42 Real constants Real Constants: Quantities that contain fractional parts like 17.34. Such numbers are called real or floating point constants. Note: Integers are inadequate to represent quantities that vary continuously such as distance , height ,temperature . A real number may also be expressed in exponential (or scientific notation). E.G. 215.45 may be written as 2.1545e2 where e2 means multiple by 102 Single character constants String constants Character constant contains characters closed within a pair of single quote E.G ‘5’, ‘X’ String Constant is a sequence of characters enclosed in double quotes E.G “Hello” Character constants
  • 43. 43 Variables A variable is a data name that may be used to store a data value. A variable may take different values a different times during execution. ANSI (American National Standards Institute) standard recognizes a length of 31 characters. However the length should not be more than eight characters, since only the first eight are treated as significant by many compilers. In c99 , at least 63 characters are significant. -remember Abc is not same as abc First_tag valid Char invalid (keyword) Prices$ invalid (Dollar sign is illegal) Com sci  invalid (blank space)
  • 44. 44 Data types C language is rich in its data types. Data type specifies the type of data that the variable can store like integer, character, floating, double, etc. Each variable in C has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. C99 adds three more data types :- _Bool, _complex and imaginary
  • 45. 45 Primitive/Fundamental data type: Each data type requires different amounts of memory and has some specific operations which can be performed over it. Derived data type : These data types are defined by user itself. User specifies the amount of space it is going to take and the type of operation . Derived data types are created from basic data types such as int, float, char, etc. User Defined Data type: the programmer can invent his/her own data types in C programming. it is called a user-defined data type is that the variables of different types are clubbed together under a single structure user-Defined
  • 46. 46 Procedures for Binary Subtraction by 1’s Complement •Write the 1’s complement of the subtrahend  change 0 to 1 and vice varsa. •Then add the 1’s complement subtrahend with the minuend •If the result has a carryover, then add that carry over in the least significant bit •If there is no carryover, then take the 1’s complement of the resultant, and it is negative. 10-5 =5 Binary of 10= 1010 Binary of 5=0101 1010 - 0101 + 101 5-10 =-5 Binary of 5= 0101 Binary of 10=1010 0101 - 1010 -------- 1’s compliment of 10(subtrahend) = 1010 0101 add this to binary of 5(minuend) 0101 5 0101 100101 +______ 1010 no carry take 1’s compliment of result and it is negative 0101 -5 Whenever a number with minus sign is encountered, the number (ignoring minus sign) is converted to its binary equivalent. Then the two’s complement of the number is calculated. That two’s complement is kept at place allocated in memory and the sign bit will be set to 1 because the binary being kept is of a negative number. Whenever it comes on accessing that value firstly the sign bit will be checked if the sign bit is 1 then the binary will be two’s complemented and converted to equivalent decimal number and will be represented
  • 47. 47 Type Storage size Value range char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127 int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 long 8 bytes or (4bytes for 32 bit OS) -9223372036854775808 to 9223372036854775807 unsigned long 8 bytes 0 to 18446744073709551615 Primary Data types
  • 48. 48 Type Storage size Value range Precision float 4 byte 1.2E-38 to 3.4E+38 6 decimal places double 8 byte 2.3E-308 to 1.7E+308 15 decimal places long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places Floating-Point Types Data types
  • 49. 49 Character Types Void Types Characters are usually stored in 8bits. The qualifier signed and unsigned may explicitly applied to char The void type has no values. Usually used to specify the type of function. A function is said to be void when it doesn’t return any value to the calling function Data types
  • 50. 50 Data type Variable_Name =constant; Int a=100; Char b=‘x’; Float =75.8 The process of giving initial values to variables is called initialization. C permits initialization of more than one variable in one statement using multiple assignment operator E.G. a=b=c=0; Assigning values to variables
  • 51. 51 scanf() function Another way of assigning values to variables is to input data from keyboard using scanf funtion 1.scanf(“control string",&variable1, &variable 2……); The format string can be %d (integer), %c (character), %s (string), %f (float) etc. Printing data to console printf() function The printf() function is used for output. It prints the given statement to the console. The syntax of printf() function is given below: 1.printf("format string",argument_list); The format string can be %d (integer), %c (character), %s (string), %f (float) ,%.12lf( long float to 12 decimals) etc. Reading data from Keyboard Printing data to console printf() function The printf() function is used for output. It prints the given statement to the console. The syntax of printf() function is given below: 1.printf("format string",argument_list); The format string can be %d (integer), %c (character), %s (string), %f (float) ,%.12lf( long float to 12 decimals) etc.
  • 52. 52 Type Size (bytes) Format Specifier int at least 2, usually 4 %d, %i char 1 %c float 4 %f double 8 %lf short int 2 usually %hd unsigned int at least 2, usually 4 %u long int at least 4, usually 8 %ld, %li long long int at least 8 %lld, %lli unsigned long int at least 4 %lu unsigned long long int at least 8 %llu signed char 1 %c unsigned char 1 %c long double at least 10, usually 12 or 16 %Lf
  • 53. 53 Interpreter Language Translators 1. Scans whole program in one go 2. Errors are shown in one go 3. It does not require source code for later execution. 4. IT takes a large amount of time for analyzing the source code 5. Object code is generated 6. Programming languages like C, C++, Java use compilers. 7. Compiler is based on translation linking-loading model, 8. A linker program that takes the object files, produced by compiler, join them into a single executable file. 9. It is special program that takes input of executable files from linker, loads it to main memory, and prepares this code for execution by computer 1. It translates only one statement of the program at a time. 2. Errors are shown line by line. 3. It require source code for later execution. 4. Interpreters take less time for analyzing the source code. 5. No object code is generated 6. Debugging is easy Programming languages like JavaScript, Python,PHP Ruby use interpreters. Compiler Printing data to console
  • 54. 54 The compilation process in C involves four steps: pre-processing, compiling, assembling, and linking. All the statements starting with the # symbol in a C program are processed by the pre-processor, and it converts our program file into an intermediate file with no # statements Pre processing Source Program Expanded source code Assembly code Object code Preprocessing Compiling Linking Exe code assembling first.i abc.s first.c abc.obj/abc.o abc.exe/abc.out
  • 55. 55 System Ready Enter program Program Code Edit Source program C compiler Syntax Error Link with system Library Execute object code Logic and Data Errors Correct Output Compile Source Program System Library Input Data Stop No errors Logic errors Data error No Source Program Yes Object Code Executable object code Process of compiling and running a C Program
  • 56. 56 Comments in C Single-line comments start with two forward slashes (//). Multi-line comments start with /* and ends with */. Let us play with char data type
  • 57. 57 you must use the char type and create an array Strings are used for storing text/characters String in C C does not have a String type to create string variables char university[] = “chitkara"; printf("%c", university[0]); char university[] = “chitkara"; printf("%s", university);
  • 58. 58 String in C Take Input of a String in C Without Spaces The scanf() function is probably the easiest way to string input in C. We just need the access specifier %s Hence, the scanf() function should be preferred when we know the string we want to input doesn't contain white spaces and that it will not exceed the memory buffer. gets() function The working of gets() is such that it keeps reading the input stream until it encounters a newline character: n. Hence, even if the string input in C has spaces in it, all of them get included as input until n doesn't occur. But gets() doesn't care about the size of the character array passed to it and would lead to buffer over flow A buffer overflow (or buffer overrun) occurs when the volume of data exceeds the storage capacity of the memory buffer The gets() method is no longer a standard function according to the C11 standard ISO/IEC 9899:2011. But it is still available in libraries and will continue to be available for compatibility reasons.
  • 59. 59 String in C Take Input of a String in C With Spaces fgets() can take string input in C from both the standard input stream or from some file fgets(char_array, size, stdin); 1.{%[^n]%*c} inside scanf •%*[^n] scans everything until a n, but doesn't scan in the n. The asterisk(*) tells it to discard whatever was scanned. •%*c scans a single character, which will be the n left over by %*[^n] in this case. The asterisk instructs scanf to discard the scanned character. In scanf function you can use regular expressions to restrict or validate the char you are going to read, here in your question [^n] is regular expression that will exclude n i.e in other words scanf will read all char until you hit enter button. Now coming to %*c , * is used to indicate don’t assign
  • 60. 60 #include <stdio.h> int main() { int i = 10; char c = 'a'; int add; add= i + c; printf("Value of sum : %dn", add ); } Integer promotion: C is converted in ascii int main() { char i = '1'; char c = 'a'; int add; add= i + c; printf("Value of sum : %dn", add ); }
  • 61. 61 Type Casting in C Converting the value of one data type to another type is known as type conversion. C permits the mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type without losing any significance._________IMPLICIT TYPE CONVERSION. RULE: Lower type is converted into a higher type All short and char are converted to int. I. if one operand is long double the other will be converted long double. II. If one operand is double the other is converted to double and result will be double. III. --------------------float the ----------------------float and -----------------float. IV. ---------------------long int----------------------long int and --------------long int. The final result of an expression is converted to type of variable on the left of assignment sign before assigning value to it. Following changes are introduced Float to int cause truncation of fractional part. Double to float cause loss of rounding digits. Long int to int cause dropping of excess higher order bits
  • 62. 62 x= 1/i + i*f - d int Float int i,x; float f; double d; long int 1; int double long long long float Float int double int float float double An expression is a combination of operators and operands which reduces to a single value.
  • 63. 63 Type Casting in C EXPLICIT TYPE CONVERSION: When we want to force type conversion. Ratio =quantity1/quantity2; If quantity1 and quantity2 are declare integers then decimal part of the result would be lost. Ratio=(float)qualtity1/quantity2 The operator (float) converts the quantity1 number to floating point for the evaluation. The type of quantity1 remains as int in other parts of the program. Z=(int)3.4; A=(int)21.3/(int)4.5
  • 64. 64 Operators and Expressions Operators: Operators are used in programs to manipulate data and variables. C operators are classified into a number of categories: 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment operators 5. Increment and decrement operators 6. Conditional operators 7. Bitwise operators 8. Special operators An expression is sequence of operators and operands that reduces to a single value. E.G 10+15;
  • 65. 65 Operators Operator Meaning + Addition or unary plus - Subtraction or unary minus * Multiplication / Division % Modulo Division Operator Meaning < Is less than <= Is less than or equal to > Is greater than >= Is greater than or equal to == Is equal to != Is not equal to Arithmetic operators Relation operators Relational operators help in making a relationship or comparison between two operands with which they are used An arithmetic operator is used to perform arithmetic/mathematical operations on operands.
  • 66. 66 Operators Operator Meaning && Logical AND || Logical OR ! Logical NOT Operator Meaning Syntax: V op=exp V=variable, op= operator, exp=expression a=a+1 a+=1 a=a-1 a-=1 a=a*(n+1) a*=n+1 a=a/(n+1) a/=n+1 a=a%b a%=b Logical operators (used to test more than one condition) Assignment Operators( used to assign the result of an expression to a variable) The logical operators are used when we want to check or test more than one condition and make decisions. An assignment operator is used to assign values to the operands.
  • 67. 67 Operators Operator Meaning ++ ++ adds 1 to the operand - - -- subtracts 1 from the operand Postfix(a++) and prefix(++a) a++(postfix) and ++a(prefix) mean the same thing but they form the statements independently, they behave differently.  Increment and decrement operators are unary operators.  a=5 a=5  b=++m b=a++ Increment and Decrement operators Unary operators: are operators that act upon a single operand to produce a new value. Types of unary operators: 1.unary minus(-) 2.increment(++) 3.decrement(- -) 4.NOT(!) 5.Addressof operator(&) 6.sizeof() The minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive. unary minus is different from the subtraction operator, as subtraction requires two operands.
  • 68. 68 Operator Meaning For manipulating data at bit level.  Bitwise operators are not applied to float or double & Bitwise AND | Bitwise OR ^ Bitwise Exclusive OR << shift left >> Shift right Bitwise Operators Conditional Operators Operator Meaning Exp1? Exp2:exp3 Exp1 is evaluated first, if it is nonzero (true) then exp2 is evaluated otherwise exp3 is evaluated Operators
  • 69. 69 Operator Meaning , Used to link the related expressions together Comma & Address Operator sizeof() sizeof Special Operators Operators int main() { int value; int x,y; value = (x=10, y=5); printf("%d %d",x,y); return 0;
  • 70. 70 Arithmetic Expression Operator Description Associativity Rank () Left to right 1 +,-,++,-- ,!,~,*,& sizeof(), Right to Left 2 *,/,% Left to right 3 + - Left to right 4 << ,>> Left to right 5 <,<=,>,>= Left to right 6 ==, != Left to right 7
  • 71. 71 Arithmetic Expression Operator Description Associativity Rank & Bitwise AND Left to right 8 ^ Bitwise XOR Right to Left 9 | Bitwise OR Left to right 10 && Logical AND Left to right 11 || Logical OR Left to right 12 ?: Conditional expression Right to left 13 =,*=,/=,%=,+=,-= Assignment operators Right to left 14 , Comma operator Left to Right 15
  • 72. 72 Operator Precedence in C is used to determine the sequence in which different operators will be evaluated if two or more operators are present in an expression. The associativity of operators: is used to determine whether an expression will be evaluated from left-to-right or from right-to- left if there are two or more operators of the same precedence. E.G c=a*5/5 ------------Here  a-b/3+c*2-1 a=9, b=12, c=3  a-b/(3+c)*2-1 1. Parentheses have the highest precedence among all operators in C. Operator Precedence
  • 73. 73 printf("%d", 1 == 3 != 5); Operator Precedence Z=++a * (3 + 8) % 35 - 28 / 7; z = a++ + ++a; a > b > c
  • 74. 74 Macros in C The macro in C language is known as the piece of code which can be replaced by the macro value. The macro is defined with the help of #define preprocessor directive and the Macro doesn’t end with a semicolon(;). Whenever the compiler encounters the macro, it replaces the macro name with the macro value. e.g #define PI 3.14 #: preprocessor directive PI macro name 3.14 Macro Value Q: Write a program to calculate the area of a circle with a macro definition for PI( Given that diameter of the circle is 16 cm) #define MARKS 100 #define MIN 1 #define G 9.8
  • 75. 75 Sr. No. Macro Feature 1 __LINE__ Macro It contains the current line number on which this macro is used. 2 __FILE__ Macro It contains the name of the file where the current program is present. 3 __DATE__ Macro It contains the current date in MMM DD YYYY format. 4 __TIME__ Macro It contains the current time in HH:MM format. 5 __STDC__ Macro It is defined as 1 when there is a successful compilation. Predefined Macros and their features:
  • 76. 76 IF Statement: The if statement is a simple decision-making and branching statement and it is used to control the flow of the program execution. IF Statement It means depending on the condition the control is transferred either to the true block or false block. It is also called a control statement. Condition check True False
  • 77. 77 if(expression) #include<stdio.h> int main() { int a=10; float b=50; if(a>b) { printf("yes %d",a); } return 0; } #include<stdio.h> int main() { char a=‘1’; float b=50; if(a>b) { printf("yes %d",a); } return 0; }
  • 78. 78 int main() { int a=10; int b=50; int c=500; if(a>b>c) { printf("yes %d",a); } return 0; } #include<stdio.h> int main() { int a=10; int b=5; int c=0; if(a>b>c) { printf("yes %d",a); } printf("outside if statement"); return 0;
  • 79. 79 Types of If Statements if statement may be implemented in different forms depending on the complexity of testing conditions to be evaluated. •Simple if Statement •if-else Statement •Nested if-else Statement •else-if Ladder Condition check True False If Block Else block
  • 80. 80 Program to check whether a person is eligible to vote or not. Given that age must be equal to or greater than 18 Q. Write a program that takes integer input from the user. Based on that input you have to decide whether the integer input is an even or odd number Find out the given number is even or not using Ternary Operator in C. (num % 2 == 0)
  • 81. 81 If Else Ladder if(condition) { } else if(condition) { // this else if will be executed when condition in if is false and // the condition of this else if is true }.... // once if-else ladder can have multiple else if else { // at the end we put else } if() { } Else if() { } Else if() { } else Write a program to Check whether a number is positive, negative or 0 Calculate Grade According to marks using if else ladder. Given that: marks less than 100 and marks greater or equal 90 --A marks less than 90 and marks greater or equal 70 --B marks less than 70 and marks greater or equal 50 --C marks less than 50 and marks greater or equal 40 --D marks less than 40 and marks greater or equal 0 --F other than this marks are not valid
  • 82. 82 if (condition 1) { //if the second condition holds if (condition 2) { do something } //if the second condition does not hold else { do something else } } // if the first condition does not hold else{ //if the third condition holds if (condition 3) { do something } //if the third condition does not hold else { do something else } } Nested If Else Statement Write a program to find Which number is greatest among the three numbers that the user has received as input
  • 83. 83 Write a program to analyze if the number is even or odd, and then if it is even, whether it is divisible by 4 or not, and if it is odd, whether it is divisible by 3 or not Write to program to Check if a year is a leap year Write a program to find Which number is greatest among the three numbers that the user has received as input 4 100 400 Write a program to multiple variable with a constant without using multiplication operator.
  • 84. 84 Every year that is evenly divisible by four is a leap year except for years that are evenly divisible by 100 and 20For example, 2014, 2015, 2017, and 2018 are not leap years because they are not evenly divisible by four, 2012, 2016, 2020, and 2024 are leap years because they are evenly divisible by four and not evenly divisible by 100, 1800, 1900, 2100, and 2200 are not leap years because they are evenly divisible by 100 and not evenly divisible by 400, and 1600, 2000, and 2400 are leap years because they are evenly divisible by 400. All these rules makes the average calendar year 365.2425 days, which is fairly close to the actual time it takes for Earth to orbit the sun, which is slightly less than 365.2422 days
  • 85. 85 The math.h header defines various mathematical functions and one macro. All the functions available in this library take double as an argument and return double as the result. double ceil(double x): The C library function double ceil (double x) returns the smallest integer value greater than or equal to x. double floor(double x): The C library function double floor(double x) returns the largest integer value less than or equal to x. double fabs(double x): The C library function double fabs(double x) returns the absolute value of x double fmod(double x, double y) : The C library function double fmod(double x, double y) returns the remainder of x divided by y. sqrt(double x): The C library function double sqrt(double x) returns the square root of x double pow(double x, double y): The C library function double pow(double x, double y) returns x raised to the power of y i.e. xy.
  • 86. 86 The term b2; - 4ac is known as the discriminant of a quadratic equation. It tells the nature of the roots. If the discriminant is greater than 0, the roots are real and different. If the discriminant is equal to 0, the roots are real and equal. •If the discriminant is less than 0, the roots are complex and different. Write a program to find roots of a quadratic equations
  • 87. 87
  • 88. 88 #include<stdio.h> int main() { int i,j; i=10; j=10; if(i==1) { printf("how are you"); } else if(i==10) { printf("yes"); } else if(i==10) { printf("no"); } return 0; } #include<stdio.h> int main() { int i,j; i=10; j=10; if(i==1) { printf("how are you"); } else if(i==10) { printf("yes"); } else if(j==10) { printf("no"); } return 0; }
  • 89. 89 C program to count the total number of notes in a given amount Int a=5; Printf(%d %d %d %d %d”, a,--a,--a,--a,--a); Printf(%d %d %d %d %d”, a, a++,a++,a++,a++); C program to swap two numbers using temporary variable? C program to swap two numbers without using a temporary variable?
  • 91. 91 Formatted output Printf(“%7.4f”,98.7654) Printf(“%7.2f”, 98.7654) Printf(“%-7.2f”, 98.7654) Printf(“%f”, 98.7654) 9 8 . 7 6 5 4 9 8 . 7 7 9 8 . 7 6 5 4 9 8 . 7 7
  • 92. 92 int main() { printf(" %d", printf("%s", “how are you")); getchar(); } int main() { int a ; int z= scanf("%d ", &a); printf(" %d",z ); getchar(); } X=Printf(“hello”); Printf(“%d”, x);
  • 93. 93 Getchar(): Reading a single character can be done using the function getchar Variable_name=getchar(); C Supports many other similar functions which are contained in the filetype ctype.h #include<ctype.h>  Isalnum(c)  Isalpha(c)  Isdigit(c)  Islower(c)  Ispunct(c)  Isspace(c)  Isupper(c)
  • 94. 94 Like getchar, there is an analogous function putchar for writing charactrs one at a time to the terminal Putchar(variable_name) e.g putchar(toupper(alphabet)); Write a program that reads a character from the keyboard and then prints the reverse case. That is if the input is lower case output will be upper case and vice versa without using predefined functions Write a program that reads a character from the keyboard and then prints the reverse case. That is if the input is lower case output will be upper case and vice versa using predefined functions
  • 95. 95
  • 96. 96 int main() { char a; a= getch(); printf("%c", a); return 0; } getch(): getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers like Turbo C. It reads also a single character from the keyboard. But it does not use any buffer, so the entered character is immediately returned without waiting for the enter key.
  • 97. 97 int main() { char a; a= getc(stdin); printf("%c", a); return 0; } getc(): It reads a single character from a given input stream and returns the corresponding integer value (typically ASCII value of read character) on success. It returns EOF on failure.
  • 98. 98 getchar(): The difference between getc() and getchar() is getc() can read from any input stream, but getchar() reads from standard input. So getchar() is equivalent to getc(stdin).. int main() { printf("%c", getchar()); return 0; }
  • 100. 100 Switch in C The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Switch(Expression) { case value1: block1 break; case value2: block2 break Default: default block break; } In a switch statement, the “case value” can be of “char” and “int” type
  • 101. 101 The expression provided in the switch should result in a constant value otherwise it would not be valid. For example: Valid expressions for switch – switch(1+2+23) switch(1*2+3%4) Invalid switch expressions – switch(ab+cd) switch(a+b+c) The default statement is optional, if you don’t have a default in the program, it would run just fine without any issues. However it is a good practice to have a default statement so that the default executes if no case is matched.
  • 102. 102 #include <stdio.h> int main() { int number=1; switch (number) { case 1: case 2: case 3: printf("One, Two, or Three.n"); break; case 4: case 5: case 6: printf("Four, Five, or Six.n"); break; default: printf("Greater than Six.n");}}
  • 103. Create a grading system using a switch case 100-90->A 80 -90->B 60-80->C 40-60->D 30-40->E <30->F 103
  • 105. 105
  • 106. 106 We consider the following program in which the user to type his class group Number(15,17,19), if the Group ID (15,17,19)is valid it will ask him to enter his Roll NO(1- 5), if the Roll No is correct the program will print message “ Welcome to CSE” to the user, otherwise ,the program will print Incorrect Roll NO and if the Group ID does not exist , the program will print Incorrect Group ID. Please Enter Your Group ID: 17 Enter your RollNO: 15 Incorrect Roll NO Please Enter Your Group ID: 17 Enter your RollNO: 5 Welcome to CSE Please Enter Your Group ID: 20 Incorrect Group ID
  • 107. 107 Write a program to convert the given two-digit number into English word format with the help of a switch case. e.g 7-> seven Using the switch case, write a program in which the user selects any operator among +,-,*,/ then the program asks for two integers, and after that performs the required operation on given two integers.
  • 108. 108 Necessary Use switch case and/or if else if required, Write a program that asks for two inputs year and month number(1-12). Based on the year and month number, calculate the total number of days from the Month Jan E.G year:2020 month: 3 total days= 91
  • 109. 109 Necessary Use switch case and/or if else if required, Write a program that asks for two inputs year and month number(1-12). Based on the year and month number, calculate the total number of days from the Month Jan E.G year:2020 month: 3 total days= 91
  • 110. 110 A computer manufacturing company has the following monthly compensation policy to their sales persons: Minimum base salary: 1500 Bonus for every computer sold :200 Commission on the total monthly sales :2 percent (0.02) The sales price of each computer is fixed at the beginning of every month. Write a program to compute a sales persons gross salary Hint gross salary=Base salary+bonus+comissions Test Case Input number sold and price 5 20430.00 Bonus= 1000.00 Comission=2045 Gross salary =4545.00
  • 111. 111 A electric power distribution company charges its domestic consumers as follows Consumption Units Rate of charge 0-200 Rs 0.50 per unit 201-400 Rs 100 plus Rs 0.65 per unit excess of 200 401-600 Rs 230 plus Rs 0.80 per unit excess of 400 601 and above Rs 390 plus 1.00 per unit excess of 600 Write a program that reads customer number, power consumed, and print amount paid by customer. Test Case: input Customer N0 :101 Units consumer : 202 Output : Charges 116
  • 113. 113 C supports the goto statement to branch unconditionally from one point to another in the program. The goto statement requires a label in order to identify the places where the branch is to be made. The label is any valid variable name and must follow a colon: Goto label; Label: Statement; Label: Statement; Goto label; Forward jump Backward jump
  • 115. 115 Loop In looping, a sequence of statements is executed until some conditions for terminations of the body of the loop and others known as control statements. Control Statements: tests certain conditions and directs the repeated execution of the statements contained in the body of the loop. Test conditions Body of loop Entry controlled loop Test condition s Body of loop Exit controlled loop entry entry False true False true Pre-test Post test
  • 116. 116 Based on the nature of the control variable and the kind of value assigned to it for testing the control expression, the loops may be classified into two general categories: 1. Counter-controlled loops: when we know in advance exactly how many times the loop will be executed 2. Sentinel-controlled loops: a special value called sentinel value is used to change the loop control expression from true or false
  • 117. 117 While(test condition) { Body of the loop } While loop is an entry controlled loop statement Sum=0; n=1; while(n<=10) { Sum=sum+n*n; n=n+1; } Printf(“sum=%d”, sum); Character =‘’ While(character!= ‘y’) Character=getchar(); //sentinel control loop While Loop
  • 118. 118 The do-while loop is a post tested loop do{ 1.//code to be executed 2.} 3.while(condition); 1 2 3 4 5 5 7 8 9 10 ---------------------- 1 2 3 4 5 6 7 8 9 10 Do While Loop
  • 119. 119 Write a program to find the factorial of number using while loop Write a program to reverse a given number e.g 123 -> 321 Write a program using while loop and print the following: 1 1 2 2 3 3 4 4 5 5 6 6
  • 120. 120 Write a program using a while loop and print the following pattern: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50
  • 121. 121 Write an interactive program to demonstrate the process of multiplication. The program should ask the user to enter two-digit integers and print the product of integers as shown below 37x45 is ------------------------------ 45 x 37 --------- 315 135 ------------- add them 1665 --------------
  • 122. Jump in loops 122 Break: When a break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop Goto: An important use of goto is to exit from deeply next loops when an error occurs. A simple break statement would not work here.
  • 123. 123
  • 124. 124
  • 125. Skipping a part in loops 125 Continue: The continue statement causes the loop to be continued with the next iteration after skipping any statements in between SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH NEXT ITERATIONS continue;
  • 126. 126 #include<stdio.h> int i=1; int main() { while(i<10) { if(i==5) { printf("This is %dn",i); continue; printf("cant print it"); } printf("hello %dn",i); i++; } } for(i=0;i<10;i++) { printf("the value of i is %d",i); if(i==7) { printf("the value now is %d",i); continue; } printf(" this should be printedn"); } }
  • 127. 127 For(initialization; test-condition;increment/decrement) { Body of loop } FOR Loop  Initialization of the control variables is done first, using an assignment statement such as i=1.  The value of the control variable is tested using the test condition. The test condition is a relational expression such as i<2 that determines whether the n loop terminates  When the body of the loop is executed, the control is transferred back to for statement after evaluating the last statement in the loop.  Now control variable is incremented using an assignment statement such as i=i+1
  • 128. 128 for(x=0;x<=10;x=x+1) { Printf(“%d”,x) } FOR Loop Additional features of For loop  More than one variable can be initialized at a time in the for loop for(n=0,p=1;n<10;n++)  The test condition may have a compound relation and increment section may also have more than one part Sum=0; For(i=1,j=1; i<20 &&sum<100; ++i,++j) { sum=sum+I; j=j+I; printf(“%d %d ”,j,sum); }
  • 129. 129 FOR Loop Additional features of For loop  m=5; for( ; m!=50 ;) we can omit one or more sections of for loop if necessary
  • 131. 131 For(initialization; test-condition;increment/decrement) { For(initialization; test-condition;increment/decrement) { For(initialization; test-condition;increment/decrement) { } } } for(i=1; i<=5;++i) { for(j=1; j<=5;++j) { for(z=1; z<=5;++z) { } } } Nested FOR Loop
  • 132. 132 For Columns loop2 For Rows Loop1 For Pattern printing loop3
  • 133. 133 12345678910 11111 22222 33333 44444 55555 1 2 3 4 5 6 7 8 9 10 ***** ***** ***** ***** 12345 12345 12345 12345 12345 987654321 * * * * * * * * * * * * * * * * 1 12 123 1234 12345 12345 1234 123 12 1 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 * * * * * * * * * * * * * * * * 1 2 3 4 5 6 7 1 2 3 4 5 1 2 3 1 - - - -1 - - - 2 3 - - 3 4 5 - 4 5 6 7 5 6 7 8 9 LEVEL 1 LEVEL 2 LEVEL 3 S S S S S S S S S S S S S S S S
  • 134. 134 Write a function in c that Converts Binary Numbers to Decimal Write a program to find Prime Numbers Between Two Integers  Pre-condition check:  if number 1> number 2 swap the two numbers.
  • 135. 135 Write a program to check whether a number is a prime number or not *without using function* Write a program to find Prime Numbers Between Two Integers  Pre-condition check:  if number 1> number 2 swap the two numbers. Write a program to find whether a number is an Armstrong number or not Write a program to print Fibonacci Series  User specifies the total number of elements to be printed The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
  • 136. ARMSTRONG NUMBER 136 1634, 8208, 9474 Write a program to find whether a number is an Armstrong number or not
  • 137. 137 C Program to draw pascal triangle LAB WORK
  • 138. 138 FIND ODD NUMBER BETWEEN 1 AND 100 FIND THE SUM OF N NATURAL NUMBERS FIND THE SUM OF THE FIRST N ODD NUMBERS FIND THE SUM OF FIRST N EVEN NUMBERS LAB WORK C Program to convert decimal numbers to binary C Program to Convert Binary Numbers to Decimal
  • 140. 140 User Defined Functions C functions can be classified into two categories, namely:  Library functions  User-defined functions *main is an example of user-defined functions. If a program is divided into functional parts, independently codes a program called subprograms, in C such subprograms are called functions. Function: A function is a self-contained block of code that performs a particular task. Once a function has been designed it is treated as a black box that takes some data from the main program and returns a value. The inner details of operations are invisible to the rest of the program
  • 141. 141 Elements of User DefinedFunctions  Like variables functions have types (such as int) associated with them  Like variables, function names and their types must be declared and defined before they are used in the program. We need to established three elements that are related to functions  Function definition  Function call  Function declaration Void printl(void); /*declaration */ Main() { printl(); } Void printl(void) { statements………. ------------------------ }
  • 142. 142 Functions definitions Function definition: A function definition, also known as function implementation shall include the following elements.  Function name;  Function type;  List of parameters  Local variables declarations  Function statements  Return statement. Function_type function_name(parameter list) { Local variables declaration; Executable statement; ------------------- ------------------ Return statement; }
  • 143. 143 Function type Function type specifies the type of value(like float and double) that the function is expected to return to the program calling the function.  if the return type is not explicitly specified , C will assume that it is a integer type.  if function is not returing anything then we need to specify the return type as void Void is one of the fundamental data type in C.
  • 144. 144 Formal parameters List The parameter list declares the variables that will receive the data sent by the calling program. They serve as input data to the function to carry out the specified task. Since they represent actual input values they are called as formal parameters. The parameters list contains the declaration of variables separated by commas and surrounded by parentheses. Float quadratic(int a, int b, int c) double power(double x, int n) float mul(float x,floaty) int sum(int a, int b) Int sum(int a,b) Is illegal
  • 145. 145 void If function has no formal parameters, to indicate the parameter list is empty, we use keyword void between the parentheses as in Void printl(void) { } Many compilers accept an empty set of parentheses, without specifying anything as in void printl() But is a good programming style to use void to indicate a nill parameter list
  • 146. 146 Function Body The function body contains:  Local declaration that specifies the variables  Function statements  A return-type statement *if the function can’t return we can omit the return statement. However, its return type should be specified as void. When a function reaches its return statement, the control is transferred back to the calling program,-----------in Absence of a return statement, the closing brace acts as a void return; A local variable is a variable that is defined inside a function and used without having any role in the communication between functions. Float mul(float x, float y) { Float result; /*local variable*/ Result=x*y; Result(result); }
  • 147. 147 Return Values and their types The return type can take one of the following forms: 1) Return; -----------Doesn’t return any value and acts much as closing brace of the function in C99, if a function is specified as returning a value, the return value must have value associated with it Or 2)Return (expression) The function can return only one value per call Int product (void) { Return (2.33* 5.1) } will return the value of 7 (automatically casted to function type)
  • 148. 148 Function calls A function can be called by simply using the function name followed by list of actual prameters (or arguments) Int main() { Int y; Y=mul(5,3); } Int mul(int x, int y) { Int z; Z=x*y; Return (z); } Printf(“%d”, mul(p,q)); A function that return values can be used in expressions like: If(mul(p,q)>total)
  • 149. 149 Function declaration All functions in a c program must be declared before they are involved. A prototype declaration may be placed in two places in a program  Above all the functions including the main(global prototype)  Inside a function definition. (local prototype) The place of declaration of a function defines a region in a program in which the function may be used by other functions. This region is known as the scope of the functions.
  • 150. char pri(void); int main() { char x; x= pri(); printf("%c",x); } char pri(void) { return 'a'; } 150 int main() { char x; pri(); printf("Fine"); } void pri(void) { printf("how are you"); }
  • 151. #include<stdio.h> void swap(int,int); void main( ) { int n1,n2; printf("Enter the two numbersn"); scanf("%d%d",&n1,&n2); printf("nThe values of n1 and n2 before calling the swap function are n1=%d n2=%d",n1,n2); swap(n1,n2); printf("nThe values of n1 and n2 after calling the swap function are n1=%d n2=%d",n1,n2);} 151
  • 152. 152 void swap(int n1,int n2) { int temp; temp=n1; n1=n2; n2=temp; printf("nThe values of n1 and n2 after swapping are n1=%d n2=%d",n1,n2); }
  • 153. 153 #include<stdio.h> void prn(int,int); ; int main() { int a,b int x=10,y=12; printf("a= %d and b= %d",x,y); prn(x,y); } void prn(int x , int y) { a=x+1; b=y+1; printf("value of a=%d and value of b=",a,b); }
  • 154. 154 Write a user-defined function to calculate the Volume of the cylinder where another user- defined function returns the square of the net radius. Given that the outer radius is the cylinder is 16cm and the inner radius is 8cm and the height of the cylinder is 25cm Write a user-defined function that returns the age in years of a person. Enter Date of birth details Day: month: Year: Enter current day: Enter current month: Enter current year:
  • 156. 156 Storage classes In some programming languages, variable retains its value throughout the program like BASIC PROGRAM. But that is not the case with C programming It depends on the storage class a variable may assume. In C , variable not only have data types but the storage classes. Following are the storage classes , relevant to functions 1. Automatic variables 2. Register variables 3. Static variables 4. External variables
  • 157. 157 Storage classes Variable have scope, visibility and longevity Scope: determines over what region of the program a variable is actually available The scope of a variable is determined at compile-time only In Simple words, if you use a variable out of its scope compiler will throw an error Longevity: refers to the period during which a variable retains a given value during execution of a program Visibility refers to the accessibility of a variable from the memory Default definition value: Memory allocation does not happen in the declaration whereas in definition memory gets allocated to the variable.
  • 158. 158 Variable declaration is useful when the programmer uses multiple files and when he defines the variables in one of the files. They are available when linking the program. He can use the variable in any place. Even though it is possible to declare a variable multiple times in it only once such as in a file or a function. What is a Definition in C The definition of a variable indicates the compiler where and how much storage to create for the variable. A variable definition defines the data type and a set of one or more variables of that type. Below is an example of a declaration. int a, b;
  • 159. 159 Automatic Variables Automatic Variables: are declared inside a function in which they are utilized, They are created and destroyed automatically when the function is exited. They are also called local or internal variables A variable declared inside a function without storage class specification is by default an automatic variable Main() { Int number } _____________________________________________________________ Main() { Auto number } #include<stdio.h> auto int max; //Error, illegal to declare auto with global scope. int main() { auto int min; // Legal syntax }
  • 160. 10 100 1000 160 Void fun1(void); Void fun2(void); Main() { Int m=1000; Fun2(); printf(%d ,m); } Void fn1(void) { Int m=10; Printf(“%d”,m); } Void fun2(void) { Int m=100; Fun1(); Printf(“%d”, m); }
  • 161. 161 Register Variables Register Variables: tells the compiler that the variable should be kept in one of the machine’s registers, instead of kept in the memory(where normal variables are stored). Since register access is faster than memory access, keeping the frequently accessed variables (e.g loop variables in the register will lead to faster execution of programs. Register int count; Some compilers allow only int and char variables but ANSI standard doesn’t restrict its application C will automatically convert register variables into non-Register variables once the limit is reached
  • 162. 162 Static Variables Static Variables: the value of static variables persists until the end of the program. A static variable is declared using static keyword Static int x; Static float y; Internal Static variables are similar to auto variables except they remain in existence (alive) through out the remainder of the program. internal static variable can be used to retain values between function calls.
  • 163. 163 #include<stdio.h> static int out; // Global static variable implicitly initialized to 0. void main() { static int in = 10;//local static variable explicitly initialized to 10 printf("global: %d, local: %d", out, in); } two static variables with the same definition in two different functions refer to two different memory locations and hence they are not be assumed as a single variable. For example in the below code, void fun1() { static sInt = 100; } void fun2() { static sInt = 10; }
  • 164. 164 Void stat(void); Int main() { Int I; For(i=1;i<=3;i++) { stat(); } } Void stat(void) { Int x=0; x=x+1; Printf(“%dn, x); } Void stat(void); Int main() { Int I; For(i=1;i<=3;i++) { stat(); } } Void stat(void) { Static Int x=0; x=x+1; Printf(“%dn, x); }
  • 165. 165 #include<stdio.h> void stat(void); int main() { int i; for(i=1;i<=3;i++) { stat(); } printf("%d",x); } void stat(void) { int x=0; x=x+1; printf("%dn", x); } #include<stdio.h> void stat(void); int main() { int i; for(i=1;i<=3;i++) { stat(); } printf("%d",x); } void stat(void) { static int x=0; x=x+1; printf("%dn", x); }
  • 166. 166 External Variables External variables: variables that are both alive and active throughout the entire program are known as external variables. They are also known as global variables. In case a local variable and global variable have the same name, the Local variable has precedence over the global variable. Int fun1(void); Int x; /*global */ Main() { X=10; Printf(“%d”,x); Printf(“%d,fun1()); } Fun1(void) { x=x+10; }
  • 167. 167 External Variables Global variables available only from the point of declaration to the end of the program. • Main() • { • y=5; • } • Int y; /*global declaration*/ • func1() • { • y=y+1; • } Global variables are initialized with zero by default
  • 168. 168 Extern Variables Declare the storage class with the extern. Main() { Extern int y; } IT informs the compiler that y is an integer type defined somewhere else in the program extern declaration doesn’t allocate storage space for variable Extern keyword: The extern keyword is used to declare a global variable, it is just a reference to the compiler that the variable definition is somewhere in the program or in another file
  • 169. 169 #include<stdio.h> void main() { extern int m; m=15; printf("%d",m); } int max; Extern variables are useless when used in the same file. They are mainly designed to export global variables from another file.
  • 170. #include<stdio.h> int x; int main() { int y; printf(“%d %d”, x, y); } 170
  • 171. 171 #include<stdio.h> Void main() { Extern int i=10; Printf(“%d”,i); } #include<stdio.h> void main() { extern i; i=10; printf("%d",i); } int i=20; #include<stdio.h> void main() { extern i; printf("%d",i); } int i=20;
  • 172. 172 Storage Class Scope Lifetime Initial Value Storage Location Auto Within the block, in which it is declared. Within the block, in which it is declared. Initialized with garbage value. RAM Register Within the block, in which it is defined. Same as auto, within the block in which it is declared. Initialized with garbage value. Register Static Within the block, in which it is defined. Throughout the main program. Zero. RAM Extern Global scope, unbound by any function. Same as static, till the end of the main program. Zero. RA
  • 173. 173 Arrays C Supports derived data type called array that can be used to store, process , print and manipulate large amount of data. Array is a fixed-sized sequenced collection of elements of the same data type. The array is classified as one of the data structures in the C A data structure is a specialized format for organizing, processing, retrieving and storing data.
  • 174. 174 Arrays Declaration of Array : int number[10]; This declaration is also called as vector The computer reserves five storage locations: 3 4 1 2 8 Number[0] Number[1] Number[2] Number[3] Number[4] Subscripts of an array begin with 0 and can be integer constant, inter variables, or expression that yields to integers An array is allocated block of memory for the specified no. of elements in contiguous or continuous locations by the compiler.
  • 175. 175 Arrays Any reference to the array outside the declared limits would not necessarily cause an error. Rather it might result in unpredictable program results. C language treats character strings simply as an array of characters. Char name[10]; “Welcome to” ‘W’ ‘E’ ‘L’ ‘C’ ‘O’ ‘M’ ‘E’ ‘ ’ ‘T’ ‘O’ ‘/0’ float marks[5] = {67, 89.5, 45.8, 60, 48.6}; /* marks contains 5 floats */ Let’s see how these 5 floats are organised in marks, marks[0] = 67; marks[1] = 89.5; marks[2] = 45.8; marks[3] = 60; marks[4] = 48.6;
  • 176. 176 Initialization Arrays Array can be initialized at either of following stages: At compile time At run time Compile Time Initialization Int number[5]={1,2,3,4,5}; Float marks[5]={1.2,3.5,5.5} // the remaining two elements to zero in case of number and null in case of character array The size may be omitted, in such cases, the compiler allocates enough space for all initialized elements. int number[ ]={1,2,3,};
  • 177. 177 Initialization Arrays Char name[ ]={‘c’,’h’,’I’,’t’,’k’,’r’,’a’}; An alternative way is char name [ ]=“chitkara”; Int number [3]={10,20,30,40}; #include<stdio.h> int main() { char number[3]={'j','o','m','p','i'}; printf("%c",number[3]); }
  • 178. 178 #include<stdio.h> int main() { int number[3]={1,2}; printf("%d",number[2]); } #include<stdio.h> int main() { int number[3]={1,2}; printf("%d",number[3]); } #include<stdio.h> int main() { char number[3]={'j','o'}; printf("%c",number[2]); } #include<stdio.h> int main() { char number[3]={'j','o'}; printf("%s",number[2]); }
  • 180. Passing array to a function 180 #include <stdio.h> void display(int r1, int r2) { printf("%dn", r1); printf("%dn", r2); } int main() { int rollno[] = {2, 8, 4, 12} display(rollno[0], rollno[1]); return 0; }
  • 181. 181 float calculateSum(float num[]); int main() { float rollno[] = {2, 5, 6, 3, 4, 8}; result = cadd(rollno); } float calculateSum(int abc[]) { }
  • 182. WRITE A PROGRAM TO SORT AN N-ELEMENTS ARRAY 182 WRITE A C PROGRAM FOR LINEAR SEARCH IN C FIND THE LARGEST ELEMENT IN AN ARRAY FIND THE SUM OF ALL THE ELEMENTS IN AN ARRAY NOTE : PASS ARRAY TO A FUNCTION WHICH CALCULATES THE SUM OF THE ARRAY STORE THE ELEMENTS OF ONE ARRAY IN OTHER ARRAY BUT IN REVERSE ORDER C PROGRAM TO INSERT AN ELEMENT IN AN ARRAY
  • 183. 183 String in C The string can be defined as the one-dimensional array of characters terminated by a null ('0’). There are two ways to declare a string in c language. 1.By char array char ch[8]={‘C', ’h', ’i’, ’t', ’k', ’a', ’r', ’a', '0'}; By string literal Char ch[]=“chitkara”; We need to add the null character '0' at the end of the array by ourself whereas, it is appended internally by the compiler in the case of the character array.
  • 184. 184 String functions (strlen) strlen() function:The strlen() function returns the length of the given string #include<stdio.h> #include <string.h> int main(){ char ch[20]={'c', 'h', 'i', 't', 'k', 'a', 'r', 'a','0', 'n'}; printf("Length of string is: %d",strlen(ch)); return 0; }
  • 185. 185 String functions (strcpy) and strncpy The strcpy(destination, source) function copies the source string in destination. 1.#include<stdio.h> 2.#include <string.h> 3.int main(){ 4. char name[4]={‘c’,’a’,’n’,’t’}; 5. char name2[4]; 6. strcpy(name2,name); 7. printf("Value of second string is: %s",name2); 8. return 0; 9.} strncpy strncpy(s1, s2, n) copies the first ‘n’ characters of the second string s2 to the first string s1
  • 186. 186 String functions (strcat) The strcat(first_string, second_string) function concatenates two strings and result is returned to first_string #include<stdio.h> #include <string.h> int main(){ char ch[6]={'h', 'e', 'l', 'l', 'o'}; char ch2[3]={'c','i'}; strcat(ch,ch2); printf("Value of first string is: %s",ch); return 0; }
  • 187. 187 String functions (strncat) strncpy strncpy(s1, s2, n) copies the first ‘n’ characters of the second string s2 to the first string s1. char s2[ ]= "Hello"; char s1[10]; strncpy(s1, s2, 2);
  • 188. 188 String functions (strcmp) strcmp strcmp(s1, s2) compares two strings and finds out whether they are same or different. It compares the two strings character by character till there is a mismatch. If the two strings are identical, it returns a 0. If not, then it returns -1. strncmp strncmp(s1, s2, n) compares the first ‘n’ characters of s1 and s2. If the two strings are identical, it returns a 0. If not, it may return the difference between the ASCII values of the first non-matching pair of characters.
  • 189. 189 #include <stdio.h> #include <string.h> int main() { char s1[ ]= "Healo"; char s2[ ]= "Hebld"; int i, j; i = strcmp(s1, "Hello"); j = strncmp(s1,s2,3); printf("%d n %dn", i, j); return 0; } -1 -1 #include <stdio.h> #include <string.h> int main() { char s1[ ]= "Heblo"; char s2[ ]= "Heald"; int i, j; i = strcmp(s1, "Hello"); j = strncmp(s1,s2,3); printf("%d n %dn", i, j); return 0; } -1 1
  • 190. 190 String functions __ The strrev(string) function returns reverse of the given string. The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr() function. The strupr(string) function returns string characters in uppercase. Let's see a simple example of strupr() function.
  • 191. Memory Layout of C program 191
  • 192. 192
  • 193. 193 C program contains five segments these are : text segment. DS (Data Segment) and BSS (block started by symbol), heap segment, the stack segment
  • 194. 194 Text Segment  A text segment, also known as a code segment or simply as text, which contains executable instructions.(compiled program instructions)  text segment may be placed below the heap or stack(low memory address) in order to prevent heaps and stack overflows from overwriting it.  the text segment is sharable so that only a single copy needs to be in memory for frequently executed programs, the text segment is often read-only, to prevent a program from accidentally modifying its instructions
  • 195. 195 Data Segment DS(Initialized data segment): •It contains the explicitly initialized global and static variables. •The size of this segment is determined by the size of the values in the program’s source code and does not change at run time. •It has read-write permission so the value of the variable of this segment can be changed at run time. int global_var = 50; //read write permission const int global_var2 = 30 //read-only permission
  • 196. 196 BSS Segment BSS _[block staring segment](Uninitialized data segment): //block starting symbol •It contains all uninitialized global and static variables. •All variables in this segment initialized by the zero(0) and pointer with the null pointer. •The program loader allocates memory for the BSS section when it loads the program.
  • 197. 197 Heap Segment Heap: •It is used to allocate the memory at run time. •Heap area managed by the memory management functions like malloc, calloc, free, etc which may internally use the brk and sbrk system calls to adjust its size.
  • 198. 198 Stack Segment •It is located at a higher address and grows and shrinks opposite to the heap segment. •The stack contains local variables from functions and related book-keeping data. •Each function has one stack frame. •Stack frames contain the function’s local variables arguments and return value. •The stack contains a LIFO structure. Function variables are pushed onto the stack when called and functions variables are popped off the stack when return. •SP(stack pointer) register tracks the top of the stack.
  • 202. 202 #include<stdio.h> Int y; int x=10; int main() { return 0; } BSS segment
  • 203. 203 Stack Heap Bss Segment Data segment Text segment #include<stdio.h> int a=10; int b=10; int c=10; int main() { int vol=volume(); printf("the volume =%d“,vol); } int volume() { int ar=area(a,b); int volume= ar*c; return volume; } int area(int x, int y) { int area=x*y; return area; } a=10 b=10 C=10 Main() Int vol Printf() return Volume() ar, volume return area() X,y,area return
  • 205. 205  Pointer is a derived data type • Pointer contains the memory addresses • Pointer are used to manipulate the data stored in the memory Pointers are most efficient in handling arrays Pointers can be used to return multiple values from a function via function arguments. Pointers allow c to support dynamic memory allocation Pointers reduce the length and complexity of programs. They increase execution speed Each cell , commonly known as byte has number called address
  • 206. 206 Int quantity =179; The system finds a location for the integer variable quantity and puts the value 179 in that location let us suppose system chose the address 5000 for quantity 179 quantity 5000 v a r i a b l e a d d r e s s v a l u e Same like house name with house number We can access value with quantity or address
  • 207. 207 Since memory address is like number we can assign it to variable and save it in memory. Such variable that hold memory address are called pointer variables A pointer variable is a variable that holds the address, which is the location of another variable in memory variable value address quantity 179 5000 p 5000 5078 Since the value of variable p is the address of the variable quantity we may access the value of quantity by using the value of p The variable p points to variable quantity thus p gets the name pointer
  • 208. 208 Pointer constant: Memory address within a computer are called pointer constant. We can not change them; we can use them to store data values Pointer values: we can not save the value of memory address directly. We can obtain value through variable stored there using address operator &. The value thus obtained is called pointer value Pointer Variable: After getting pointer value, it can be stored into another variable called pointer variable
  • 209. 209 Accessing the Address of a variable 1. The actual location of a variable is machine dependent p=&quantity Would assign the address(say 5000) to p & operator can be used with simple variables or the element of an array. Illegal use of & operator: 1. &125 2. Int x[30] &x; 3. &(x+y) Program………
  • 210. 210 Declaring a pointer variable 1. Every variable must be declared for its type. 1. Pointer variable contains the address that belong to separate data type they must be declared as pointer.
  • 211. 211 Datatype *pointer_name; Int *p; declares the variable p as a pointer variable that points to an integer data type Important: int refers to the data type of the variable being pointed to by p Float *x; X as a pointer to floating point variable; The declaration cause the compiler to allocate memory locations for the pointer variables p and x. since the memory location have not been assigned any values, these location may contain some unknown values
  • 212. 212 Int *p p ? Unknown location Int* p; Int *p; Int * p;
  • 213. 213 Initialization of pointer variable 1. The process of assigning the address of a variable to a pointer variable is called initialization. Int *p; p=&quantity; Or Int *p=&quantity;
  • 214. 214 Float a,b; Int x, *p; p=&a //wrong We declare pointer as int type, the system assumes that any address that the pointer will hold will point to an integer variable. Compiler doesn’t detect such errors. So be careful to avoid wrong pointer assignment We can also define pointer variable with NULL or 0. Int *p=NULL Or Int *p=0;
  • 215. 215 Accessing a variable through its pointer 1. How to access the value of the variable using pointer? This can be done using unary operator *(asterisk) Int quantity, *p, n; Quantity=10; p=&quantity; n=*p n=*&quantity
  • 216. 216 Symbol Name Description & Address of operator Used to find the address of a variable ∗ Indirection operator Used to access the value at an address
  • 217. 217 #include<stdio.h> int main() { int x,*p1, **p2; x=100; p1=&x; p2=&p1; printf("%dn",p1); printf("%d",*p2); printf("%d",**p2); }
  • 218. 218 Chain of pointers It is possible to make a pointer to point to another pointer, thus creating a chain of pointers. Address 2 Address 1 value p2 variable p1 This is knows a multiple indirections Int **p2 This declaration tells the compiler that p2 is a pointer to a pointer of int type. P2 is pointer to a integer but pointer to an integer pointer
  • 219. 219 Pointer Expression Like other variables , pointe variables can be used in expression, e.g if p1 and p2 are properly initialized then Y=*p1 * p2; Z=*p2/ *p1; C allows us to add and subtract integers from pointers.  P1+4;  P2-2;  P1-p2 are allowed if both pointer are of same array. -then p1-p2 gives the number of elements b/w p1 and p2; P1>p2 or p1==p2, are allowed , if they don’t refer to separate and un realted variables. P1/p2 or p1*p2 or p1/5 are not allowed
  • 220. a=2 b7= Z=8 220 Write a program to illustrate the use of pointer in arithmetic operations int main() { int a, b, *p1, *p2, x,y,z; a=12; b=4; p1=&a; p2=&b; x=*p1 * *p2 -6; y= 4* -*p2/ *p1 +10; *p2=*p2+3; *p1=*p2 -5; z=*p1 * *p2 -6; printf( "a= %d ,b =%dn",a,b); printf("z=%d",z); }
  • 221. 221 Pointer increment and Scale factor P2=P2+2; P1=p1+1; It will cause the pointer say p1 to next value of its type, e.g if p1 has value 62280 the after increment by 1 new value will be 62284; Its value is increase by length of data type called the scale factor
  • 222. 222 #include<stdio.h> int main() { int a, b, *p1, *p2, x,y,z; a=12; b=4; p1=&a; p2=&b; x=*p1 * *p2 -6; y= 4* -*p2/ *p1 +10; *p2=*p2+3; *p1=*p2 -5; z=*p1 * *p2 -6; printf( "a= %d ,b =%dn",a,b); printf("z=%d",z); printf("-------------------------n"); printf("%dn",p1); p1=p1+1; printf("%dn",p1); }
  • 223. 223 Pointers and Arrays When array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of first element 1 2 3 4 5 6 7 1000 1004 1008 1012 1016 1020 1024 Address of x[4]=Base address + (4 X scale of data type) 1000+4X4= 1016; Now instead of using index we can use now pointer to access the array elements; P+4; Which is faster than using indexing
  • 224. #include<stdio.h> int main() { int *p ,sum; int x[5]={5,9,6,3,7}; int i=0; p=x; printf("Elements value address"); while(i<5) { printf("x[%d] %d %un",i,*p,p); sum=sum + *p; i++,p++; } printf("n sum= %dn",sum); printf("n x[0]= %un",&x[0]); printf("p= %u",p); ret 224 Write a program using pointers to compute the sum of all elements stored in an array
  • 225. 225 Pointers and character Strings String are treated like character arrays and therefore they are declared and initialized as follows : Char str[5]=“hello” ; Compiler automatically inserts null character ‘0’ at end of string. Alternative method C supports : Char *str=“good”; IT stores address in the pointer variable str. H E L L O 0 str
  • 226. 226 Run time Assignment: Char *string1; String1=“good”; To print the content of string String1: Printf(“%s”,string1) No need to used indirection operator * here
  • 227. #include<stdio.h> int main() { char *name; int length; name="hello"; char *cptr=name;; printf("%sn",name); printf("%dn",name); printf("%dn",cptr); while(*cptr != '0') { printf("%c is stored at %un",*cptr,cptr); cptr++; } length=cptr-name; printf("n length of string =%d",length); return 0; } 227 With the help of pointers, sort an array? 5,7,3,8,9,2 Write a program using pointers to determine the length of characters In string
  • 228. 228 int main() {int prime[5] = {2,3,5,7,11}; printf("Result using &prime = %dn",&prime); printf("Result using prime = %dn",prime); printf("Result using &prime[0] = %dn",&prime[0]); } int main() { int prime[5] = {2,3,5,7,11}; printf("Result using &prime = %dn",&prime + 1); printf("Result using prime = %dn",prime + 1); printf("Result using &prime[0] = %dn",&prime[0] + 1); }
  • 229. 229 Pointer as function arguments When we pass the address to a function, the parameters receiving the addresses should be pointer. The process of calling a function using pointers to pass the address of variable is known as call by reference. The function which is called by reference can change the value of the variable used in the call Int main() { Show(&x); } Change(int *p) { }
  • 230. #include<stdio.h> int main() { int x,y; x=100; y=200; printf("before exhange x=%d,y=%dn",x,y); swap(&x,&y); printf("After exhange x=%d,y=%dn",x,y); } void swap(int *a, int *b) { int temp =*a; *a=*b; *b=temp; } Write a function using pointer to exchange the values stored in two location in memory 230
  • 231. Function returning pointers THE FUNCTION CAN RETURN MULTIPLE VALUES THROUGH POINTER PARAMETER. WE CAN FORCE A FUNCTION TO RETURN A POINTER TO THE CALLING FUNCTION 231 Main() { Int a=10; Int b=20; Int *p; P=larger(&a,&b) Print(“%d”,*p); Int *larger(int *x , int *y) { If(*x>*y) Return x ; //address of x } Else Return y; //address of y
  • 232. #include <stdio.h> void greatestOfAll( int *p){ int max = *p; for(int i=0; i < 5; i++){ if(*(p+i) > max) max = *(p+i); } printf("The largest element is %dn",max); } main(){ int myNumbers[5] = { 34, 65, -456, 0, 3455}; greatestOfAll(myNumbers); /* Prints :The largest element is 3455" */ } 232 Create a function and Find the largest element in the array by passing address of array to the function(take help of pointer/s. Also find the size of array both in main function using sizeof operator
  • 233. 233
  • 234. 234 Write a program in c That passes array as a parameter to function and then adds value 3 to the each element in array using pointers and then updated array is printed in the main function Int main() { Define array Call function(array name) Prints updated array; } Function(-------) { Adds 3 to each element } Given that Elements of array are: 5 6 4 3 2 7 After adding 3: 8,9,7,6,5,10
  • 235. 235 Use sizeof operator find the size of an integer array
  • 236. 236 Pointers to Functions #include <stdio.h> int main() { printf("Address of main() function is %p",&main); return 0; }
  • 237. 237 Pointers to Functions A function like variable has type and address location in the memory. it is possible to declare a pointer to a function, which can then be used as a argument in another function A pointer to function is decalred as: Type (*fptr) (); This tells compiler that fptr is a pointer to a function, which return type value. The parentheses around around *fptr are necessary . Statement type *large() would declare large as function returning a pointer to type
  • 238. 238 int mul(int, int); Int (*p) (); P1=mul; //p1 to point mul We can use the pointer p1 with list of parameters that is (*p1)(x,y); is same as mul(x,y)
  • 239. 239 1.include <stdio.h> 2.void func1(void (*ptr)()); 3.void func2(); 4.int main() 5.{ 6. func1(func2); 7. return 0; 8.} 9.void func1(void (*ptr)()) 10.{ 11. printf("Function1 is called"); 12. (*ptr)(); 13.} 14.void func2() 15.{ 16. printf("nFunction2 is called"); 17.} Passing a function's address as an argument to other function
  • 240. 240 #include<stdio.h> #define PI 3.14 double y(double); double table(double(*f)(),double, double,double); int main() { printf("Table of y(x)=2*x*x-x+1nn"); table(y,0.0,2.0,0.5); table(cos,0.0,PI,0.5); } double table(double (*f)(), double min, double max,double step) { double a,value; for(a=min; a<=max;a+=step) { value=(*f)(a); printf("%lfn",value); } } double y(double x) { return (2*x*x-x+1); }
  • 241. 241 #include<stdio.h> int length(int (*fp)(),int l,int b); int volume(); int main() { int l=10; int b=20; length(volume,l,b); } int length(int (*fp)(),int l,int b) { int z=(*fp)(); printf("%d",z*l*b); } int volume() { return 30; }
  • 242. 242 #include<stdio.h> int *add(int*, int*); int main() { int a=10; int b=12; int* (*fp)(); fp=add; int *z=(*fp)(&a,&b); z=z+20; printf("%d",z); } int *add(int *x, int *y) { *x=*x+*y; printf("%dn",*x); return x; }
  • 243. 243 Create a function and swap two arrays with the help of pointers
  • 244. 244 const Pointer in C A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the address will remain constant. Therefore, we can say that if a constant pointer is pointing to some variable, then it cannot point to any other variable. int *const ptr; 1. int *const ptr; 2. ptr=&a; 3. ptr=&b
  • 245. 245 Pointer to Constant A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed. 1.const int* ptr; 2. ptr=&b; 3. *ptr=10;
  • 246. 246 Constant Pointer to a Constant A constant pointer to a constant is a pointer, which is a combination of the above two pointers. It can neither change the address of the variable to which it is pointing nor it can change the value placed at this address. 1. const int* const ptr=&a; 2. *ptr=12; 3. ptr=&b; 4. printf("Value of ptr is :%d",*ptr);
  • 247. 247 void pointer in C if we declare the int pointer, then this int pointer cannot point to the float variable or some other type of variable A pointer to void means a generic pointer that can point to any data type •Dereferencing a void pointer in C we print the value of the variable which is pointed by the void pointer 'ptr' by using the statement given below: *(int*)ptr;
  • 248. 5 marks question 248 The company was established in 2010 and it was decided that 5 employees were going to work in the company, So a programmer hired at that time to develop a program for the company decided to declare an array of size 5 that contains the integer employee id greater than zero, but, only 3 persons joined the company having employee id 12,13,14 and the vacancy of two employees is still pending. As now you are hired in the same company as a programmer you are requested to display the current content of the same array and also the total number of elements(current employees) without modifying the previous array(size/empid) Given : Int empid[5]={12,13,14} Constraint: As the vacancy of two employees is pending, if they joined their entry is to be done in the same array and your program must display all the empid’s and count(i.e 5) without changing any line of code. 10 marks question
  • 249. 249 Q1 Write a c program to copy one array to another using pointers Q2 Write a program to find the reverse of a string using pointers; Q3 A company needs a program that can manage its inventory of products. Each product has a name, ID number, price, and quantity in stock. Write a C program that can perform the following tasks: 1. Add a new product to the inventory by accepting input for the name, ID number, price, and quantity in stock. 2. Display the current inventory by listing all products and their corresponding information. 3. Search for a product by ID number and display its information. 4. Exit the program
  • 250. 250 suppose the input list contains the following integer values: [10, 20, 30, 20, 40, 10, 50, 30] The program should recognize that the values 10, 20, and 30 are duplicates, and discard all but one of them, resulting in the following list: [10, 20, 30, 40, 50] suppose the input list contains the following integer values: [10, 20, 30, 20, 40, 10, 50, 30] The program should recognize that the values 10, 20, and 30 are duplicates, and discard all of them, resulting in the following list: [30, 40, 50]
  • 252. 252 2D array will store the data in table form like matrix consisting of rows and columns Type Array_name[row size][column size]
  • 253. 253 12 [0][0] 14[0][1] 12[0][2] 34[1][0] 45[1][1] 67[1][2] 23[2][1] 45[2][1] 67[2][1] Col 0 Col 1 Col 2 Row 0 Row 1 Row 2
  • 254. 254 Initialization of 2D Array in C int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; int c[2][3] = {{1, 3, 0}, {-1, 5, 9}}; int c[][3] = {{1, 3, 0}, {-1, 5, 9}}; int c[2][3] = {1, 3, 0, -1, 5, 9};
  • 255. 255 1.Int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; 2.for(i=0;i<4;i++){ 3. for(j=0;j<3;j++){ 4. printf("arr[%d] [%d] = %d n",i,j,arr[i][j]); Write a program that do the Sum of two matrices of size 2x2 and stores the result in third matrix
  • 256. 256 Write a program and Transport the matrix 1 2 3 4 5 6 7 8 9 1 4 7 2 5 8 3 6 9
  • 257. 257
  • 258. 258 For example: #include <stdio.h> int main(void) { int m,n; int arr[] = {4, 3, 1, 2}; int *p = arr; } Now suppose we want a pointer to point to a 2D array. We saw a single pointer can point to an entire 1D array. So all we need to do is create a pointer for each row/column of the 2D array. #include <stdio.h> int main(void) { int arr[2][3] = {{3, 2, 1}, {8, 9, 10}}; int *p[2]; p[0] = arr[0]; //Pointer points to first row of 2D array p[1] = arr[1]; //Pointer points to second row of 2D array } Address of 3 Address of 4 3 2 1 4 3 1 2