SlideShare a Scribd company logo
1 of 160
CSC103:
Programming in C Language
Prepared by:
NZABONITEGEKA Gilbert(MSc.)
Module description
• 15 credits module (100hours)
• 50hours (Face to face/ contact hours)
• Theoretical Part and
• Practical part
• 50 hours (self guided study+ Reading+
Examination)
Examination process
• CAT : Continuous Assessment Test /60 marks,
• Final Exam / 40 marks
Having successfully completed the module, students will be able
to demonstrate knowledge and understanding of:
• How to write and debug programs using an IDE
• The principles of designing structured programs
• When and how to use the appropriate statements available
in the C language
• Both Theoretical and Practical concept in programming using
high level programming languages.
• Use various Programming language construct available in C
• Explain the principles of structured program design
• Describe when and how to use the stand C statement
• Write, Compile and Debug basic C programs using an IDE
• Develop programs or applications to solve problems in many
areas (numerical analysis, artificial intelligence, Computer
Networks, etc)
Objectives
• Introduction,
• Writing, compiling and executing a simple C Program.
• Variables and Constants Declaration, types and
memory consumption.
• Directives in C - #define, #include.
• Simple I/O Functions - getchar, putchar, printf ,scanf
• Formatted I/O statements.
• Operators and expressions.
• Managing input/output operations .
• Decision making branching and looping. Arrays.
Handling of character strings.
• User defined functions.
Course content
6
How is university different from
school?
• Studying is your responsibility
– You are in charge of
• lecture, practical and tutorial attendance
• handing in assignments
• checking whether your marks have been
recorded.
• Lecturers are not “teachers”.
– Lecturers do teaching, research and administration.
Chapter I: Introduction
C Programming Course Overview
• What is to be taught?:
– How to program C stylishly and elegantly.
– Small and fast mathematical programs.
– Documenting code.
• Why teach programming?:
– Some maths relies on computers.
– Simulation lets us apply maths to the real world.
– It might get you a job after you finish your maths course.
– It can be fun to do.
• Learning a Programming Language
-The best way to learn is to write programs in the computer.
Some words about Computer
Programming languages
• Naturally a language is the source of
communication between two persons, and
also between person to machine like
computer.
• The languages we can use to communicate
with the computer are known as Computer
programming languages.
• Generally there are two major types of
languages are available are as follows:
• Low level languages
• The set of commands available in low level is
complex and not easy to understandable.
• In this category " Assembly " and " machine
codes " are available.
• Assembly programs are faster than other high-
level language programs.
• High level languages
• The set of commands available in high level
language is very simple and easy to
understandable.
• High level languages are further divided into
two major categories.
1. Procedure Oriented language
2. Non-Procedural Languages:
1. Procedure Oriented language
• In this category we are able to create our
project or programs using procedural
approach means in this type we can able to
divide our big project/program into small
subroutines or procedures.
• After making procedures we can able to call a
‘procedure’ one or more places.
• The lists of procedural languages are as
follows:
• C language
• C++ (Object Oriented)
• Java (Objected Oriented)
• Smalltalk (Objected Oriented)
• Pascal language
High-Level Language
• Compilers and linkers translate a high level
program into executable machine code.
#include <stdio.h>
int main()
{
printf(“Hello World”);
return 0;
}
Source code Executable code
10100110 01110110
00100110 00000000
11111010 11111010
01001110 10100110
11100110 10010110
11001110 00101110
10100110 01001110
11111010 01100110
01001110 10000110
etc...
2. Non-Procedural Languages: This category
also known as ‘Problem Oriented languages’.
• In this type of languages we can able to make
program only at specific range like database.
• The followings are the examples of Non
procedural languages
• SQL (Structured Query Language)
• SNOBOL (String processor)
Learning a C Programming Language
• The best way to learn is to write programs
• Work your way through examples from
lectures, and/or additional online tutorials
• Once you are comfortable writing simple
programs in C, take a look at Lab.
18
Algorithm:
A set of instructions describing
how to do a task (or process).
eureka!
Program: C
From Algorithms to Programs
• Both are sets of instructions on how to do a
task
• Algorithm:
– talking to humans, easy to understand
– in plain (English) language
• Program:
– talking to computer (compiler)
– can be regarded as a “formal expression” of an
algorithm
C Language History
• C is programming language developed
at AT & T’s Bell Laboratories of USA.
• First standard version release in 1972.
• It was designed and written (developed) by
Dennis Ritchie.
• Before c a Programming language is very
popular in those days the name of the language
is B-Language so the developers decided the
name of ‘C’ language because C is next to B.
• B which evolved from BCPL.
• C seems to be popular because it is reliable,
simple and ease to use compared to other
programming languages.
• It was designed for systems programming
– Operating systems
– Compilers
– Filters
Why learn C?
• C is small (only 32 keywords).
• C is common (lots of C code about).
• C is stable (the language doesn’t change much).
• C is quick running.
• C is the basis for many other languages (Java, C++,
awk, Perl).
• It may not feel like it but C is one of the easiest
languages to learn.
• Flexible language
• It allows portability
• Wide availability on a variety of computers
Some programmer jargon
• Some words that will be used a lot:
– Source code: The stuff you type into the computer. The
program you are writing.
– Compile (build): Taking source code and making a program
that the computer can understand.
– Executable: The compiled program that the computer can
run.
– Language: (Special sense) The core part of C central to
writing C code.
– Library: Added functions for C programming which are bolted
on to do certain tasks.
– Header file: Files ending in .h which are included at the start
of source code.
Rules of writing a C program
• One important feature of C is that it is a case
sensitive language.
• Lowercase and uppercase letters are distinct.
• It is advisable to follow coding conventions in
order to develop programs which are readable
and hence easily maintainable.
• Consider the following simple program which
display ‘Hello World’
More about Hello World
#include <stdio.h>
/* My first C program which prints Hello World */
int main()
{
printf ("Hello World!n");
return 0;
}
Preprocessor
Library command
main() means “start here”
Comments are good
Return 0 from main means our program
finished without errorsBrackets
define code blocks
Chapter II:
C Character, Keywords, Variables, Data
Types and Constants
Introduction
• Computers are useful because of their ability to
store and manipulate huge amounts of
information.
• This information may be numbers, such as a
financial report, or alphabetic characters like
names and addresses.
• Managing this information requires the usage of
programming languages.
• One of the important tasks of a programming
language is identifying the type of data it is
manipulating.
• Before we use a variable in C we must declare
it. We must identify what kind of information
will be stored in it.
• This is called defining a variable.
• Variables must be declared at the start of any
block of code, but most are found at the start
of each function.
C Characters
• A character denotes any alphabets,digit or
special symbol used to represent information.
• Alphabets:A,B,C,……,Y,Z
a,b,c,…….,y,z
• Digits: 0,1,2,….,9
• Special symbols:, . ! ^ & () _ <> {} ~ # ¬ etc
C constant
• A constant is an entity that doesn’t change
where a variable is an entity that may change.
• Types of Constant:
• Primary Constant (Integer, Real, Character)
• Secondary Constant(Array, Pointer,
Structure,..)
Rules for constructing integer constant
a) It must have at least one digit
b) It must not have a decimal point
c) It can be either positive or negative
d) No commas or blanks are allowed within integer
constant
e) If no sign precedes an integer constant it is
assumed to be positive.
f) The allowed range is -2147483648 to
+2147483647 but it depends on the compilers
For Turbo or Turbo C++ the range is -32768 to
32767
• Examples of Integer constant:
• 426,+782,-8000, etc
Rules for constructing Real constants
Real constants are often called floating point constant. It
can be written into two forms: Exponential form and
Fractional form
Rules for constructing Real constants expressed in
fractional form
a) It must have at least one digit
b) It must have a decimal point
c) It can be either positive or negative
d) Default sign positive.
e) No commas or blanks are allowed within integer
constant.
f) EX:+325.34,-32.76,…
• Rules for constructing Real constants
expressed in exponential form
a) The mantissa part and exponential part
should be separated by e or E.
b) Mantissa part may have a positive or
negative sign.
c) Default sign of mantissa part is positive
d) The exponent must have at least one digit
which must be a positive or negative integer.
• Ex:+3.2e-5,4.1e8,-0.2E+3,etc
Types of C variable names
• We must declare the type of every variable we use
in C.
• An entity that may vary during program execution
is called variable.
• Variable names are names given to the locations in
memory.
• Variable name holds value.
• Every variable has a type (e.g. int) and a name.
• For example, Integer variable can hold only integer
constant and character variable can hold only
character constant.
• Examples:
• Common variable types are int, double,char
and float.
• Other types are signed, unsigned, long, short
and const.
Rules for constructing variable names
• A variable name is any combinations of 1 to 31
alphabets, digits or underscore.Some compilers
accepts variable name whose length could be up to
247 characters but don’t create unnecessarily long
variable names as it adds to your typing effort.
• The first character in the variable name must be an
alphabets or undescore
• No commas or blanks are allowed within a variable
name.
• No special symbol other than underscore can be
used in a variable name ( gross_sal, net_sal, etc)
• A good name for your variables is important.
• Following are the examples of type declaration
statements:
• Ideally, a comment with each variable name helps
people know what they do but not necessary.
int a,b;
double d;
/* This is
a bit cryptic */
int start_time;
int no_students;
double course_mark;
/* This is a bit better
*/
Keywords of C
• Keyword: are the words whose meaning has
already been explained to the C compiler.
• They cannot be used as variable names
because if we do so, we are trying to assign a
new meaning to the keyword which is not
allowed by computer.
• They are 32 keywords as follows:
• Flow control (6) – if, else, return, switch,
case, default
• Loops (5) – for, do, while, break,
continue
• Common types (5) – int, float, double,
char, void
• structures (3) – struct, typedef, union
• Counting and sizing things (2) – enum, sizeof
• Rare but still useful types (7) – extern, signed,
unsigned, long, short, static, const
• Evil keywords which we avoid (1) – goto
• Wierdies (3) – auto, register, volatile
Data types
• C provides a number of data types, some of
the basic types used are:
• There are variants to the above, such as
int integer
char character
float a floating point number
unsigned int unsigned integer
short int short integer
long int long integer
double double precision floating point number
• When declaring variables to be of type long
int, short int and unsigned int it is permissible
to omit the keyword int.
• The main difference among these data types is
the amount of memory allocated for storing
these.
• The maximum and minimum values that can
be stored in these variables depend on the
version of C and the computer system being
used.
Data Type Maximum Minimum Bytes
int 32767 -32768 2
unsigned int 65535 0 2
short 32767 -32768 2
long 2147483647 -2147483648 4
char (ASCII
codes)
127 -128 1
unsigned char 255 0 1
float 3.4E+38 3.4E-38 4
double 1.7E+308 1.7E-308 8
Formatted Input and Output
• Formatted output statement is nothing but the
most commonly used printf() function.
• This function consists of a literal string or value
of a variable which has to be displayed on the
standard terminal and a format specifier which
specifies how it has to display.
• Consider some of the following printf ()
statements:
• printf("Hello n");
• printf("Your salary is t %f n", sal);
• Some of the commonly used format specifiers are
mentioned below:
• %d int: Integer
• %ld long int: long integer
• %c char :single character
• %s string: Null terminated strings
• %f float or double
• %e same as %f but exponential notation is used
• %g use %f or %e
• %x hexadecimal value (base 16)
• %o Octal value (base 8)
• scanf() is used for reading formatted data from
the keyboard.
• Similar to printf () it requires a format specifier,
followed by the list of items to be read.
• One important point to remember here
is, scanf() requires the address of the items to
be read.
CHAPTER III:
Operators and Expressions in C
language
Introduction
• C has a wide range of operators.
• Expressions Combine values using operators
and function calls
• Expressions return a value of a known type
Arithmetic Expressions
• An arithmetic expression is composed of operators
and operands. Operators act on operands to yield a
result.
• Commonly used arithmetic operators are +, -, *, /
and %.
• The plus sign (+) is used to add two values, the
minus sign (-) to subtract one value from another,
the asterisk(*) to multiply two values, the division
(/) to divide a value and the modulus (%) to obtain
the reminder of integer division.
• These are known as binary operators since they
operate on two values or variables.
• It take arithmetic (numerical) values and
return an arithmetic (numerical) value
• Are composed using the following operators:
+ (unary plus)
- (unary minus)
+ (addition)
- (subtraction)
* (multiplication)
/ (division or quotient)
% (modulus or remainder)
Precedence in Expressions
• Defines the order in which an expression is
evaluated.
Example1
1 + 2 * 3 - 4 / 5 =
B stands for brackets,
O for Order (exponents),
D for division,
M for multiplication,
A for addition, and
S for subtraction.
B.O.D.M.A.S.
1 + (2 * 3) - (4 / 5)
More on precedence
• *, /, % are at the same level of precedence
• +, - are at the same level of precedence
• For operators at the same “level”, left-to-right
ordering is applied.
2 + 3 – 1 = (2 + 3) – 1 = 4
2 – 3 + 1 = (2 – 3) + 1 = 0
2 * 3 / 4 = (2 * 3) / 4 = 6 / 4
2 / 3 * 4 = (2 / 3) * 4 = 0 * 4
Precedence in Expressions – Example
(cont)
6.2
1 + 2 * 3 - 4 / 5 =
1 + (2 * 3) - (4 / 5)
Precedence in Expressions –Example
(cont)
6.2
1 + 2 * 3 - 4 / 5 =
1 + (2 * 3) - (4 / 5)
Precedence in Expressions –
Example (cont)
Integer division
results in integer
quotient
1 + 2 * 3 - 4 / 5 =
1 + (2 * 3) - (4 / 5)
Precedence in Expressions –
Example (cont)
= 0
D’oh
1 + 2 * 3 - 4 / 5 =
1 + (2 * 3) - (4 / 5)
Precedence in Expressions – Example
(cont)
7
1 + 2 * 3 - 4 / 5 =
1 + (2 * 3) - (4 / 5)
int-s and float-s
• float is a “communicable” type
• Example:
1 + 2 * 3 - 4.0 / 5
= 1 + (2 * 3) - (4.0 / 5)
= 1 + 6 - 0.8
= 6.2
int-s and float-s – Example 2
(1 + 2) * (3 - 4) / 5
= ((1 + 2) * (3 - 4)) / 5
= (3 * -1) / 5
= -3 / 5
= 0
int-s and float-s – Example 2
(cont)
(1 + 2.0) * (3 - 4) / 5
= ((1 + 2.0) * (3 - 4)) / 5
= (3.0 * -1) / 5
= -3.0 / 5
= -0.6
int-s and float-s – Example 3
(1 + 2.0) * ((3 - 4) / 5)
= (1 + 2.0) * (-1 / 5)
= 3.0 * 0
= 0.0
Unary operators
• A unary operator is one which operates on one value
or operand.
• The minus sign (-) plays a dual role, it is used for
subtraction as a binary operator and for negation as
a unary operator.
• This operator has a precedence higher than the rest
of the arithmetic operators.
• Example
i = +1; /* + used as a unary operator */
j = -i; /* - used as a unary operator */
• The unary + operator does nothing – just
emphasis that a numeric constant is positive.
• The unary – operator produces the negative of
its operand.
• Example: result = -x * y;
• In the above expression, if x has a value 20
and y has a value 2, then result will contain a
negative value of 40 which is -40.
Ternary operator
• In C the ternary operator is the conditional
expression operator.
• This accepts three operands.
• Question mark (?) and colon (:) are the two
symbols used.
• The format of the ternary operator is:
• expression1 ? expression2 : expression3
• Where expression1 is an expression evaluated
to true of false.
• If expression 1 is true, expression 2 is executed
• If expression 1 is false, expression 3 is executed
• Example:
• Max=(a>b)? a: b //compute maximum of a
and b.
• Let a=10 and b=20 10>20?false Max=20
• Let a=30 and b=10 30>10? True Max=30
Increment and decrement operators
• ++ is the increment operator
i++;
is equivalent to
i = i + 1;
• -- is the decrement operator
j--;
is equivalent to
j = j - 1;
A short note about ++
• ++i means increment i then use it
• i++ means use i then increment it
int i= 6;
printf ("%dn",i++); /* Prints 6 sets i to 7 */
int i= 6;
printf ("%dn",++i); /* prints 7 and sets i to 7 */
Note this important difference
It is easy to confuse yourself and others with the difference
between ++i and i++ - it is best to use them only in simple ways.
• Example: Let a=20
• Post increment
b=a++ current value of a is used b=a b=20
a is incremented by 1 a=a+1 a=21
• Pre increment
b=++a a is incremented by 1 a=a+1 a=21
incremented value of a b=a b=21
is used
• Example: Let a=10
• Post decrement
b=a-- current value of a is used b=a b=10
a is incremented by 1 a=a-1 a=9
• Pre increment
b=--a a is incremented by 1 a=a-1 a=9
incremented value of a b=a b=9
is used
Relational operator
• In real world we may have to compare two
quantities which results in either true/false or
yes/no output. In such situation we use
relational operators.
• EX1: is my score greater than 90?
• EX2: is my weight less than 68 kg?
• Relational operators are operators that are
used to find the relationship between two
operands.
• Note: Output of relational expression is true
denoted by 1 or false denoted by 0.
Description Operator
Less than <
Lesser/equal <=
Greater >
Greater/equal >=
Equal ==
Not Equal !=
Note that == is used in comparisons
and = is used in assignments. Comparison operators are used in expressions
like the ones below
• x == y valid
• i > 10 valid
• a + b != c valid
• a=<b invalid operators are not in order
• a< =b invalid there is space between < and =
3>2 1
2>3 0
2>=2 1
3+2<6 1
• Precedence of operators:
• Evaluate the expression within parentheses
• Evaluate unary operator
• Evaluate arithmetic expression
• Evaluate relational expression
EX: Evaluate the following expression
100/20<=10-5+100%10-20==5>=1!=20
Logical operators
• Logical operators in C are as per table
&&
Logical AND(Binary
operator)
||
Logical OR(Binary
operator)
! Unary NOT
They are frequently used to combine relational operators,
For example : x < 20 && x >= 10
• Logical operators use true or false properties
of expressions to return a true or false.
• True is represented by a non-zero value and
false by zero.
•
• Consider the following expression:
• result = q1 && q2; /* result is true if both q1
and q2 are non-zero */
(1&&1=1,1&&0=0,0&&1=0 and 0&&0=0 )
• result = q1 || q2; /* result is true if either q1
or q2 is non-zero */
(1 || 1=1, 1 || 0 = 1, 0 || 1=1 and 0 || 0=0)
• result = !q1; /* result is true only if q1 is zero
*/
(!0=1 and !=1=0)
• Precedence of operators:
• Evaluate the expression within parentheses
• Evaluate unary operator
• Evaluate arithmetic expression
• Evaluate relational expression
• Evaluate logical expression
EX: Evaluate the expression a+2 > b && !c || a
!=d && a-2 <=e where a=11,b=6, c=0, d=7 and
e=5
Assignment operator
• It is an operator which is used to assign the data
or result of an expression into a variable.
• Assignment operator symbol is “ = “
• Types of assignment operator:
1. Simple assignment statement Ex: a=a+10;
2. Shorthand assignment statement Ex: a+=10;
3. Multiple assignment statement Ex: a=b=10;
• Example: pi= 3.14(The value 3.14 is copied into
variable pi)
• The following table shows shorthand
assignment statement:
Shorthand statement Meaning Explanation
a+=2 a=a+2 Evaluate a+2 and
store the result in a
a-=2 a=a-2 Evaluate a-2 and store
the result in a
a*=2 a=a*2 Evaluate a*2 and
store the result in a
a/=2 a=a/2 Evaluate a/2 and
store the result in a
Comma operator
• Comma can be used in an expression.
• Comma operator is denoted ‘,’
• Comma is used in variable declaration like
int a,b,c Here comma isnot used as operator.
• Comma operator acts on two operands and
normally is used to:
• Separate items in the list Ex: a=12,345,678;
• Combine two or more statements into single
statement EX: a=10,b=20,c=30;
• Comma expression is evaluated from left to
right.
• Evaluate the following expression:
• Example 1: a=12,345,678;
• There are two operators: assignment and
comma operators,since assignment has
highest precedence over comma operator
,integer 12 is copied into variable a and other
integers 345 and 678 are discarded
• The answer is : a=12 the remaining values 345
and 678 are discarded.
• Example 2:Evaluate the following comma
expression a=5+5, 6*5;
• Solution:
• a=5+5,6*5
• a=5+5 then 6*5 is discarded
• a=5+5=10
Note: All Expression after first comma are
discarded.
CHAPTER IV:
Control of Flow Instructions
Topic
• Decision control structure
• Loop control structure
• Case control structure
Decision control structure
• Many times we want the instruction to be
executed In one situation and an entirely
different set of instruction to be executed in
another situation.
• This kind of situation is dealt with in C
programs using decision control instruction.
The if statement
• Decides what to do by evaluating a Boolean
expression.
• If the expression is true (non-zero), the
statement or block is executed.
• The general form is:
if ( expression )
{
statement
}
Program1
/* Read in a number, and check if it is odd. */
#include <stdio.h>
#include <conio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number % 2 != 0)
{
printf("%dn", number);
}
getch();
return 0;
}
Program2
/*Program to find the largest of 2 numbers*/
#include <stdio.h>
#include <conio.h>
int main()
{
int a,b;
printf(“Enter two numbers:”);
scanf(“%d %d”,&a,&b);
if(a>b)
{
printf(“%d is largest ”,a);
}
If(a<b)
{
printf(“%d is largest ”,b);
}
• Other Program to write:
• Program to find roots of quadratic equation.
If else
• Another variation of an if statement is an if
else statement.
• This statement helps a programmer to
evaluate a condition and take two different
actions depending on whether it results a
result of TRUE or FALSE.
• Can only occur after an if statement
• Is only executed when the if block does not
execute
• General form:
if ( expression )
{
statement1
}
else
{
statement2
}
/* Determine whether an input number
is odd or even. */
#include<stdio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number % 2 != 0)
{
printf("%d is an odd numbern",
number);
}
else
{
printf("%d is an even numbern",
number);
}
}
Cascaded if statement
if (expression1)
{
statements;
}
else if (expression2)
{
statements;
}
else
{
statements; <………Default block
}
/*Program to calculate percentage of marks*/
#include<stdio.h>
int main()
{
int m1,m2,m3,m4,m5,per;
printf(“Enter five marks /100 each:”);
scanf(“%d %d %d %d %d”,&m1,&m2,&m3,&m4);
per=((m1+m2+m3+m4+m5)*100)/500;
if(per>=60)
printf(“First Divisionn”);
else if(per>=50)
printf(“Second Divisionn”);
else if(per>=40)
printf(“Third Division”);
else
printf(“Fail”n);
return 0;
}
Loop control
• Before we proceed to the statements that
change the flow of execution we need to
understand how code is repetitively executed.
This is known as executing a loop.
• Each execution of a loop is known as
iteration.
• C language has three different program
statements for program looping.
• They are
• for statement,
• while statement and
• do while statement.
for loop
• For statement
• The general format of a for statement is:
for ( expression1; loop_condition; expression2)
{
program statements;
}
• The first component of the for statement,
expression1 is used to set the initial values
before an iteration begins.
• The second component which is loop
condition specifies the condition(s) that has
(have) to be met for the loop to continue.
• The final component expression2 specifies the
expression that is executed each time after
the body of loop is executed.
#include <stdio.h>
int main()
{
int x;
/* The loop goes while x < 10, and x increases by one every loop*/
for ( x = 0; x < 10; x++ )
{
/* Keep in mind that the loop condition checks the conditional statement
before it loops again. consequently, when x equals 10 the loop breaks. x is
updated before the condition is checked. */
printf( "%dn", x );
}
getch();
return 0;
}
Nested for
/*A C program to display Hello World 5 times*/
#include<stdio.h>
int main()
{
int i, n=5;
for(i=0;i<n;i++)
{
printf(“Hello World!”);
}
return 0;
}
/*A C program to Print an –4 by-2 rectangle of asterisks. */
#include<stdio.h>
int main()
{
int i, j, m=4, n=2;
for (i=0; i < n; i++)
{
for (j=0; j < m; j++)
{
printf("*");
}
printf("n");
}
return 0;
}
while
• The syntax of the while statement is
while (expression)
{
program statements;
}
• The expression specified inside the parentheses is
evaluated, if the result of the expression is true then
the program statements inside the loop is executed.
• After one iteration the expression is evaluated again
and the loop is executed depending on whether the
result is true. If the result is false, then the loop is
terminated and the program execution continues with
the statements following the while loop.
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int i=0,n=4;
clrscr();
while(i<n)
{
printf("n Hello world!");
i++;
}
getch();
return 0;
}
• do
{
program statements(do this);
}
while (expression1);
• Here the program statements are first executed
once, then the expression1 is evaluated.
• If it is true, then it proceeds to the next iteration.
This continues till the expression1 evaluates to
false.
#include<stdio.h>
#include<conio.h>
int main()
{
int i=0,n=4;
clrscr();
do
{
printf("nHello world!");
i++;
}
while(i<n);
getch();
return 0;
}
Break statement
• Format of this statement is:
break;
• Sometimes it becomes necessary to terminate a loop
depending on a condition.
• In such circumstance, a break statement can be used.
• This causes the program to exit the loop and execution
continues with the statements following the loop.
• In case of a nested loop, only the loop in which the
break statement occurs is terminated.
• A break statement takes the execution control out of
loop.
Break Example
#include<conio.h>
#include<stdio.h>
void main()
{
int i;
clrscr();
for(i=1;i<10;i++)
{
printf("nnThis is the ROUND No: %d",i);
if(i==5) break;
printf(" Let me start the ROUND No: %d n",i+1);
}
printf("This is the ROUND No: %d",i);
getch();
}
Continue statement
• Format of this statement is
continue;
• Unlike a break statement, this causes the loop in
which it occurs to continue.
• All the statements following the continue statement
are ignored.
• This is used to bypass a group of statements in a loop
based upon certain criteria or conditions.
Continue example
#include<conio.h>
#include<stdio.h>
void main()
{
int i;
clrscr();
for(i=1;i<10;i++)
{
printf("nnThis is the ROUND No: %d",i);
if(i==5) continue;
printf(" Let me start the ROUND No: %d n",i+1);
}
printf("This is the ROUND No: %d",i);
getch();
}
switch case statement
Syntax of switch case:
switch (expression1)
{
case val1 :
program statements;
break;
case val2 :
program statements;
break;
…
default :
program statements;
break;
}
• The expression1 is repeatedly compared against
values val1, val2 and so on till a match is found.
• Then the corresponding program statements are
executed.
• Every set of statements needs a break statement
otherwise the program execution will continue
into the next case statement that satisfies the
expression.
• There is a special default statement at the end
which gets executed when the value of
expression1 does not match any of the case
values
Example 1
#include<conio.h>
#include<stdio.h>
void main()
{
int i=2;
clrscr();
switch(i)
{
case 1:
printf(“I am in case 1n");
break;
case 2:
printf(“I am in case 2n");
break;
case 3:
printf(“I am in case 3n");
default:
printf(“I am in defaultn");
}
getch();
}
• Example 2: Write a c program which simulate
calculator of 5 arithmetic operations (+,-,*,/
and %) using switch case
• Example 3: Write a c program to display days
of week using switch case.
CHAPTER V:
Function
What is a function?
• The function is one of the most basic things to
understand in C programming.
• A large program can be divided into manageable
pieces called modules where each module does a
specific task. Thus the function often called modules
are self contained small programs(called program
segments) that carry out some specific, well defined
tasks.
• A function is a sub-unit of a program which performs a
specific task.
• We have already seen one function from the C library
printf(),scanf(),getch(),clrscr(),etc
.
• We need to learn to write our own functions.
• Functions take arguments (variables) and
may return an argument.
• Think of a function as extending the C
language to a new task.
• NOUNS functions are VERBS.
• The function can be classified into two
categories as shown below:
1. Library functions/predefined functions.
2. User defined Functions(UDFs).
Why functions
• The program that we study are very small when
compared to the program that we write for a complex
in real word.
• If the program is very there are too many
disadvantages:
• It is very difficult for the programmer to write a large
program
• Very difficult to identify logical errors and correct
errors in a large program
• Very difficult to read and understand a large problem
• Large programs are more prone to errors and so on.
Library name Example functions Header files
Standard
input/output library
printf():is used to
display/print data on
the screen
scanf():used to read
data from the
keyboard,etc…
stdio.h
Math library pow(x,y):compute xy
sqrt(x):compute
square root of x,etc….
math.h
Character library isalpha(),
tolower(),toupper(),et
c…
ctype.h
String library Strcpy(),stlen(),
strcmp(),etc…
string.h
Time clock(),time(),etc.. time.h
Library functions/predefined functions
User defined functions
• Using only library functions, it is not possible to
write a program to achieve some specific tasks.
• In such case, the programmer need to write their
own functions to achieve the required tasks.
• The functions which are written by the
programmer/user to do some specific tasks are
called User defined functions.
• Suppose we want to compute square of number. And the
function library to do this task is not available then the
function square() can be defined by user to return square
of number.
What are these prototype things?
• A prototype tells your C program what to
expect from a function - what arguments it
takes (if any) and what it returns (if any)
• Prototypes should go before main()
• #include finds the prototypes for library
functions (e.g. printf)
• A function MUST return the variable type we
say that it does in the prototype.
#include<stdio.h>
#include<conio.h>
void italy();
void rwanda(); Function prototype
void usa();
int main()
{
printf("I am in main functionn");
italy();
rwanda(); Function call
usa();
getch();
return 0;
}
void italy()
{
printf("I am in Italyn");
}
void rwanda()
{
printf("I am in Rwandan");
}
void usa()
{
printf("I am in USAn");
}
What is scope?
• The scope of a variable is where it can be used in
a program
• Normally variables are local in scope - this means
they can only be used in the function where they
are declared (main is a function)
• We can also declare global variables.
• If we declare a variable outside a function it can
be used in any function under where it is declared
• Global variables are A BAD THING
The print stars example
#include <stdio.h>
void print_stars(int);
void main()
{
int i;
for (i= 0; i < 5; i++)
print_stars(5);
}
void print_stars (int n)
{
int i;
for (i= 0; i < n; i++)
printf ("*");
printf ("n");
}
This program prints five rows of
five stars
This prints 'n' stars and then
a new line character
Loop around 5 times to
print the stars
*****
*****
*****
*****
*****
Variables here are LOCAL variables
#include<stdio.h>
#include<conio.h>
int calcsum(int x,int y,int z);/*Function prototype*/
int main()
{
int a,b,c,sum;
printf("Enter 3 numbers:");
scanf("%d %d %d",&a,&b,&c);
sum=calcsum (a,b,c); /*Function call*/
printf("sum of (%d %d %d)=%dn",a,b,c,sum);
getch();
return 0;
}
int calcsum(int x,int y,int z)/*Function definition*/
{
int d;
d=x+y+z; /*definition*/
return d;
}
• There are somethings to know about this
program:
1. From the main function values of a,b,c are
passed on to the function calcsum(), by
making a call to the function calcsum() and
mentioning a,b,c and d in the parantheses.
calcsum(a,b,c);
• In the calcsum() function these values get
collected in three variables s,y and z.
• calcsum(x,y,z)
2. The variables a,b and c are called ‘actual
argument’, where as the variables x,y and z are
called ‘formal arguments’. Any number can be
passed to the function being called.
The type, order and number of the actual and
formal arguments must be the same.
3. Function Prototype declaration of calcsum() is
int. This indicates our function return a value of
type int.( int calcsum(int, int, int) )
CHAP. VI:
Arrays
• Array is a data structure that represents a
collection of the same types of
data(element(s)).
• We have one dimensional array &
multidimensional array.
Declaring Array Variables
• datatype arrayRefVariable[];
Example:
int A[10];
Indexed Variables
• The array elements are accessed through the index.
• The array indices are 0-based, i.e., it starts from 0 to
arrayRefVariable.length-1.
• In the example, the array A holds ten integer values
and the indices are from 0 to 9.
• Each element in the array is represented using the
following syntax, known as an indexed variable:
arrayRefVariable[index];
Using Indexed Variables
• After an array is created, an indexed variable
can be used in the same way as a regular
variable.
• For example, the following code adds the
value in A[0] and A[1] to A[2].
A[2] = A[0] + A[1];
Array Initializers
• Declaring, creating, initializing in one step:
int A[10]= {1,9, 2,7,3,5,11,0,-5,11};
This shorthand syntax must be in one statement.
Declaring, creating, initializing Using the Shorthand
Notation
int A[10]= {1,9, 2,7,3,5,11,0,-5,11};
This shorthand notation is equivalent to the following statements:
int A[10];
A[0] = 1;
A[1] = 9;
A[2] = 2;
A[3] = 7;
A[4] = 3;
A[5] = 5;
A[6] = 11;
A[7] = 0;
A[8] = -5;
A[9] = 11;
140
• Using the shorthand notation, you have to
declare, create, and initialize the array all in one
statement.
• Splitting it would cause a syntax error.
• For example, the following is wrong:
int A[10];
A = {1,9, 2,7,3,5,11,0,-5,11};
A C program to initialize an array
#include<conio.h>
#include<stdio.h>
void main()
{
/*declaration*/
int A[10], i;
clrscr();
/*initialization an array using for loop*/
for(i=0;i<10;i++)
{
printf("Enter the number");
scanf("%d“, &A[i]);
}
A C program to initialize an array(cont)
/*Displaying an array using for loop*/
printf("The array is : ");
for(i=0;i<10;i++)
{
printf("%d”, A[i]); /*Elements displayed*/
}
getch();
}
Two-dimensional Arrays
• Thus far, you have used one-dimensional arrays to
model linear collections of elements.
• You can use a two-dimensional array to represent a
matrix or a table.
• For example, the following table that describes the
distances between the cities can be represented
using a two-dimensional array.
Two-dimensional Arrays
Distance table(in km)
145
Declaring Variables of Two-dimensional
Arrays and Creating Two-dimensional
Arrays
// Declaration of two-dimensional array syntax:
dataType arrayrefVar[size][size];
array name
Example:
int matrix[3][3];
146
Two-dimensional Array Illustration
147
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use an array initializer to declare, create and
initialize a two-dimensional array. For example,
int matrix [4][3] ;
matrix[0][0] = 1; matrix[0][1] = 2; matrix0][2] = 3;
matrix[1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6;
matrix[2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9;
matrix[3][0] = 10; matrix3][1] = 11; matrix[3][2] = 12;
int matrix[4][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
Same as
#include<conio.h>
#include<stdio.h>
void main()
{ //declaration
int matrix[3][3] ;
int i,j;
clrscr(); // initialization
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
printf("Enter the %d Number",j+1);
scanf("%d",&matrix[i][j]);
//displaying an array
printf("The matrix is: ");
for(i=0;i<3;i++)
{
printf("nn ");
for(j=0;j<3;j++)
{
printf("%d ",matrix[i][j]);
}
}
getch();
}
Chapter VII:
String
• In C language, the group of character, digits and
other symbols enclosed within quotation marks are
called as string.
• The string is always declared as character arrays. In
other words, character arrays are called strings.
• To manipulate text such as words and sentences
normally strings are used.
• Every string is terminated with ‘0’ (NULL) character;
the decimal value of NULL character is zero.
• Example:
char name[6]={‘H’,’E’,’L’,’L’,’O’,’0’};
• Each character of string occupies 1 byte of
memory.
• The last character is always ‘0’.
• It is not compulsory to write ‘0’ in string.
• The compiler automatically puts ‘0’ at the
end of the character array or string.
• The characters of string are stored in
contiguous (neighbouring) memory locations.
Declaration and Initialization of String
• char name [6] =”Hello”;//using double quotes
• char name[6]={‘H’,’e’,’l’,’l’,’o’,’0’};//using single quote
• The c compiler inserts the NULL (0) character
automatically at the end of the string. So the
initialization of NULL character is not essential.
• char name[6]={’U’,’N’,’I’,’V’,’E’,’R’} //An error.
The output will not be ‘UNIVER’ but UNIVER with
some garbage value as the NULL character has not
been initialized.
Display of strings with different formats
• String header file is : #include <string.h>
• The printf() function is used for displaying the various data
types.
• The printf() function with %s format is to be used for
displaying the string on the screen.
• scanf() is replaced by gets() to read the string from the
keyboard.
• strlen() function.
This function counts the number of characters in a given string.
The format of function is strlen(string).
• strrev() function
• This function is used to find reverse of a string.
• Example:
• Write a c program to read a text through the keyboard.
Determine the length of the string and its reverse
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char x[10];
int len;
clrscr();
printf("Enter any string to check:n");
gets(x);
len=strlen(x);
printf("lenght of %s is %dn",x,len);
printf("reverse of %s is %sn",x,strrev(x));
getch();
return 0;
}
• stricmp() function.
• This function compares two strings without considering lower
case or upper case.
• It returns zero when two strings are same otherwise it returns
non-zero value.
Exercise: Write a program to compare two strings
• strlwr() function
• This function can be used to convert any string to a lower case.
When you are passing any upper case string to this function, it is
converted into lower case.
The format of function is strlwr(string).
Exercise: Write a program to convert upper case string to lower
case using strlwr()
• strupr() function
• This function is the same as strlwr() but the difference is that
strupr() converts lower case strings to upper case.
• The format of function is strupr(string).
Exercise: Write a c program to convert your full name in lower
case string to upper case using strupr()
Exercise: Write a program to know whether the entered character
string is palindrome or not. (Palindrome word reads same from
left to right & right to left).
• strcat(): This function is used to concatenate two strings
• The format is strcat (target, source)
#include<stdio.h>
#include<string.h>
#include<conio.h>
main()
{
char fname[10];/*Source string*/
char sname[10];/*target string*/
printf("Enter fname");
gets(fname);
printf("Enter sname");
gets(sname);
clrscr();
strcat(sname,fname);
printf("Fullname is %sn",sname);
getch();
return 0;
}
References
• Core texts
• Brian W.Kernighan and Dennis M.Ritchie,[1988] The C programming
Language, Second edition, Prentice Hall.
• Clovis L. Tondo and Scotte E. Gimpel,[ 1989] The C Answer book
,Second edition, Prentice Hall.
• Ritchie, M. Dennis, [2000]The C programming language, 005.33 KER
2000
• Background Texts
• (Hervey and Paul) Deitel and Associates, [2007] C how to program,
Fifth edition, Prentice Hall.
• Ritchie, M. Dennis,[2000] The C programming Language.
• Uckan, Yuksel,[1999] Problem solving using C: Structured
programming Techniques

More Related Content

What's hot

Chapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to ProgrammingChapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to Programmingmshellman
 
Generations Of Programming Languages
Generations Of Programming LanguagesGenerations Of Programming Languages
Generations Of Programming Languagespy7rjs
 
Lect 1. introduction to programming languages
Lect 1. introduction to programming languagesLect 1. introduction to programming languages
Lect 1. introduction to programming languagesVarun Garg
 
Programming languages
Programming languagesProgramming languages
Programming languagesvito_carleone
 
software development and programming languages
software development and programming languages software development and programming languages
software development and programming languages PraShant Kumar
 
Program & language generation
Program & language generationProgram & language generation
Program & language generationBuxoo Abdullah
 
C presentation book
C presentation bookC presentation book
C presentation bookkrunal1210
 
best notes in c language
best notes in c languagebest notes in c language
best notes in c languageIndia
 
What is token c programming
What is token c programmingWhat is token c programming
What is token c programmingRumman Ansari
 
History of C Programming Language
History of C Programming LanguageHistory of C Programming Language
History of C Programming LanguageNiloy Biswas
 

What's hot (20)

C language
C languageC language
C language
 
Chapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to ProgrammingChapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to Programming
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c language
 
Generations Of Programming Languages
Generations Of Programming LanguagesGenerations Of Programming Languages
Generations Of Programming Languages
 
Lect 1. introduction to programming languages
Lect 1. introduction to programming languagesLect 1. introduction to programming languages
Lect 1. introduction to programming languages
 
Programming languages
Programming languagesProgramming languages
Programming languages
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Programming : QBASIC
Programming : QBASICProgramming : QBASIC
Programming : QBASIC
 
software development and programming languages
software development and programming languages software development and programming languages
software development and programming languages
 
Program & language generation
Program & language generationProgram & language generation
Program & language generation
 
Computer Quiz MCQ's
Computer Quiz MCQ'sComputer Quiz MCQ's
Computer Quiz MCQ's
 
C AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDYC AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDY
 
C presentation book
C presentation bookC presentation book
C presentation book
 
best notes in c language
best notes in c languagebest notes in c language
best notes in c language
 
What is token c programming
What is token c programmingWhat is token c programming
What is token c programming
 
History of C Programming Language
History of C Programming LanguageHistory of C Programming Language
History of C Programming Language
 
Lecture 1- History of C Programming
Lecture 1- History of C Programming Lecture 1- History of C Programming
Lecture 1- History of C Programming
 
C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
 
Programming in c notes
Programming in c notesProgramming in c notes
Programming in c notes
 
Programming languages
Programming languagesProgramming languages
Programming languages
 

Viewers also liked (11)

Resume 2016 (1)
Resume 2016 (1)Resume 2016 (1)
Resume 2016 (1)
 
bbbbb Joseph Gregory Resume
bbbbb Joseph Gregory Resume bbbbb Joseph Gregory Resume
bbbbb Joseph Gregory Resume
 
Jonathon Hoefer Resume
Jonathon Hoefer ResumeJonathon Hoefer Resume
Jonathon Hoefer Resume
 
Baker's presentation converted to ppt from google doc
Baker's presentation converted to ppt from google docBaker's presentation converted to ppt from google doc
Baker's presentation converted to ppt from google doc
 
rollup-2013_final_1
rollup-2013_final_1rollup-2013_final_1
rollup-2013_final_1
 
Cine venezolano2013
Cine venezolano2013Cine venezolano2013
Cine venezolano2013
 
Drivers of Consumer Choice
Drivers of Consumer ChoiceDrivers of Consumer Choice
Drivers of Consumer Choice
 
Macau Food Safety
Macau Food SafetyMacau Food Safety
Macau Food Safety
 
Chapter 8: Front Office Accounting
Chapter 8: Front Office AccountingChapter 8: Front Office Accounting
Chapter 8: Front Office Accounting
 
Computacion
ComputacionComputacion
Computacion
 
Jonnie Williams Director Resume
Jonnie Williams Director ResumeJonnie Williams Director Resume
Jonnie Williams Director Resume
 

Similar to C_Programming_Notes_ICE

Similar to C_Programming_Notes_ICE (20)

C language unit-1
C language unit-1C language unit-1
C language unit-1
 
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDYC LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Chapter 1: Introduction
Chapter 1: IntroductionChapter 1: Introduction
Chapter 1: Introduction
 
Programing fundamentals with C++
Programing fundamentals with C++Programing fundamentals with C++
Programing fundamentals with C++
 
Unit-1 (introduction to c language).pptx
Unit-1 (introduction to c language).pptxUnit-1 (introduction to c language).pptx
Unit-1 (introduction to c language).pptx
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Introduction to programming c
Introduction to programming cIntroduction to programming c
Introduction to programming c
 
c++
 c++  c++
c++
 
Lesson 1
Lesson 1Lesson 1
Lesson 1
 
Introduct To C Language Programming
Introduct To C Language ProgrammingIntroduct To C Language Programming
Introduct To C Language Programming
 
c-introduction.pptx
c-introduction.pptxc-introduction.pptx
c-introduction.pptx
 
Compilers.pptx
Compilers.pptxCompilers.pptx
Compilers.pptx
 
C Language
C LanguageC Language
C Language
 
Basics of C Prog Lang.pdf
Basics of C Prog Lang.pdfBasics of C Prog Lang.pdf
Basics of C Prog Lang.pdf
 
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTREC & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
 
C.pdf
C.pdfC.pdf
C.pdf
 

C_Programming_Notes_ICE

  • 1. CSC103: Programming in C Language Prepared by: NZABONITEGEKA Gilbert(MSc.)
  • 2. Module description • 15 credits module (100hours) • 50hours (Face to face/ contact hours) • Theoretical Part and • Practical part • 50 hours (self guided study+ Reading+ Examination)
  • 3. Examination process • CAT : Continuous Assessment Test /60 marks, • Final Exam / 40 marks
  • 4. Having successfully completed the module, students will be able to demonstrate knowledge and understanding of: • How to write and debug programs using an IDE • The principles of designing structured programs • When and how to use the appropriate statements available in the C language • Both Theoretical and Practical concept in programming using high level programming languages. • Use various Programming language construct available in C • Explain the principles of structured program design • Describe when and how to use the stand C statement • Write, Compile and Debug basic C programs using an IDE • Develop programs or applications to solve problems in many areas (numerical analysis, artificial intelligence, Computer Networks, etc) Objectives
  • 5. • Introduction, • Writing, compiling and executing a simple C Program. • Variables and Constants Declaration, types and memory consumption. • Directives in C - #define, #include. • Simple I/O Functions - getchar, putchar, printf ,scanf • Formatted I/O statements. • Operators and expressions. • Managing input/output operations . • Decision making branching and looping. Arrays. Handling of character strings. • User defined functions. Course content
  • 6. 6 How is university different from school? • Studying is your responsibility – You are in charge of • lecture, practical and tutorial attendance • handing in assignments • checking whether your marks have been recorded. • Lecturers are not “teachers”. – Lecturers do teaching, research and administration.
  • 8. C Programming Course Overview • What is to be taught?: – How to program C stylishly and elegantly. – Small and fast mathematical programs. – Documenting code. • Why teach programming?: – Some maths relies on computers. – Simulation lets us apply maths to the real world. – It might get you a job after you finish your maths course. – It can be fun to do. • Learning a Programming Language -The best way to learn is to write programs in the computer.
  • 9. Some words about Computer Programming languages • Naturally a language is the source of communication between two persons, and also between person to machine like computer. • The languages we can use to communicate with the computer are known as Computer programming languages. • Generally there are two major types of languages are available are as follows:
  • 10. • Low level languages • The set of commands available in low level is complex and not easy to understandable. • In this category " Assembly " and " machine codes " are available. • Assembly programs are faster than other high- level language programs.
  • 11. • High level languages • The set of commands available in high level language is very simple and easy to understandable. • High level languages are further divided into two major categories. 1. Procedure Oriented language 2. Non-Procedural Languages:
  • 12. 1. Procedure Oriented language • In this category we are able to create our project or programs using procedural approach means in this type we can able to divide our big project/program into small subroutines or procedures. • After making procedures we can able to call a ‘procedure’ one or more places.
  • 13. • The lists of procedural languages are as follows: • C language • C++ (Object Oriented) • Java (Objected Oriented) • Smalltalk (Objected Oriented) • Pascal language
  • 14. High-Level Language • Compilers and linkers translate a high level program into executable machine code. #include <stdio.h> int main() { printf(“Hello World”); return 0; } Source code Executable code 10100110 01110110 00100110 00000000 11111010 11111010 01001110 10100110 11100110 10010110 11001110 00101110 10100110 01001110 11111010 01100110 01001110 10000110 etc...
  • 15. 2. Non-Procedural Languages: This category also known as ‘Problem Oriented languages’. • In this type of languages we can able to make program only at specific range like database. • The followings are the examples of Non procedural languages
  • 16. • SQL (Structured Query Language) • SNOBOL (String processor)
  • 17. Learning a C Programming Language • The best way to learn is to write programs • Work your way through examples from lectures, and/or additional online tutorials • Once you are comfortable writing simple programs in C, take a look at Lab.
  • 18. 18 Algorithm: A set of instructions describing how to do a task (or process). eureka! Program: C
  • 19. From Algorithms to Programs • Both are sets of instructions on how to do a task • Algorithm: – talking to humans, easy to understand – in plain (English) language • Program: – talking to computer (compiler) – can be regarded as a “formal expression” of an algorithm
  • 20.
  • 21. C Language History • C is programming language developed at AT & T’s Bell Laboratories of USA. • First standard version release in 1972. • It was designed and written (developed) by Dennis Ritchie. • Before c a Programming language is very popular in those days the name of the language is B-Language so the developers decided the name of ‘C’ language because C is next to B. • B which evolved from BCPL.
  • 22. • C seems to be popular because it is reliable, simple and ease to use compared to other programming languages. • It was designed for systems programming – Operating systems – Compilers – Filters
  • 23. Why learn C? • C is small (only 32 keywords). • C is common (lots of C code about). • C is stable (the language doesn’t change much). • C is quick running. • C is the basis for many other languages (Java, C++, awk, Perl). • It may not feel like it but C is one of the easiest languages to learn. • Flexible language • It allows portability • Wide availability on a variety of computers
  • 24. Some programmer jargon • Some words that will be used a lot: – Source code: The stuff you type into the computer. The program you are writing. – Compile (build): Taking source code and making a program that the computer can understand. – Executable: The compiled program that the computer can run. – Language: (Special sense) The core part of C central to writing C code. – Library: Added functions for C programming which are bolted on to do certain tasks. – Header file: Files ending in .h which are included at the start of source code.
  • 25. Rules of writing a C program • One important feature of C is that it is a case sensitive language. • Lowercase and uppercase letters are distinct. • It is advisable to follow coding conventions in order to develop programs which are readable and hence easily maintainable. • Consider the following simple program which display ‘Hello World’
  • 26. More about Hello World #include <stdio.h> /* My first C program which prints Hello World */ int main() { printf ("Hello World!n"); return 0; } Preprocessor Library command main() means “start here” Comments are good Return 0 from main means our program finished without errorsBrackets define code blocks
  • 27. Chapter II: C Character, Keywords, Variables, Data Types and Constants
  • 28. Introduction • Computers are useful because of their ability to store and manipulate huge amounts of information. • This information may be numbers, such as a financial report, or alphabetic characters like names and addresses. • Managing this information requires the usage of programming languages. • One of the important tasks of a programming language is identifying the type of data it is manipulating.
  • 29. • Before we use a variable in C we must declare it. We must identify what kind of information will be stored in it. • This is called defining a variable. • Variables must be declared at the start of any block of code, but most are found at the start of each function.
  • 30. C Characters • A character denotes any alphabets,digit or special symbol used to represent information. • Alphabets:A,B,C,……,Y,Z a,b,c,…….,y,z • Digits: 0,1,2,….,9 • Special symbols:, . ! ^ & () _ <> {} ~ # ¬ etc
  • 31. C constant • A constant is an entity that doesn’t change where a variable is an entity that may change. • Types of Constant: • Primary Constant (Integer, Real, Character) • Secondary Constant(Array, Pointer, Structure,..)
  • 32. Rules for constructing integer constant a) It must have at least one digit b) It must not have a decimal point c) It can be either positive or negative d) No commas or blanks are allowed within integer constant e) If no sign precedes an integer constant it is assumed to be positive. f) The allowed range is -2147483648 to +2147483647 but it depends on the compilers For Turbo or Turbo C++ the range is -32768 to 32767
  • 33. • Examples of Integer constant: • 426,+782,-8000, etc
  • 34. Rules for constructing Real constants Real constants are often called floating point constant. It can be written into two forms: Exponential form and Fractional form Rules for constructing Real constants expressed in fractional form a) It must have at least one digit b) It must have a decimal point c) It can be either positive or negative d) Default sign positive. e) No commas or blanks are allowed within integer constant. f) EX:+325.34,-32.76,…
  • 35. • Rules for constructing Real constants expressed in exponential form a) The mantissa part and exponential part should be separated by e or E. b) Mantissa part may have a positive or negative sign. c) Default sign of mantissa part is positive d) The exponent must have at least one digit which must be a positive or negative integer. • Ex:+3.2e-5,4.1e8,-0.2E+3,etc
  • 36. Types of C variable names • We must declare the type of every variable we use in C. • An entity that may vary during program execution is called variable. • Variable names are names given to the locations in memory. • Variable name holds value. • Every variable has a type (e.g. int) and a name. • For example, Integer variable can hold only integer constant and character variable can hold only character constant.
  • 37. • Examples: • Common variable types are int, double,char and float. • Other types are signed, unsigned, long, short and const.
  • 38. Rules for constructing variable names • A variable name is any combinations of 1 to 31 alphabets, digits or underscore.Some compilers accepts variable name whose length could be up to 247 characters but don’t create unnecessarily long variable names as it adds to your typing effort. • The first character in the variable name must be an alphabets or undescore • No commas or blanks are allowed within a variable name. • No special symbol other than underscore can be used in a variable name ( gross_sal, net_sal, etc)
  • 39. • A good name for your variables is important. • Following are the examples of type declaration statements: • Ideally, a comment with each variable name helps people know what they do but not necessary. int a,b; double d; /* This is a bit cryptic */ int start_time; int no_students; double course_mark; /* This is a bit better */
  • 40. Keywords of C • Keyword: are the words whose meaning has already been explained to the C compiler. • They cannot be used as variable names because if we do so, we are trying to assign a new meaning to the keyword which is not allowed by computer. • They are 32 keywords as follows:
  • 41. • Flow control (6) – if, else, return, switch, case, default • Loops (5) – for, do, while, break, continue • Common types (5) – int, float, double, char, void • structures (3) – struct, typedef, union • Counting and sizing things (2) – enum, sizeof • Rare but still useful types (7) – extern, signed, unsigned, long, short, static, const • Evil keywords which we avoid (1) – goto • Wierdies (3) – auto, register, volatile
  • 42. Data types • C provides a number of data types, some of the basic types used are: • There are variants to the above, such as int integer char character float a floating point number
  • 43. unsigned int unsigned integer short int short integer long int long integer double double precision floating point number
  • 44. • When declaring variables to be of type long int, short int and unsigned int it is permissible to omit the keyword int. • The main difference among these data types is the amount of memory allocated for storing these. • The maximum and minimum values that can be stored in these variables depend on the version of C and the computer system being used.
  • 45. Data Type Maximum Minimum Bytes int 32767 -32768 2 unsigned int 65535 0 2 short 32767 -32768 2 long 2147483647 -2147483648 4 char (ASCII codes) 127 -128 1 unsigned char 255 0 1 float 3.4E+38 3.4E-38 4 double 1.7E+308 1.7E-308 8
  • 46. Formatted Input and Output • Formatted output statement is nothing but the most commonly used printf() function. • This function consists of a literal string or value of a variable which has to be displayed on the standard terminal and a format specifier which specifies how it has to display. • Consider some of the following printf () statements: • printf("Hello n"); • printf("Your salary is t %f n", sal);
  • 47. • Some of the commonly used format specifiers are mentioned below: • %d int: Integer • %ld long int: long integer • %c char :single character • %s string: Null terminated strings • %f float or double • %e same as %f but exponential notation is used • %g use %f or %e • %x hexadecimal value (base 16) • %o Octal value (base 8)
  • 48. • scanf() is used for reading formatted data from the keyboard. • Similar to printf () it requires a format specifier, followed by the list of items to be read. • One important point to remember here is, scanf() requires the address of the items to be read.
  • 49. CHAPTER III: Operators and Expressions in C language
  • 50. Introduction • C has a wide range of operators. • Expressions Combine values using operators and function calls • Expressions return a value of a known type
  • 51. Arithmetic Expressions • An arithmetic expression is composed of operators and operands. Operators act on operands to yield a result. • Commonly used arithmetic operators are +, -, *, / and %. • The plus sign (+) is used to add two values, the minus sign (-) to subtract one value from another, the asterisk(*) to multiply two values, the division (/) to divide a value and the modulus (%) to obtain the reminder of integer division. • These are known as binary operators since they operate on two values or variables.
  • 52. • It take arithmetic (numerical) values and return an arithmetic (numerical) value • Are composed using the following operators: + (unary plus) - (unary minus) + (addition) - (subtraction) * (multiplication) / (division or quotient) % (modulus or remainder)
  • 53. Precedence in Expressions • Defines the order in which an expression is evaluated.
  • 54. Example1 1 + 2 * 3 - 4 / 5 = B stands for brackets, O for Order (exponents), D for division, M for multiplication, A for addition, and S for subtraction. B.O.D.M.A.S. 1 + (2 * 3) - (4 / 5)
  • 55. More on precedence • *, /, % are at the same level of precedence • +, - are at the same level of precedence • For operators at the same “level”, left-to-right ordering is applied. 2 + 3 – 1 = (2 + 3) – 1 = 4 2 – 3 + 1 = (2 – 3) + 1 = 0 2 * 3 / 4 = (2 * 3) / 4 = 6 / 4 2 / 3 * 4 = (2 / 3) * 4 = 0 * 4
  • 56. Precedence in Expressions – Example (cont) 6.2 1 + 2 * 3 - 4 / 5 = 1 + (2 * 3) - (4 / 5)
  • 57. Precedence in Expressions –Example (cont) 6.2 1 + 2 * 3 - 4 / 5 = 1 + (2 * 3) - (4 / 5)
  • 58. Precedence in Expressions – Example (cont) Integer division results in integer quotient 1 + 2 * 3 - 4 / 5 = 1 + (2 * 3) - (4 / 5)
  • 59. Precedence in Expressions – Example (cont) = 0 D’oh 1 + 2 * 3 - 4 / 5 = 1 + (2 * 3) - (4 / 5)
  • 60. Precedence in Expressions – Example (cont) 7 1 + 2 * 3 - 4 / 5 = 1 + (2 * 3) - (4 / 5)
  • 61. int-s and float-s • float is a “communicable” type • Example: 1 + 2 * 3 - 4.0 / 5 = 1 + (2 * 3) - (4.0 / 5) = 1 + 6 - 0.8 = 6.2
  • 62. int-s and float-s – Example 2 (1 + 2) * (3 - 4) / 5 = ((1 + 2) * (3 - 4)) / 5 = (3 * -1) / 5 = -3 / 5 = 0
  • 63. int-s and float-s – Example 2 (cont) (1 + 2.0) * (3 - 4) / 5 = ((1 + 2.0) * (3 - 4)) / 5 = (3.0 * -1) / 5 = -3.0 / 5 = -0.6
  • 64. int-s and float-s – Example 3 (1 + 2.0) * ((3 - 4) / 5) = (1 + 2.0) * (-1 / 5) = 3.0 * 0 = 0.0
  • 65. Unary operators • A unary operator is one which operates on one value or operand. • The minus sign (-) plays a dual role, it is used for subtraction as a binary operator and for negation as a unary operator. • This operator has a precedence higher than the rest of the arithmetic operators. • Example i = +1; /* + used as a unary operator */ j = -i; /* - used as a unary operator */
  • 66. • The unary + operator does nothing – just emphasis that a numeric constant is positive. • The unary – operator produces the negative of its operand. • Example: result = -x * y; • In the above expression, if x has a value 20 and y has a value 2, then result will contain a negative value of 40 which is -40.
  • 67. Ternary operator • In C the ternary operator is the conditional expression operator. • This accepts three operands. • Question mark (?) and colon (:) are the two symbols used. • The format of the ternary operator is: • expression1 ? expression2 : expression3 • Where expression1 is an expression evaluated to true of false. • If expression 1 is true, expression 2 is executed • If expression 1 is false, expression 3 is executed
  • 68. • Example: • Max=(a>b)? a: b //compute maximum of a and b. • Let a=10 and b=20 10>20?false Max=20 • Let a=30 and b=10 30>10? True Max=30
  • 69. Increment and decrement operators • ++ is the increment operator i++; is equivalent to i = i + 1; • -- is the decrement operator j--; is equivalent to j = j - 1;
  • 70. A short note about ++ • ++i means increment i then use it • i++ means use i then increment it int i= 6; printf ("%dn",i++); /* Prints 6 sets i to 7 */ int i= 6; printf ("%dn",++i); /* prints 7 and sets i to 7 */ Note this important difference It is easy to confuse yourself and others with the difference between ++i and i++ - it is best to use them only in simple ways.
  • 71. • Example: Let a=20 • Post increment b=a++ current value of a is used b=a b=20 a is incremented by 1 a=a+1 a=21 • Pre increment b=++a a is incremented by 1 a=a+1 a=21 incremented value of a b=a b=21 is used
  • 72. • Example: Let a=10 • Post decrement b=a-- current value of a is used b=a b=10 a is incremented by 1 a=a-1 a=9 • Pre increment b=--a a is incremented by 1 a=a-1 a=9 incremented value of a b=a b=9 is used
  • 73. Relational operator • In real world we may have to compare two quantities which results in either true/false or yes/no output. In such situation we use relational operators. • EX1: is my score greater than 90? • EX2: is my weight less than 68 kg?
  • 74. • Relational operators are operators that are used to find the relationship between two operands. • Note: Output of relational expression is true denoted by 1 or false denoted by 0.
  • 75. Description Operator Less than < Lesser/equal <= Greater > Greater/equal >= Equal == Not Equal != Note that == is used in comparisons and = is used in assignments. Comparison operators are used in expressions like the ones below
  • 76. • x == y valid • i > 10 valid • a + b != c valid • a=<b invalid operators are not in order • a< =b invalid there is space between < and = 3>2 1 2>3 0 2>=2 1 3+2<6 1
  • 77. • Precedence of operators: • Evaluate the expression within parentheses • Evaluate unary operator • Evaluate arithmetic expression • Evaluate relational expression EX: Evaluate the following expression 100/20<=10-5+100%10-20==5>=1!=20
  • 78. Logical operators • Logical operators in C are as per table && Logical AND(Binary operator) || Logical OR(Binary operator) ! Unary NOT They are frequently used to combine relational operators, For example : x < 20 && x >= 10
  • 79. • Logical operators use true or false properties of expressions to return a true or false. • True is represented by a non-zero value and false by zero. •
  • 80. • Consider the following expression: • result = q1 && q2; /* result is true if both q1 and q2 are non-zero */ (1&&1=1,1&&0=0,0&&1=0 and 0&&0=0 ) • result = q1 || q2; /* result is true if either q1 or q2 is non-zero */ (1 || 1=1, 1 || 0 = 1, 0 || 1=1 and 0 || 0=0) • result = !q1; /* result is true only if q1 is zero */ (!0=1 and !=1=0)
  • 81. • Precedence of operators: • Evaluate the expression within parentheses • Evaluate unary operator • Evaluate arithmetic expression • Evaluate relational expression • Evaluate logical expression EX: Evaluate the expression a+2 > b && !c || a !=d && a-2 <=e where a=11,b=6, c=0, d=7 and e=5
  • 82. Assignment operator • It is an operator which is used to assign the data or result of an expression into a variable. • Assignment operator symbol is “ = “ • Types of assignment operator: 1. Simple assignment statement Ex: a=a+10; 2. Shorthand assignment statement Ex: a+=10; 3. Multiple assignment statement Ex: a=b=10; • Example: pi= 3.14(The value 3.14 is copied into variable pi)
  • 83. • The following table shows shorthand assignment statement: Shorthand statement Meaning Explanation a+=2 a=a+2 Evaluate a+2 and store the result in a a-=2 a=a-2 Evaluate a-2 and store the result in a a*=2 a=a*2 Evaluate a*2 and store the result in a a/=2 a=a/2 Evaluate a/2 and store the result in a
  • 84. Comma operator • Comma can be used in an expression. • Comma operator is denoted ‘,’ • Comma is used in variable declaration like int a,b,c Here comma isnot used as operator. • Comma operator acts on two operands and normally is used to: • Separate items in the list Ex: a=12,345,678; • Combine two or more statements into single statement EX: a=10,b=20,c=30; • Comma expression is evaluated from left to right.
  • 85. • Evaluate the following expression: • Example 1: a=12,345,678; • There are two operators: assignment and comma operators,since assignment has highest precedence over comma operator ,integer 12 is copied into variable a and other integers 345 and 678 are discarded • The answer is : a=12 the remaining values 345 and 678 are discarded.
  • 86. • Example 2:Evaluate the following comma expression a=5+5, 6*5; • Solution: • a=5+5,6*5 • a=5+5 then 6*5 is discarded • a=5+5=10 Note: All Expression after first comma are discarded.
  • 87. CHAPTER IV: Control of Flow Instructions
  • 88. Topic • Decision control structure • Loop control structure • Case control structure
  • 89. Decision control structure • Many times we want the instruction to be executed In one situation and an entirely different set of instruction to be executed in another situation. • This kind of situation is dealt with in C programs using decision control instruction.
  • 90. The if statement • Decides what to do by evaluating a Boolean expression. • If the expression is true (non-zero), the statement or block is executed. • The general form is: if ( expression ) { statement }
  • 91. Program1 /* Read in a number, and check if it is odd. */ #include <stdio.h> #include <conio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); if (number % 2 != 0) { printf("%dn", number); } getch(); return 0; }
  • 92. Program2 /*Program to find the largest of 2 numbers*/ #include <stdio.h> #include <conio.h> int main() { int a,b; printf(“Enter two numbers:”); scanf(“%d %d”,&a,&b); if(a>b) { printf(“%d is largest ”,a); } If(a<b) { printf(“%d is largest ”,b); }
  • 93. • Other Program to write: • Program to find roots of quadratic equation.
  • 94. If else • Another variation of an if statement is an if else statement. • This statement helps a programmer to evaluate a condition and take two different actions depending on whether it results a result of TRUE or FALSE. • Can only occur after an if statement • Is only executed when the if block does not execute
  • 95. • General form: if ( expression ) { statement1 } else { statement2 }
  • 96. /* Determine whether an input number is odd or even. */ #include<stdio.h> main() { int number; printf("Enter an integer: "); scanf("%d", &number); if (number % 2 != 0) { printf("%d is an odd numbern", number); } else { printf("%d is an even numbern", number); } }
  • 97. Cascaded if statement if (expression1) { statements; } else if (expression2) { statements; } else { statements; <………Default block }
  • 98. /*Program to calculate percentage of marks*/ #include<stdio.h> int main() { int m1,m2,m3,m4,m5,per; printf(“Enter five marks /100 each:”); scanf(“%d %d %d %d %d”,&m1,&m2,&m3,&m4); per=((m1+m2+m3+m4+m5)*100)/500; if(per>=60) printf(“First Divisionn”); else if(per>=50) printf(“Second Divisionn”); else if(per>=40) printf(“Third Division”); else printf(“Fail”n); return 0; }
  • 99. Loop control • Before we proceed to the statements that change the flow of execution we need to understand how code is repetitively executed. This is known as executing a loop. • Each execution of a loop is known as iteration. • C language has three different program statements for program looping.
  • 100. • They are • for statement, • while statement and • do while statement.
  • 101. for loop • For statement • The general format of a for statement is: for ( expression1; loop_condition; expression2) { program statements; }
  • 102. • The first component of the for statement, expression1 is used to set the initial values before an iteration begins. • The second component which is loop condition specifies the condition(s) that has (have) to be met for the loop to continue. • The final component expression2 specifies the expression that is executed each time after the body of loop is executed.
  • 103. #include <stdio.h> int main() { int x; /* The loop goes while x < 10, and x increases by one every loop*/ for ( x = 0; x < 10; x++ ) { /* Keep in mind that the loop condition checks the conditional statement before it loops again. consequently, when x equals 10 the loop breaks. x is updated before the condition is checked. */ printf( "%dn", x ); } getch(); return 0; }
  • 104. Nested for /*A C program to display Hello World 5 times*/ #include<stdio.h> int main() { int i, n=5; for(i=0;i<n;i++) { printf(“Hello World!”); } return 0; }
  • 105. /*A C program to Print an –4 by-2 rectangle of asterisks. */ #include<stdio.h> int main() { int i, j, m=4, n=2; for (i=0; i < n; i++) { for (j=0; j < m; j++) { printf("*"); } printf("n"); } return 0; }
  • 106. while • The syntax of the while statement is while (expression) { program statements; } • The expression specified inside the parentheses is evaluated, if the result of the expression is true then the program statements inside the loop is executed. • After one iteration the expression is evaluated again and the loop is executed depending on whether the result is true. If the result is false, then the loop is terminated and the program execution continues with the statements following the while loop.
  • 108. • do { program statements(do this); } while (expression1); • Here the program statements are first executed once, then the expression1 is evaluated. • If it is true, then it proceeds to the next iteration. This continues till the expression1 evaluates to false.
  • 110. Break statement • Format of this statement is: break; • Sometimes it becomes necessary to terminate a loop depending on a condition. • In such circumstance, a break statement can be used. • This causes the program to exit the loop and execution continues with the statements following the loop. • In case of a nested loop, only the loop in which the break statement occurs is terminated. • A break statement takes the execution control out of loop.
  • 111. Break Example #include<conio.h> #include<stdio.h> void main() { int i; clrscr(); for(i=1;i<10;i++) { printf("nnThis is the ROUND No: %d",i); if(i==5) break; printf(" Let me start the ROUND No: %d n",i+1); } printf("This is the ROUND No: %d",i); getch(); }
  • 112. Continue statement • Format of this statement is continue; • Unlike a break statement, this causes the loop in which it occurs to continue. • All the statements following the continue statement are ignored. • This is used to bypass a group of statements in a loop based upon certain criteria or conditions.
  • 113. Continue example #include<conio.h> #include<stdio.h> void main() { int i; clrscr(); for(i=1;i<10;i++) { printf("nnThis is the ROUND No: %d",i); if(i==5) continue; printf(" Let me start the ROUND No: %d n",i+1); } printf("This is the ROUND No: %d",i); getch(); }
  • 114. switch case statement Syntax of switch case: switch (expression1) { case val1 : program statements; break; case val2 : program statements; break; … default : program statements; break; }
  • 115. • The expression1 is repeatedly compared against values val1, val2 and so on till a match is found. • Then the corresponding program statements are executed. • Every set of statements needs a break statement otherwise the program execution will continue into the next case statement that satisfies the expression. • There is a special default statement at the end which gets executed when the value of expression1 does not match any of the case values
  • 116. Example 1 #include<conio.h> #include<stdio.h> void main() { int i=2; clrscr(); switch(i) { case 1: printf(“I am in case 1n"); break; case 2: printf(“I am in case 2n"); break; case 3: printf(“I am in case 3n"); default: printf(“I am in defaultn"); } getch(); }
  • 117. • Example 2: Write a c program which simulate calculator of 5 arithmetic operations (+,-,*,/ and %) using switch case • Example 3: Write a c program to display days of week using switch case.
  • 119. What is a function? • The function is one of the most basic things to understand in C programming. • A large program can be divided into manageable pieces called modules where each module does a specific task. Thus the function often called modules are self contained small programs(called program segments) that carry out some specific, well defined tasks. • A function is a sub-unit of a program which performs a specific task. • We have already seen one function from the C library printf(),scanf(),getch(),clrscr(),etc .
  • 120. • We need to learn to write our own functions. • Functions take arguments (variables) and may return an argument. • Think of a function as extending the C language to a new task. • NOUNS functions are VERBS.
  • 121. • The function can be classified into two categories as shown below: 1. Library functions/predefined functions. 2. User defined Functions(UDFs).
  • 122. Why functions • The program that we study are very small when compared to the program that we write for a complex in real word. • If the program is very there are too many disadvantages: • It is very difficult for the programmer to write a large program • Very difficult to identify logical errors and correct errors in a large program • Very difficult to read and understand a large problem • Large programs are more prone to errors and so on.
  • 123. Library name Example functions Header files Standard input/output library printf():is used to display/print data on the screen scanf():used to read data from the keyboard,etc… stdio.h Math library pow(x,y):compute xy sqrt(x):compute square root of x,etc…. math.h Character library isalpha(), tolower(),toupper(),et c… ctype.h String library Strcpy(),stlen(), strcmp(),etc… string.h Time clock(),time(),etc.. time.h Library functions/predefined functions
  • 124. User defined functions • Using only library functions, it is not possible to write a program to achieve some specific tasks. • In such case, the programmer need to write their own functions to achieve the required tasks. • The functions which are written by the programmer/user to do some specific tasks are called User defined functions. • Suppose we want to compute square of number. And the function library to do this task is not available then the function square() can be defined by user to return square of number.
  • 125. What are these prototype things? • A prototype tells your C program what to expect from a function - what arguments it takes (if any) and what it returns (if any) • Prototypes should go before main() • #include finds the prototypes for library functions (e.g. printf) • A function MUST return the variable type we say that it does in the prototype.
  • 126. #include<stdio.h> #include<conio.h> void italy(); void rwanda(); Function prototype void usa(); int main() { printf("I am in main functionn"); italy(); rwanda(); Function call usa(); getch(); return 0; }
  • 127. void italy() { printf("I am in Italyn"); } void rwanda() { printf("I am in Rwandan"); } void usa() { printf("I am in USAn"); }
  • 128. What is scope? • The scope of a variable is where it can be used in a program • Normally variables are local in scope - this means they can only be used in the function where they are declared (main is a function) • We can also declare global variables. • If we declare a variable outside a function it can be used in any function under where it is declared • Global variables are A BAD THING
  • 129. The print stars example #include <stdio.h> void print_stars(int); void main() { int i; for (i= 0; i < 5; i++) print_stars(5); } void print_stars (int n) { int i; for (i= 0; i < n; i++) printf ("*"); printf ("n"); } This program prints five rows of five stars This prints 'n' stars and then a new line character Loop around 5 times to print the stars ***** ***** ***** ***** ***** Variables here are LOCAL variables
  • 130. #include<stdio.h> #include<conio.h> int calcsum(int x,int y,int z);/*Function prototype*/ int main() { int a,b,c,sum; printf("Enter 3 numbers:"); scanf("%d %d %d",&a,&b,&c); sum=calcsum (a,b,c); /*Function call*/ printf("sum of (%d %d %d)=%dn",a,b,c,sum); getch(); return 0; } int calcsum(int x,int y,int z)/*Function definition*/ { int d; d=x+y+z; /*definition*/ return d; }
  • 131. • There are somethings to know about this program: 1. From the main function values of a,b,c are passed on to the function calcsum(), by making a call to the function calcsum() and mentioning a,b,c and d in the parantheses. calcsum(a,b,c); • In the calcsum() function these values get collected in three variables s,y and z. • calcsum(x,y,z)
  • 132. 2. The variables a,b and c are called ‘actual argument’, where as the variables x,y and z are called ‘formal arguments’. Any number can be passed to the function being called. The type, order and number of the actual and formal arguments must be the same. 3. Function Prototype declaration of calcsum() is int. This indicates our function return a value of type int.( int calcsum(int, int, int) )
  • 134. • Array is a data structure that represents a collection of the same types of data(element(s)). • We have one dimensional array & multidimensional array.
  • 135. Declaring Array Variables • datatype arrayRefVariable[]; Example: int A[10];
  • 136. Indexed Variables • The array elements are accessed through the index. • The array indices are 0-based, i.e., it starts from 0 to arrayRefVariable.length-1. • In the example, the array A holds ten integer values and the indices are from 0 to 9. • Each element in the array is represented using the following syntax, known as an indexed variable: arrayRefVariable[index];
  • 137. Using Indexed Variables • After an array is created, an indexed variable can be used in the same way as a regular variable. • For example, the following code adds the value in A[0] and A[1] to A[2]. A[2] = A[0] + A[1];
  • 138. Array Initializers • Declaring, creating, initializing in one step: int A[10]= {1,9, 2,7,3,5,11,0,-5,11}; This shorthand syntax must be in one statement.
  • 139. Declaring, creating, initializing Using the Shorthand Notation int A[10]= {1,9, 2,7,3,5,11,0,-5,11}; This shorthand notation is equivalent to the following statements: int A[10]; A[0] = 1; A[1] = 9; A[2] = 2; A[3] = 7; A[4] = 3; A[5] = 5; A[6] = 11; A[7] = 0; A[8] = -5; A[9] = 11;
  • 140. 140 • Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. • Splitting it would cause a syntax error. • For example, the following is wrong: int A[10]; A = {1,9, 2,7,3,5,11,0,-5,11};
  • 141. A C program to initialize an array #include<conio.h> #include<stdio.h> void main() { /*declaration*/ int A[10], i; clrscr(); /*initialization an array using for loop*/ for(i=0;i<10;i++) { printf("Enter the number"); scanf("%d“, &A[i]); }
  • 142. A C program to initialize an array(cont) /*Displaying an array using for loop*/ printf("The array is : "); for(i=0;i<10;i++) { printf("%d”, A[i]); /*Elements displayed*/ } getch(); }
  • 143. Two-dimensional Arrays • Thus far, you have used one-dimensional arrays to model linear collections of elements. • You can use a two-dimensional array to represent a matrix or a table. • For example, the following table that describes the distances between the cities can be represented using a two-dimensional array.
  • 145. 145 Declaring Variables of Two-dimensional Arrays and Creating Two-dimensional Arrays // Declaration of two-dimensional array syntax: dataType arrayrefVar[size][size]; array name Example: int matrix[3][3];
  • 147. 147 Declaring, Creating, and Initializing Using Shorthand Notations You can also use an array initializer to declare, create and initialize a two-dimensional array. For example, int matrix [4][3] ; matrix[0][0] = 1; matrix[0][1] = 2; matrix0][2] = 3; matrix[1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6; matrix[2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9; matrix[3][0] = 10; matrix3][1] = 11; matrix[3][2] = 12; int matrix[4][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; Same as
  • 148. #include<conio.h> #include<stdio.h> void main() { //declaration int matrix[3][3] ; int i,j; clrscr(); // initialization for(i=0;i<3;i++) for(j=0;j<3;j++) { printf("Enter the %d Number",j+1); scanf("%d",&matrix[i][j]);
  • 149. //displaying an array printf("The matrix is: "); for(i=0;i<3;i++) { printf("nn "); for(j=0;j<3;j++) { printf("%d ",matrix[i][j]); } } getch(); }
  • 151. • In C language, the group of character, digits and other symbols enclosed within quotation marks are called as string. • The string is always declared as character arrays. In other words, character arrays are called strings. • To manipulate text such as words and sentences normally strings are used. • Every string is terminated with ‘0’ (NULL) character; the decimal value of NULL character is zero. • Example: char name[6]={‘H’,’E’,’L’,’L’,’O’,’0’};
  • 152. • Each character of string occupies 1 byte of memory. • The last character is always ‘0’. • It is not compulsory to write ‘0’ in string. • The compiler automatically puts ‘0’ at the end of the character array or string. • The characters of string are stored in contiguous (neighbouring) memory locations.
  • 153. Declaration and Initialization of String • char name [6] =”Hello”;//using double quotes • char name[6]={‘H’,’e’,’l’,’l’,’o’,’0’};//using single quote • The c compiler inserts the NULL (0) character automatically at the end of the string. So the initialization of NULL character is not essential. • char name[6]={’U’,’N’,’I’,’V’,’E’,’R’} //An error. The output will not be ‘UNIVER’ but UNIVER with some garbage value as the NULL character has not been initialized.
  • 154. Display of strings with different formats • String header file is : #include <string.h> • The printf() function is used for displaying the various data types. • The printf() function with %s format is to be used for displaying the string on the screen. • scanf() is replaced by gets() to read the string from the keyboard. • strlen() function. This function counts the number of characters in a given string. The format of function is strlen(string). • strrev() function • This function is used to find reverse of a string.
  • 155. • Example: • Write a c program to read a text through the keyboard. Determine the length of the string and its reverse
  • 156. #include<stdio.h> #include<conio.h> #include<string.h> int main() { char x[10]; int len; clrscr(); printf("Enter any string to check:n"); gets(x); len=strlen(x); printf("lenght of %s is %dn",x,len); printf("reverse of %s is %sn",x,strrev(x)); getch(); return 0; }
  • 157. • stricmp() function. • This function compares two strings without considering lower case or upper case. • It returns zero when two strings are same otherwise it returns non-zero value. Exercise: Write a program to compare two strings • strlwr() function • This function can be used to convert any string to a lower case. When you are passing any upper case string to this function, it is converted into lower case. The format of function is strlwr(string). Exercise: Write a program to convert upper case string to lower case using strlwr()
  • 158. • strupr() function • This function is the same as strlwr() but the difference is that strupr() converts lower case strings to upper case. • The format of function is strupr(string). Exercise: Write a c program to convert your full name in lower case string to upper case using strupr() Exercise: Write a program to know whether the entered character string is palindrome or not. (Palindrome word reads same from left to right & right to left). • strcat(): This function is used to concatenate two strings • The format is strcat (target, source)
  • 159. #include<stdio.h> #include<string.h> #include<conio.h> main() { char fname[10];/*Source string*/ char sname[10];/*target string*/ printf("Enter fname"); gets(fname); printf("Enter sname"); gets(sname); clrscr(); strcat(sname,fname); printf("Fullname is %sn",sname); getch(); return 0; }
  • 160. References • Core texts • Brian W.Kernighan and Dennis M.Ritchie,[1988] The C programming Language, Second edition, Prentice Hall. • Clovis L. Tondo and Scotte E. Gimpel,[ 1989] The C Answer book ,Second edition, Prentice Hall. • Ritchie, M. Dennis, [2000]The C programming language, 005.33 KER 2000 • Background Texts • (Hervey and Paul) Deitel and Associates, [2007] C how to program, Fifth edition, Prentice Hall. • Ritchie, M. Dennis,[2000] The C programming Language. • Uckan, Yuksel,[1999] Problem solving using C: Structured programming Techniques

Editor's Notes

  1. 6
  2. July 24, 2003
  3. Lecture 3: C Primitives 1
  4. 10/17/2016