0% found this document useful (0 votes)
2 views119 pages

CS174 ProgramminginC 1

The document outlines the structure and fundamentals of the C programming language, including its history, control structures, functions, arrays, pointers, and file processing. It explains the process of compiling and executing C programs, detailing the steps from writing code to debugging. Additionally, it covers key concepts such as identifiers, keywords, and the use of Integrated Development Environments (IDEs) in programming.

Uploaded by

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

CS174 ProgramminginC 1

The document outlines the structure and fundamentals of the C programming language, including its history, control structures, functions, arrays, pointers, and file processing. It explains the process of compiling and executing C programs, detailing the steps from writing code to debugging. Additionally, it covers key concepts such as identifiers, keywords, and the use of Integrated Development Environments (IDEs) in programming.

Uploaded by

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

Course Units

Unit I: Introduction to C programming Language

Unit II: Control Structures

Unit III: Functions

Unit IV: Arrays

Unit V: Points

Unit VI: Structures, Unions and enumerated types

Unit VII: File Processing


Unit I: Introduction to C programming Language

LECTURE ONE
Unit I: Introduction to C programming Language

 Developed at AT & T’s Bell Laboratories of USA in 1972


 Designed and written by a man named Dennis Ritchie
 In the late seventies C began to replace the more familiar
languages of that time like PL/I, ALGOL, etc
 It was initially designed for programming UNIX operating
system
 Software tools as well as the C compiler are written in C
 Major parts of popular operating systems like Windows, UNIX,
Linux is still written in C
 This is because even today when it comes to performance
(speed of execution) nothing beats C
Unit I: Introduction to C programming Language..

 Moreover, if one needs to extend the operating system to work


with new devices one needs to write device driver programs
 These programs are exclusively written in C
 C seems so popular because it is
 Reliable
 Simple and
 Easy to use
Program

 There is a close analogy between learning English language


and learning C language.
 The classical method of learning English is to first learn the
alphabets used in the language, then learn to combine these
alphabets to form words
 Which in turn are combined to form sentences and
sentences are combined to form paragraphs
 Learning C is similar and easier. Instead of straight-away learning
how to write programs,
 We must first know what alphabets, numbers and special
symbols are used in C
Program

 Then how using them? - constants, variables and


keywords are constructed, and finally how are these
combined to form an instruction.
 A group of instructions would be combined later on to form
a program.
Program

 Therefore, a computer program is a collection of the


instructions necessary to solve a specific problem.
 The basic operations of a computer system form what is known
as the computer’s instruction set
 And the approach or method that is used to solve the problem is
known as an algorithm.
 So far as programming language concern these are of two
types.
1. Low level programming language
2. High level programming language
Low level programming language

 Low level languages are machine level and assembly level


language
 In machine level language computer only understand digital
numbers i.e. in the form of 0 and 1
 Instruction given to the computer is in the form of binary digit,
which is difficult to implement instruction in binary code
 This type of program is not portable, difficult to maintain and also
error prone
 The assembly language is on other hand modified version of
machine level language
 Where instructions are given in English like word as ADD, SUM,
MOV etc
Low level programming language…

 It is easy to write and understand but not understand by the


machine
 So the translator used here is assembler to translate into
machine level
 Although language is bit easier, programmer has to know low
level details related to low level language
 In the assembly level language the data are stored in the
computer register, which varies for different computer.
 Hence it is not portable.
High level programming language…

 These languages are machine independent, means they are


portable. The languages in this category are Pascal, Cobol,
Fortran etc.
 High level languages are understood by the machine. The
machine use translator to translate into machine level
 A translator is software which is used to translate high level
language as well as low level language into machine level
language.
 There are three types of translator:
1. Compiler
2. Interpreter
3. Assembler
High level programming language

 A compiler or an interpreter is a program that converts program


written in high-level language into machine code understood by the
compute
 The program written in high level language is known as source
program and the corresponding machine level language program is
called as object program
 Both compiler and interpreter perform the same task but there
working is different
 Compiler read the program at-a-time and searches the error and
lists them
 If the program is error free then it is converted into object
program
 When program size is large then compiler is preferred
High level programming language

 Whereas interpreter read only one line of the source code and
convert it to object code.
 It checks error, statement by statement i.e. line by line and
hence takes more time.
High level programming language

Difference between Compiler and


Interpreter
Integrated Development Environments (IDE)

 The process of editing, compiling, running, and debugging


programs is often managed by a single integrated application
known as an Integrated Development Environment (IDE).
 An IDE is a windows-based program that allows us to easily
manage large software programs, edit files in windows, and
compile, link, run, and debug programs.
 On Mac OS X, CodeWarrior and Xcode are two IDEs that are used
by many programmers
 Under Windows, Microsoft Visual Studio is a good example of a
popular IDE.
 Kylix is a popular IDE for developing applications under Linux
 IDEs also support program development in several different
programming languages in addition to C, such as C# and C++.
Structure of C Language program

1 ) Comment line
2) Preprocessor directive
3 ) Global variable declaration
4) main function( )
{
Local variables;
Statements;
}
User defined function
}
}
Structure of C Language program…

 Comment line
It indicates the purpose of the program. It is represented as
/*……………………………..*/
Comment line is used for increasing the readability of the
program.
It is useful in explaining the program and generally used for
documentation.
It is enclosed within the decimetres. Comment line can be
single or multiple line but should not be nested.
It can be anywhere in the program except inside string
constant & character constant.
Structure of C Language program…

 Preprocessor Directive
 #include<stdio.h> tells the compiler to include information
about the standard input/output library.
 It is also used in symbolic constant such as #define PI
3.14(value).
 The stdio.h (standard input output header file) contains
definition &declaration of system defined function such as
printf( ), scanf( ), pow( ) etc.
 Generally printf() function used to display and scanf()
function used to read value
Structure of C Language program…

 Global Declaration
 This is the section where variable are declared globally so
that it can be access by all the functions used in the
program. And it is generally declared outside the function

 Main()
 It is the user defined function and every function has one
main() function from
 Where actually program is started and it is encloses within the
pair of curly braces.
 The main( ) function can be anywhere in the program but in
general practice it is placed in the first position.
Structure of C Language program…

 Main() ….
It Syntax :
main()
{
……..
……..
}
The main( ) function return value when it declared by data type
as int main( )
{
return 0
}
Structure of C Language program…

 Main() ….
The main function does not return any value when void
(means null/empty) as void main(void ) or void main()
{
printf (“C language”);
}
Output: C language
 The program execution start with opening braces and end with
closing brace.
 And in between the two braces declaration part as well as
executable part is
 mentioned. And at the end of each line, the semi-colon is given
which indicates statement termination
Structure of C Language program…

/*First c program with return statement*/


#include <stdio.h>
int main (void)
{
printf ("welcome to c Programming language.\n");
return 0;
}
Output: welcome to c programming language.
Steps for Compiling and executing the Programs

 A compiler is a software program that analyzes a program


developed in a particular computer language and then
translates it into a form that is suitable for execution on a
particular computer system
 Figure in the next slide shows the steps that are involved in
entering, compiling, and executing a computer program
developed in the C programming language and the typical
Unix commands that would be entered from the command
line
Steps for Compiling and executing the Programs
Steps for Compiling and executing the Programs

 Step 1
 The program that is to be compiled is first typed into a file on the
computer system.
 There are various conventions that are used for naming files,
typically be any name provided the last two characters are “.c” or
file with extension .c.
 So, the file name prog1.c might be a valid filename for a C
program. A text editor is usually used to enter the C program into
a file.
 For example, vi is a popular text editor used on Unix systems. The
program that is entered into the file is known as the source
program because it represents the original form of the program
expressed in the C language.
Steps for Compiling and executing the Programs

 Step 2
 The compilation process is initiated by typing a special command
on the system. When this command is entered, the name of the
file that contains the source program must also be specified.
 For example, under Unix, the command to initiate program
compilation is called cc. If we are using the popular GNU C
compiler, the command we use is gcc.
$ gcc prog1.c or cc prog1.c
 In the first step of the compilation process, the compiler examines
each program statement contained in the source program and
checks it to ensure that it conforms to the syntax and semantics of
the language
Steps for Compiling and executing the Programs

 Step 2…
 If any mistakes are discovered by the compiler during this phase,
they are reported to the user and the compilation process ends
right there.
 The errors then have to be corrected in the source program (with
the use of an editor), and the compilation process must be
restarted.
 Typical errors reported during this phase of compilation might be
due to an expression that has unbalanced parentheses (syntactic
error), or due to the use of a variable that is not “defined”
(semantic error).
Steps for Compiling and executing the Programs

 Step 3
 When all the syntactic and semantic errors have been
removed from the program, the compiler then proceeds to
take each statement of the program and translate it into a
“lower” form that is equivalent to assembly language
program needed to perform the identical task.
Steps for Compiling and executing the Programs

 Step 4
 After the program has been translated the next step in the
compilation process is to translate the assembly language
statements into actual machine instructions.
 The assembler takes each assembly language statement
and converts it into a binary format known as object code,
which is then written into another file on the system.
 This file has the same name as the source file under Unix,
with the last letter an “o” (for object) instead of a “c”.
Steps for Compiling and executing the Programs

 Step 5
 After the program has been translated into object code, it is
ready to be linked.
 This process is once again performed automatically whenever
the cc or gcc command is issued under Unix.
 The purpose of the linking phase is to get the program into a
final form for execution on the computer.
 If the program uses other programs that were previously
processed by the compiler, then during this phase the
programs are linked together.
Steps for Compiling and executing the Programs

 Step 5…
 Programs that are used from the system’s program library are also
searched and linked together with the object program during this phase.
 The process of compiling and linking a program is often called building.
 The final linked file, which is in an executable object code format, is
stored in another file on the system, ready to be run or executed.
 Under Unix, this file is called a.out by default.
 Under Windows, the executable file usually has the same name as the
source file, with the c extension replaced by an exe extension
Steps for Compiling and executing the Programs

 Step 6
 To subsequently execute the program, the command a.out has the effect of
loading the program called a.out into the computer’s memory and initiating its
execution.
 When the program is executed, each of the statements of the program is
sequentially executed in turn.
 If the program requests any data from the user, known as input, the program
temporarily suspends its execution so that the input can be entered
 Or, the program might simply wait for an event, such as a mouse being clicked,
to occur
Steps for Compiling and executing the Programs

 Step 6…
 Results that are displayed by the program, known as output, appear in a
window, sometimes called the console.
 If the program does not produce the desired results, it is necessary to go
back and reanalyze the program’s logic.
 This is known as the debugging phase, during which an attempt is made
to remove all the known problems or bugs from the program.
 To do this, it will most likely be necessary to make changes to original
source program.
/* Simple program to add two numbers…………………….*/

#include <stdio.h>
int main (void)
{
int v1, v2, sum; //v1,v2,sum are variables and int is data type
declared
v1 = 150;
v2 = 25;
sum = v1 + v2;
printf ("The sum of %i and %i is= %i\n", v1, v2, sum);
return 0;
}
Output:
The sum of 150 and 25 is=175
END OF LECTURE ONE
DISCUSSION QUESTIONS
Unit I: Introduction to C programming Language

LECTURE TWO
Character set

 A character denotes any alphabet, digit or special symbol used


to represent information.
 Valid alphabets, numbers and special symbols allowed in C
are

 The alphabets, numbers and special symbols when


properly combined form constants, variables and keywords.
Identifiers

 Identifiers are user defined word used to name entities like


variables, arrays, functions, structures etc
 Rules for naming identifiers are:
1. Name should only consists of alphabets (both upper and lower
case), digits and underscore (_) sign.
2. First characters should be alphabet or underscore
3. Name should not be a keyword
4. Since C is a case sensitive, the upper case and lower case
considered differently, for example code, Code, CODE etc.
are different identifiers.
5. Identifiers are generally given in some meaningful name such
as value, net_salary, age, data etc
Keyword

 There are certain words reserved for doing specific task, these
words are known as reserved word or keywords. These
words are predefined and always written in lower case or small
letter.
 These keywords can’t be used as a variable name as it
assigned with specific meaning.
 Some examples are:
int, short, signed, unsigned, default, volatile, float, long,
double, break, continue, typedef, static, do, for, union,
return, while, do, extern, register, enum, case, goto, struct,
char, auto, const etc.
Data types

 Data types refer to an extensive system used for declaring


variables or functions of different types before its use.
 The type of a variable determines how much space it occupies
in storage and how the bit pattern stored is interpreted.
 The value of a variable can be changed any time. C has the
following 4 types of data types
 Basic built-in data types: int, float, double, char
 Enumeration data type: enum
 Derived data type: pointer, array, structure, union
 Void data type: void
Data types…

 A variable declared to be of type int can be used to contain


integer values only—that is, values that do not contain decimal
places.
 A variable declared to be of type float can be used for storing
floating- point numbers (values containing decimal places).
 The double type is the same as type float, only with roughly
twice the precision.
 The char data type can be used to store a single character,
such as the letter a, the digit character 6, or a semicolon
similarly A variable declared char can only store character type
value.
Data types…

 There are two types of type qualifier in c


 Size qualifier: short, long
 Sign qualifier: signed, unsigned
 When the qualifier unsigned is used the number is always
positive, and when signed is used number may be positive or
negative.
 The range of values for signed data types is less than that of
unsigned data type
 Because in signed type, the left most bit is used to represent sign,
while in unsigned type this bit is also used to represent the value.
 The size and range of the different data types on a 16 bit machine
is given in the table next slide:
Data types…
Constants

 Constant is a any value that cannot be changed during program


execution.
 In C, any number, single character, or character string is known
as a constant.
 A constant is an entity that doesn’t change whereas a variable is
an entity that may change.
 For example, the number 50 represents a constant integer value.
The character string "Programming in C is fun.\n" is an example of
a constant character string.
 C constants can be divided into two major categories:
 Primary Constants
 Secondary Constants
Constants..

 These constants are further categorized as

Numeric constant
Character constant
String constant
Numeric constant

 Numeric constant consists of digits. It required minimum size of 2


bytes and max 4 bytes. It may be positive or negative but by
default sign is always positive.
 No comma or space is allowed within the numeric constant and it
must have at least 1 digit. The allowable range for integer
constants is -32768 to 32767.
 Truly speaking the range of an Integer constant depends upon the
compiler.
 For a 16-bit compiler like Turbo C or Turbo C++ the range is -
32768 to 32767.
 For a 32-bit compiler the range would be even greater. Mean by a
16-bit or a 32-bit compiler, what range of an Integer constant has
to do with the type of compiler
Numeric constant

 It is categorized a integer constant and real constant. An


integer constants are whole number which have no decimal point.
 Types of integer constants are:
 Decimal constant: 0-------9(base 10)
 Octal constant: 0-------7(base 8)
 Hexadecimal constant: 0----9, A------F(base 16)
 In decimal constant first digit should not be zero unlike octal
constant first digit must be zero(as 076, 0127) and in hexadecimal
constant first two digit should be 0x/ 0X (such as 0x24, 0x87A)
 By default type of integer constant is integer but if the value of
integer constant is exceeds range then value represented by
integer type is taken to be unsigned integer or long integer
Real constant

 It is also called floating point constant. To construct real constant


we must follow the rule of
 Real constant must have at least one digit.
 It must have a decimal point.
 It could be either positive or negative.
 Default sign is positive.
 No commas or blanks are allowed within a real constant. Ex.: +325.34
426.0 -32.76
 To express small/large real constant exponent(scientific) form is used
where number is written in mantissa and exponent form separated by
e/E.
 Exponent can be positive or negative integer but mantissa can be
real/integer type, for example 3.6*105=3.6e+5. By default type of floating
point constant is double
Character constant

 Character constant represented as a single character enclosed


within a single quote.
 These can be single digit, single special symbol or white
spaces such as ‘9’,’c’,’$’, ‘ ’ etc.
 Every character constant has a unique integer like value in
machine’s character code as if machine using ASCII (American
standard code for information interchange)
A------------ Z ASCII value (65-90)
a-------------z ASCII value (97-122)
0-------------9 ASCII value (48-59)
; ASCII value (59)
String constant

 Set of characters are called string and when sequence of


characters are enclosed within a double quote (it may be
combination of all kind of symbols) is a string constant.
 String constant has zero, one or more than one character and
at the end of the string null character(\0) is automatically
placed by compiler.
 Some examples are “Tanzania” , “908”, “3”,” ”, “A” etc.
 In C although same characters are enclosed within single and
double quotes it represents different meaning such as “A” and
‘A’ are different because first one is string attached with null
character at the end but second one is character constant with
its corresponding ASCII value is 65.
Symbolic constant

 Symbolic constant is a name that substitute for a sequence of


characters and, characters may be numeric, character or string
constant.
 These constant are generally defined at the beginning of the
program as
 #define name value , here name generally written in upper
case for example
#define MAX 10
#define CH ‘b’
#define NAME “sony”
Variables

 Variable is a data name which is used to store some data value


or symbolic names for storing program computations and
results.
 The value of the variable can be change during the execution.
 The rule for naming the variables is same as the naming
identifier.
 Before used in the program it must be declared.
 Declaration of variables specify its name, data types and
range of the value that variables can store depends upon its
data types.
Variables…

 Syntax:
int a; char c; float f;
 Variable initialization
 When we assign any initial value to variable during the
declaration, is called initialization of variables.
 When variable is declared but contain undefined value then it is
called garbage value.
 The variable is initialized with the assignment operator such as

Data type variable name=constant;


Example: int a=20;
Or int a;
a=20;
Expressions

 An expression is a combination of variables, constants, operators


and function call. It can be arithmetic, logical and relational for
example:-
int z= x+y // arithmetic expression
a>b //relational
a==b // logical
func(a, b) // function call
 Expressions consisting entirely of constant values are called
constant expressions. So, the expression 121 + 17 - 110 is a
constant expression because each of the terms of the expression
is a constant value.
 But if i were declared to be an integer variable, the expression 180
+ 2 - j would not represent a constant expression.
Operator

 Operators are symbols which take one or more operands or


expressions and perform arithmetic or logical computations.
 Operators are used in C language program to operate on data
and variables.
 Some operator required 2 operands to perform operation or Some
required single operation.
 C has a rich set of operators which can be classified as: arithmetic
operator, assignment, increment , decrement, logical, conditional,
comma, size of , bitwise and others.
Arithmetic operator

 All the basic arithmetic operations can be carried out in C. All the
operators have almost the same meaning as in other languages.
 Both unary and binary operations are available in C language.
Unary operations operate on a singe operand, therefore the
number 5 when operated by unary – will have the value –5
+ For performing Addition
- For performing Subtraction
/ For performing Division
* For performing Multiplication
% Modulo for finding remainder in division operation
Note: But modulus cannot applied with floating point operand as well as
there are no exponent operator in c.
Arithmetic operator...

Integer Arithmetic
When an arithmetic operation is performed on two whole numbers
or integers then such an operation is called as integer arithmetic. It
always gives an integer as the result. Let x = 27 and y = 5 be 2
integer numbers. Then the integer operation leads to the following
results.
x + y = 32
x – y = 22
x * y = 115
x%y=2
x/y=5
Note: In integer division the fractional part is truncated.
Arithmetic operator...

Floating point arithmetic


When an arithmetic operation is preformed on two real numbers or
fraction numbers such an operation is called floating point arithmetic.
The floating point results can be truncated according to the
properties requirement. The remainder operator is not applicable for
floating point arithmetic operands.

Let x = 14.0 and y = 4.0 then


x + y = 18.0
x – y = 10.0
x * y = 56.0
x / y = 3.50
Arithmetic operator...

Mixed mode arithmetic


When one of the operand is real and other is an integer and if the
arithmetic operation is carried out on these 2 operands then it is
called as mixed mode arithmetic.
If any one operand is of real type then the result will always be real
thus

15/10.0 = 1.
Relational Operators

 Often it is required to compare the relationship between operands


and bring out a decision and program accordingly. This is when
the relational operator come into picture.
 C supports the following relational operators
Relational Operators..

 It is required to compare the marks of 2 students, salary of 2


persons, we can compare them using relational operators.
 A simple relational expression contains only one relational
operator and takes the following form.
exp1 relational operator exp2
 Where exp1 and exp2 are expressions, which may be simple
constants, variables or combination of them.
 Given below is a list of examples of relational expressions and
evaluated values.
6.5 <= 25 TRUE
10 < 7 + 5 TRUE
Note: Relational expressions are used in decision making statements
of C language such as if, while and for statements to decide the
course of action of a running program.
Logical Operators

 C has the following logical operators, they compare or evaluate


logical and relational expressions.
Logical Operators…

Logical AND (&&)


This operator is used to evaluate 2 conditions or expressions with
relational operators simultaneously.
Both the expressions to the left and to the right of the logical
operator is true then the whole compound expression is true.
For Example
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10
the whole expression is true only if both expressions are true i.e., if a
is greater than b and x is equal to 10.
Logical Operators…

Logical OR (||)
The logical OR is used to combine 2 expressions or the condition
evaluates to true if any one of the 2 expressions is true.
For Example
a < m || a < n
The expression evaluates to true if any one of them is true or if both
of them are true.
It evaluates to true if a is less than either m or n and when a is less
than both m and n.
Logical Operators…

Logical NOT (!)


The logical not operator takes single expression and evaluates to
true if the expression is false and evaluates to false if the expression
is true.
In other words it just reverses the value of the expression.

For Example
! (x >= y)
The NOT expression evaluates to true only if the value of x is
neither greater than or equal to y
Assignment Operators

 The Assignment Operator evaluates an expression on the right of


the expression and substitutes it to the value or variable on the left
of the expression.
For Example
x=a+b
 Here the value of a + b is evaluated and substituted to the
variable x.
 In addition, C has a set of shorthand assignment operators of the
form.
var oper = exp;
 Here var is a variable, exp is an expression and oper is a C binary
arithmetic operator. The operator oper = is known as shorthand
assignment operator.
Assignment Operators…

Shorthand assignment operators


Increment and Decrement Operators

 The Increment and Decrement Operators The increment and


decrement operators are one of the unary operators which are
very useful in C language.
 They are extensively used in for and while loops. The syntax of
the operators is given below
++ variable name
variable name++
– –variable name
variable name– –
 The increment operator ++ adds the value 1 to the current value
of operand and the decrement operator – – subtracts the value 1
from the current value of operand..
Increment and Decrement Operators..

 ++variable name and variable name++ mean the same thing when
they form statements independently, they behave differently when
they are used in expression on the right hand side of an assignment
statement: Consider the following
m = 5;
y = ++m; (prefix)
 In this case the value of y and m would be 6. Suppose if we rewrite
the above statement as
m = 5;
y = m++; (post fix)
 Then the value of y will be 5 and that of m will be 6. A prefix operator
first adds 1 to the operand and then the result is assigned to the
variable on the left. On the other hand, a postfix operator first assigns
the value to the variable on the left and then increments the operand.
Conditional or Ternary Operator

 The conditional operator consists of 2 symbols the question mark


(?) and the colon (:)
 The syntax for a ternary operator is as follows
exp1 ? exp2 : exp3
 The ternary operator works as follows
 exp1 is evaluated first. If the expression is true then exp2 is
evaluated & its value becomes the value of the expression. If exp1
is false, exp3 is evaluated and its value becomes the value of the
expression. Note that only one of the expression is evaluated
 For example
a = 10; Here x will be assigned to the value of b. The
b = 15; condition follows that the expression is false
x = (a > b) ? a : b
therefore b is assigned to x.
Conditional or Ternary Operator…

/* Example : to find the maximum value using conditional operator)


#include
void main() //start of the program
{
int i,j,larger; //declaration of variables
printf (“Input 2 integers : ”); //ask the user to input 2 numbers
scanf(“%d %d”,&i, &j); //take the number from standard input and store it
larger = i > j ? i : j; //evaluation using ternary operator
printf(“The largest of two numbers is %d \n”, larger); // print the largest
number
} // end of the program
 Output : Input 2 integers : 34 45
 The largest of two numbers is 45
Bitwise Operators

 C has a distinction of supporting special operators known as


bitwise operators for manipulation data at bit level. A bitwise
operator operates on each bit of data.
 Those operators are used for testing, complementing or shifting
bits to the right on left. Bitwise operators may not be applied to a
float or double.
Special Operators

 supports some special operators of interest such as comma


operator, size of operator, pointer operators (& and *) and
member selection operators (. and ->).
 The size of and the comma operators are discussed here. .

The Comma Operator


 The comma operator can be used to link related expressions
together. A comma-linked list of expressions are evaluated left to
right and value of right most expression is the value of the
combined expression.
Special Operators

 For example the statement


value = (x = 10, y = 5, x + y);
First assigns 10 to x and 5 to y and finally assigns 15 to value.
Since comma has the lowest precedence in operators the
parenthesis is necessary. Some examples of comma operator
are
In for loops:
for (n=1, m=10, n <=m; n++,m++)
In while loops
While (c=getchar(), c != ‘10’)
Exchanging values
t = x, x = y, y = t;
The size of Operator

 The operator size of gives the size of the data type or variable in
terms of bytes occupied in the memory. The operand may be a
variable, a constant or a data type qualifier.
 For Example
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
 The size of operator is normally used to determine the lengths of
arrays and structures when their sizes are not known to the
programmer.
 It is also used to allocate memory space dynamically to variables
during the execution of the program. Example program that employs
different kinds of operators. The results of their evaluation are also
shown in comparison
C Programming Input Output (I/O): printf() and
scanf()

 C programming has several in-built library functions to perform


input and output tasks.
 Two commonly used functions for I/O (Input/Output) are printf()
and scanf().
 The scanf() function reads formatted input from standard input
(keyboard) whereas the printf() function sends formatted output to
the standard output (screen).
C Programming Input Output (I/O): printf() and
scanf()…

 Example #1: C Output


#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside
quotation
return 0;
}
 Output
C Programming
C Programming Input Output (I/O): printf() and
scanf()…

How this program works?


All valid C program must contain the main() function. The code
execution begins from the start of main() function.
The printf() is a library function to send formatted output to the
screen. The printf() function is declared in "stdio.h" header file.
Here, stdio.h is a header file (standard input output header file) and
#include is a preprocessor directive to paste the code from the
header file when necessary.
When the compiler encounters printf() function and doesn't find
stdio.h header file, compiler shows error.
The return 0; statement is the "Exit status" of the program. In
simple terms, program ends.
C Programming Input Output (I/O): printf() and
scanf()…

 Example #2: C Integer Output


#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
 Output Number = 5
 Inside the quotation of printf() function, there is a format string
"%d" (for integer). If the format string matches the argument
(testInteger in this case), it is displayed on the screen.
C Programming Input Output (I/O): printf() and
scanf()…

 Example #3: C Integer Input/Output


#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d",&testInteger);
printf("Number = %d",testInteger);
return 0;
}

Output Enter an integer: 4


Number = 4
C Programming Input Output (I/O): printf() and
scanf()…

 The scanf() function reads formatted input from the keyboard.


When user enters an integer, it is stored in variable testInteger.
 Note the '&' sign before testInteger; &testInteger gets the
address of testInteger and the value is stored in that address.
C Programming Input Output (I/O): printf() and
scanf()…

 Example #3: C Floats Input/Output


#include <stdio.h>
int main()
Output
{
Enter a number: 23.45
float f;
Value = 23.450000
printf("Enter a number: ");
// %f format string is used in case of floats
scanf("%f",&f);
printf("Value = %f", f);
return 0;
}
The format string "%f" is used to read and display formatted in case
of floats.
C Programming Input Output (I/O): printf() and
scanf()…

 Example #4: C Character I/O


#include <stdio.h>
int main()
Output
{
char chr; Enter a character: g
printf("Enter a character: ");
You entered g.
scanf("%c",&chr);
printf("You entered %c.",chr);
return 0;
}

Format string %c is used in case of character types.


C Programming Input Output (I/O): printf() and
scanf()…

 Little bit on ASCII code


 When a character is entered in the above program, the character
itself is not stored. Instead, a numeric value(ASCII value) is
stored.
 And when we displayed that value using "%c" text format, the
entered character is displayed.
C Programming Input Output (I/O): printf() and
scanf()…

 Example #5: C ASCII Code


#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
// When %c text format is used, character is displayed in case of character
types
printf("You entered %c.\n",chr);
// When %d text format is used, integer is displayed in case of character
types
printf("ASCII value of %c is %d.", chr, chr);
return 0;
}
C Programming Input Output (I/O): printf() and
scanf()…

Output
Enter a character: g
You entered g.
ASCII value of g is 103.
The ASCII value of character 'g' is 103. When, 'g' is entered, 103 is
stored in variable var1 instead of g.
 You can display a character if you know ASCII code of that
character. This is shown by following example.
C Programming Input Output (I/O): printf() and
scanf()…

 Example #6: C ASCII Code


#include <stdio.h>
int main()
{
int chr = 69;
printf("Character having ASCII value 69 is %c.",chr);
return 0;
}

 Output
Character having ASCII value 69 is E.
More on Input/Output of floats and Integers

 Integer and floats can be displayed in different formats in C


programming.
 Example #7: I/O of Floats and Integers
#include <stdio.h>
int main()
{

int integer = 9876;


float decimal = 987.6543;

// Prints the number right justified within 6 columns


printf("4 digit integer right justified to 6 column: %6d\n", integer);

// Tries to print number right justified to 3 digits but the number is not right adjusted
because there are only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);

// Rounds to two digit places


printf("Floating point number rounded to 2 digits: %.2f\n",decimal);

// Rounds to 0 digit places


printf("Floating point number rounded to 0 digits: %.f\n",987.6543);

// Prints the number in exponential notation(scientific notation)


printf("Floating point number in exponential form: %e\n",987.6543);
return 0;
}
More on Input/Output of floats and Integers

Output
4 digit integer right justified to 6 column: 9876
4 digit integer right justified to 3 column: 9876
Floating point number rounded to 2 digits: 987.65
Floating point number rounded to 0 digits: 988
Floating point number in exponential form: 9.876543e+02
END OF LECTURE TWO
DISCUSSION QUESTIONS
Unit II: Control Structures

LECTURE ONE
Control Statement

 Generally C program statement is executed in a order in which


they appear in the program.
 But sometimes we use decision making condition for execution
only a part of program, that is called control statement.
 Control statement defined how the control is transferred from
one part to the other part of the program.
 There are several control statement like if...else, switch, while,
do....while, for loop, break, continue, goto etc.
Loops in C

 Loop:-it is a block of statement that performs set of


instructions.
 In loops
 Repeating particular portion of the program either a specified
number of time or until a particular no of condition is being
satisfied.
 There are three types of loops in c
i. While loop
ii. do while loop
iii. for loop
While loop

 Syntax:-

while(condition)
{
Statement 1;
Statement 2;
}
Or while(test condition)
Statement;
while loop

How while loop works?


The test condition may be any expression
The while loop evaluates the test expression.
If the test expression is true (nonzero), codes inside the body of
while loop is evaluated. The test expression is evaluated again.
The process goes on until the test expression is false.
When the test expression is false, the while loop is terminated.
while loop

Flowchart of while loop


While loop

 Example:-
/* Program to print 5 times welcome to C” */
#include<stdio.h>
void main() Output:
Welcome to C
{ Welcome to C
int p=1; Welcome to C
While(p<=5) Welcome to C
Welcome to C
{
printf(“Welcome to C\n”);
P=p+1;
} So as long as condition remains true statements within the
body of while loop will get executed repeatedly
}
While loop

 Example:-
/* Program to print 5 times welcome to C” */
#include<stdio.h>
void main()
{
int p=1;
While(p<=5)
{
printf(“Welcome to C\n”);
P=p+1;
}
}
do while loop

 This (do while loop) statement is also used for looping. The
body of this loop may contain single statement or block of
statement.
 The syntax for writing this statement is:

Do
{
Statement;
}
while(condition);
do while loop

How do...while loop works?


The code block (loop body) inside the braces is executed
once.
Then, the test expression is evaluated. If the test expression
is true, the loop body is executed again. This process goes on
until the test expression is evaluated to 0 (false).
When the test expression is true (nonzero), the do...while
loop is terminated.
do while loop
do while loop

 If initial condition is false while loop would not executed it’s


statement on other hand do while loop executed it’s
statement at least once even If condition fails for first time.
 It means do while loop always executes at least once.

Notes:
 Do while loop used rarely when we want to execute a loop
at least once
do while loop

 Example:-
#include<stdio.h>
void main()
{
int X=4;
do Output: 4 5 6 7 8 9 10
{
Printf(“%d”,X);
X=X+1;
} while(X<=10);
Printf(“ ”);
}
for loop

 The syntax of a for loop is:

for (initializationStatement; testExpression; updateStatement)


{
// codes
}
for loop

How for loop works?


The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression
is false (0), for loop is terminated. But if the test expression is
true (nonzero), codes inside the body of for loop is executed
and the update expression is updated.
This process repeats until the test expression is false.
The for loop is commonly used when the number of
iterations is known.
for loop

for loop Flowchart


for loop

 Example:-
void main()
{
int i;
for(i=1;i<10;i++)
{
Printf(“ %d ”, i);
}
}
 Output:1 2 3 4 5 6 7 8 9
for loop..

// Program to calculate the sum of first n natural numbers


// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{ Output
int num, count, sum = 0;
Enter a positive integer: 10
printf("Enter a positive integer: ");
Sum = 55
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
for loop…

 The value entered by the user is stored in variable num. Suppose,


the user entered 10.
 The count is initialized to 1 and the test expression is evaluated.
Since, the test expression count <= num (1 less than or equal to
10) is true, the body of for loop is executed and the value of sum
will equal to 1.
 Then, the update statement ++count is executed and count will
equal to 2. Again, the test expression is evaluated. Since, 2 is also
less than 10, the test expression is evaluated to true and the body
of for loop is executed. Now, the sum will equal 3.
 When the count is 11, the test expression is evaluated to 0 (false)
as 11 is not less than or equal to 10. Therefore, the loop
terminates and next, the total sum is printed.
Nesting of loop

 When a loop written inside the body of another loop then,


it is known as nesting of loop.
 type of loop can be nested in any type such as while, do
while, for. For example nesting of for loop can be
represented as :
void main()
{ Output:
int i,j; i=0
for(i=0;i<2;i++) j=0 1 2 3 4
for(j=0;j<5; j++) i=1
j=0 1 2 3 4
printf(“%d %d”, i, j);
}
Break statement(break)

 It is sometimes desirable to skip some statements inside


the loop or terminate the loop immediately without checking
the test expression.
 The break statement terminates the loop (for, while and
do...while loop) immediately when it is encountered. The
break statement is used with decision making statement
such as if...else.
 Syntax of break statement

break;
Break statement(break)…

Flowchart of break statement


Break statement(break)…

How break statement works?


Break statement(break)

 When break is encountered inside any loop, control


automatically passes to the first statement after the loop.
 This break statement is usually associated with if
statement. For example
void main()
{
int j=0; Output:
for(;j<6;j++) 0123
Printf(“ %d ”, j);
if(j==4)
break;
}
Continue statement (key word continue)

 The continue statement skips some statements inside the


loop. It is used to skip the execution of the remaining
statements in a loop and continue with the next iteration of
the loop.

 Syntax of continue Statement


continue;
Continue statement (key word continue)

 How continue statement works?


Continue statement (key word continue)

void main()
{
int n;
for(n=2; n<=9; n++)
{
if(n==4) Output: 2 3 5 6 7 8 9 out of loop
continue;
printf(“%d”, n);
}
}
Printf(“out of loop”);
}
END OF LECTURE ONE
DISCUSSION QUESTIONS

You might also like