0% found this document useful (0 votes)
5 views86 pages

Unit 1 CPRG

The document provides an overview of C programming, including fundamental concepts such as algorithms, flowcharts, and the structure of a C program. It covers the history and features of C, data types, variable declaration, and the compilation process. Additionally, it explains the basic syntax and components of C programs, including keywords, identifiers, constants, and the execution of programs.

Uploaded by

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

Unit 1 CPRG

The document provides an overview of C programming, including fundamental concepts such as algorithms, flowcharts, and the structure of a C program. It covers the history and features of C, data types, variable declaration, and the compilation process. Additionally, it explains the basic syntax and components of C programs, including keywords, identifiers, constants, and the execution of programs.

Uploaded by

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

C Programming

Intro
• Computer?
• H/W?
• S/W?
• Program?
• OS?
• Low level, high level?
• Systems, Application?
• Machine, Assembly, English?
• Algorithm, Flowchart, Program
Algorithm
• An algorithm is a step-by-step procedure to solve logical and
mathematical problems.
– A recipe is a good example of an algorithm because it says
what must be done, step by step. It takes inputs
(ingredients) and produces an output (the completed
dish).
• Algorithms are usually written in pseudocode, or a
combination of your speaking language and one or more
programming languages, before writing a program.
• Algorithms are generally created independent of underlying
languages, i.e. an algorithm can be implemented in more than
one programming language.
• Abū ʿAbdallāh Muḥammad ibn Mūsā al-Khwārizmī, a Persian
mathematician who also gave the words algorism (using place
value) and algebra.
Algorithm
• An algorithm must have five properties:
– Input: All inputs should be clearly specified
– Output: Desired output must be specified and
how it is related to the inputs
– Definiteness: Steps must be clearly specified and
detailed.
– Effectiveness: Steps must be doable and effective
– Finiteness: Algorithm must come to an end after a
specific number of steps
How to make tea?
1. Start
2. Take a vessel
3. Measure & add water to the vessel
4. Switch on burner and place vessel on burner
5. Measure & add sugar into vessel. Let sugar dissolve
6. Measure & add tea powder to vessel
7. Switch off burner and cover vessel.
8. After some time, strain & pour tea into cups
9. If required, add milk into the cups.
10. Serve the tea.
11. Stop
Adding two numbers
1. Start
2. Get the first number, n1
3. Get the second number, n2
4. Perform Sum = n1+n2
5. Display/Print Sum.
6. Stop
Find largest of three numbers
Start
1. Start
Read A,B,C
2. Get 3 numbers – A, B, C
3. Compare A with B A>B
?
1. If A>B, then make Big = A,
otherwise make Big = B Big=B
Big=A
4. Compare Big with C
1. If Big < C, then Big = C
Big<
5. Display Big C?
Big=C
6. Stop
Print Big

Stop
Flowchart
• A picture of the separate steps of a process in
sequential order.
• A graphical representation for an algorithm, using
standard symbols
• Flow – series of ordered steps, and Chart –
graphical representation
• Flowchart can be used to trace the steps of an
algorithm easily, checking for correctness.
• Since no language is used, it can be understood
universally.
Standard Flowchart Symbols

Start/Stop
Direction Arrows

Process
Connectors

Decision
Off-page
Connectors

Input/Output
Flowchart for making tea
A B
Start
Boil water No
Want
Take Vessel until sugar
milk?
dissolves
Yes
Add tea
Add Water Add milk
powder
to cup
Switch ON Switch OFF
burner and burner and
Serve
place Vessel cover vessel

Pour tea into Stop


Add Sugar cups

A B
Factorial of a given number
Given n, generate Fibonacci sequence
till n
Program to read a number, find the sum of the digits,
reverse the number and check it for palindrome
Read numbers from keyboard continuously till the user
presses 999 and to find the sum of only positive
numbers
Remove Duplicate Element in a list
C Programming
• Overview of C;
• History and Features of C;
• Structure of a C Program with Examples;
• Creating and Executing a C Program;
• Compilation process in C
History of C
• 1960, ALGOL, 1st computer language to use block structure –
structured programming
• 1967, Martin Richards, BCPL (Basic Combined Programming
Langauge) – systems s/w
• 1970, Ken Thompson, B language, used to create earlier version of
OS – UNIX
• 1973, C evolved from ALGOL, BCPL, B by Dennis Ritchie at Bell Labs.
Strongly associated with UNIX – traditional C
• 1978, K&R C, by Kernighan and Ritchie
• 1989, ANSI approved a common version called as ANSI C
• 1990, C++, an object oriented language was developed, based on C
Features of C
• Robust language
– Rich set of built-in functions and operators can be sued to
develop complex programs, C has only 32 keywords
• Combines assembly language with high level language – useful for
both systems programming and business applications
• Efficient and fast programs can be developed
– Due to variety of data-types and powerful operators
• Highly portable
– Easy to run the same program on different kinds of computers
• Well suited for structured programming
– Makes debugging, testing and maintenance easy
• C language can extend itself
– By adding our own functions to the library of functions
Sample C Program
main()
{
/*….program to print a line….*/
printf(“Welcome to C Programming”);
//….end of program
}
• The first line tells us that the name of the program is main
– program execution begins at this line
– Every program must have only one main() function
• Functions begin with { - ‘opening brace’ and end with a } - ‘closing
brace’.
– First and last lines of main() have { and }
– The part between the { and } is called the body of the function.
• Lines beginning with /* and ending with /* are multi-line comments.
• A single line comment has only // at the beginning and automatically
ends at the end of the line.
• Only executable statement in the program is the printf statement.
• All executable statements should end with a ;
Structure of a C Program

Documentation Section

Link Section
Definition Section
Global Declaration Section

Main Program Section

Subprogram Section
Sections of a C program
• Documentation Section:
– This section contains comment lines
– To provide info like name of programmer, name of
program, revision number, date and other details
which may be used later.
– Multi-line comment begins with /* and ends with */
– Single line comment begins with //
– This is not a compulsory section, but good
programming technique requires that this section is
present.
Sections of a C program
• Link Section:
– Instructs compiler to link functions from the
system library.
– It can be done by using pre-processor directives or
commands to the compiler.
– The pre-processor directives are not executable
statements, and always begin with #include.
– Their form is #include<filename>
– They never end with a ;
– This section is not compulsory
Sections of a C Program
• Definition Section:
– Contains the definitions of all the symbolic
constants used in the program.
– Statement begins with a #define, which is a pre-
processor directive, hence it should not end with a
;
– Constants are values that do not change
throughout the program.
– Comes before the main() function.
– This section is not compulsory.
Sections of a C program
• Global Declaration Section
– Used to declare all variables and user-defined
function names.
– Consists of declaration statements
– This section is not compulsory.
Sections of a C program
• Main Program Section:
– All C programs must have this section
– Program execution begins and ends with this section.
– Contains local declaration section which is used to
declare variables used only in the main() function,
followed by the body of the main() function.
– The empty pair of parenthesis () tells us that the main
function does not have any arguments.
– Different forms of main function are
• main(), int main(), void main(), main(void), int main(void).
Sections of a C Program
• Subprogram (Function Definition) Section:
– May come either before or after the main()
function.
– Contains the definitions of all the user defined
function used in the main() function.
– It can contain any number of user defined
functions.
– This section is not compulsory.
Executing a C program
• Steps involved
– Creating the program (using any editor program)
– Compiling the program (making it error free)
• Syntax errors – grammatical errors (compiler does it)
• Semantic errors – logical errors (programmer does it)
– Linking programs with library functions
– Executing the programs
System Ready A
Executable Code
Program Execute Object
Enter Program
Code Code
Source Program
Input
Edit Source Logic Data
Program Error Logic &
Data
C Compile Source Errors? Data
Compiler Program Error
No
Error
Yes Correct Output
Syntax
Errors?
Object Code
No
Stop
System Link with
Library System Library

A
C Programming Basic Concepts

• C Character Set;
• C tokens - keywords, identifiers, constants,
and variables;
• Data types;
• Declaration & initialization of variables;
• Symbolic constants
C Character Set
• Letters: A – Z, a-z
• Digits: 0 – 9
• Special Characters: , . / ? ’ ” ` ~ ! # $ % ^ & * ( )
-_=+[]{}\/|;:<>
• White spaces : blank spaces, horizontal tab,
carriage return, Newline, form feed
C tokens
• 6 types of tokens
Keywords
• Every word used in a C program is classified as
either a keyword or as an identifier.
• A keyword in C is a reserved word which has a
specific meaning.
• Keywords in C must be in lowercase.
• Keywords serve as the basic building blocks
for program statements.
List of C keywords
• 32 keywords in ANSI C
Identifiers
• Identifiers refer to the names of variables,
functions and arrays.
• They are user-defined names and consist of
sequence of letters and digits, with a letter as a
first character.
• Both uppercase and lowercase letters can be
used, although lowercase letters are generally
used.
• The underscore character is also permitted in
identifiers.
Rules for naming identifiers
• First character must be an alphabet or
underscore.
• Must consist of only letters, digits or
underscore.
• Only first 31 characters are significant.
• Cannot use a keyword.
• Must not contain white space.
Constants
• Constants are fixed values that do not change
during execution of program
Integer Constants
• An integer constant refers to a sequence of
digits.
• Generally in programs, the number systems
used are: decimal, octal and hexadecimal.
• Decimal: 0 – 9. egs - 23, 45, 76855, -21, -8
• Octal: 0 – 7. egs – 5, 12, 45, -3, -55
• Hexadecimal: 0 – 9 and A to F. egs – 8, A, C,
23, 44, 2E,
Real Constants
• Integer numbers are not enough to represent
quantities that change continuously, such as
distances, height, prices etc.
• These quantities are represented by numbers
containing fractional parts like 25.234.
• Such numbers are called as real or floating
point constants.
• Examples of real constants are: 0.067, -12.5,
+4.67, .87, 121.
Real Constants
• A real number may also be expressed in exponential
(scientific) notation, ex. 45.2344 can be written
0.452344e2.
• The exponential notation is: mantissa e exponent.
– The mantissa is either a real number expressed in decimal
notation or an integer with an optional + or – sign.
– The exponent is an integer number with an optional + or –
sign.
• Some valid examples of real constants in exponential
notation are: 0.34e2, 13e-2, -1.23e-1
Single character constants
• A single character constant or character
constant contains a single character enclosed
in between single quotes.
• Some valid examples of character constants
are: ‘f’ ‘A’ ‘/’ ’;’ ‘ ‘ ‘4’
• The character constant ‘4’ is not equal to the
number 4.
String Constants
• A sequence of characters that are enclosed
between double quotes is known as a string
literal or string constant.
• The characters in a string literal can be either
letters, digits or special symbols or white
spaces.
• Examples of string constants are: “Ajay”,
“hEllO”, “hi5”, “Wel come”, “B”, “34”
Backslash character constants
• C supports special
backslash character
constants that are
used in functions like
printf().
Datatypes
• C supports various datatypes
– Allows selection of proper type as per need
• Three classes
– Primary (fundamental) datatypes
– Derived datatypes
– User-defined datatypes
Primary datatypes
• 5 types
– Integer (int-16, short int-8, long int-32) - signed,
unsigned
– Character (char-8) - signed, unsigned
– Floating point (float-32, long double-80)
– Double precision floating point (double-64)
– void
Size and range of Primitive datatypes
• char : -128 to 127
• int : -32768 to 32767
• float : 3.4e-38 to 3.4e+38
• double : 1.7e-308 to 1.7e+308
Declaration of variables
• After deciding proper variable names, they
should be declared, for two reasons
– Tell the compiler what the variable name is
– Specify what type of data it will hold
• Variables should be declared before they are
used in the program
Primary variable declaration
• Syntax
data-type v1, v2, …., vn;
where v1, v2, …., vn are names of variables
• Variables are separated by commas
• Declaration statement must end with a semi-
colon
• Egs:
int count;
int number, total;
double ratio;
Assigning values to variables
• Values can be assigned to variables by using
the assignment operator =
variable-name = constant;
• Egs:
initial_value = 0;
final_value = 100;
Balance = 75.84;
yes = ‘x’;
Assignment statement
• Multiple assignments in one line are permitted
initial_value=0; final_value=100;
• Assignment statement implies that the value of
the variable on the left of = sign is set equal to
the value of the quantity (or expression) on the
right side of the = sign
year = year + 1
means that ‘new value of year equals old value of year+1
Assignment statement
• Also possible to assign a value to a variable when it is
declared.
data-type variable_name = constant;
– Egs:
int final_value=100;
char yes = ‘x’;
double balance = 75.84;
• It is possible to initialise more than one variable in one
statement by using multiple assignment operators
p = q = r = 0;
x = y = z = MAX;
Declaring variable as a constant
• Sometimes it is necessary to have variables
whose value does not change during the
program.
• Can be done by using the keyword const, for
eg:
const int class-size=40;
Declaring a variable as volatile
• If a variable value should be allowed to be changed
anytime from outside the program, the keyword
volatile is used
• Eg:
volatile int date;
• This allows the value of date to be changed by external
factors. Here, value of date can also be changed from
inside the program.
• If a variable value should be allowed to be changed
only by external factors, but not by its own program ,
then,
const volatile int date;
User defined type declaration
• This is called as type definition
• Allows user to define an identifier that represents an
existing datatype (like an alias or nickname)
– This can be used later to declare variables
typedef type identifier
– where type refers to existing datatype and identifier refers to
the ‘new’ name given to datatype
• Egs:
typedef int units;
typedef float marks;
Can be used later to declare variables, as shown below
units batch1, batch2;
marks name1[50], name2[50];
Enumerated datatype
• This is another user-defined datatype
• Defined as follows
enum identifier {value1, value2, ….valuen};
• Identifier is a user-defined datatype that is used to declare variables
that can have one of the values value1, value2,… valuen
• Declaration is as follows
enum identifier v1, v2, v3;
• Egs:
enum day {Monday, Tuesday, ….., Saturday};
enum day week_start, week_end;
week_start = Monday;
week_end = Friday;
• Definition and declaration can be combined into one statement
enum day {Monday, Tuesday,…, Saturday} week_start, week_end;
Defining Symbolic constants
• Constants are values that should not change
during a program.
• Two ways of defining constants
– Using const keyword
const float pi = 3.1412;
– Using #define pre-processor directive
#define PI 3.1412
Symbolic constants
• Constants are often used in programs
• They may appear repeatedly at various points in a
program
– Egs: pi (3.142) or no_of_students (50)
• Two problems may arise
– Modifiability : we may want to change pi to 3.14159 to
increase accuracy, then it has to be done at all points in the
program
– Understandability : numeric constants may be used in
different parts, but it becomes difficult to make out its
meaning. Eg – 50 may mean student strength in one part,
but may mean passing marks at another point. Hence
there is need to define each with a specific symbolic name
Symbolic constants
• Use the following syntax
#define symbolic-name value of constant
• Egs:
#define STRENGTH 50
#define PASS-MARKS 40
#define PI 3.14159
• Symbolic names are also called as constant
identifiers
• Symbolic names are not variables, and hence do
not appear in declarations
Rules for defining symbolic constants
1. All rules that apply to variables also apply to symbolic name.
Generally symbolic names are written in CAPTIAL LETTERS, to
distinguish them from the normal variable names.
2. No blank space between # and define is allowed.
3. # must be the first character in the #define statement.
4. A blank space is required between #define and the symbolic name
and between symbolic name and the value.
5. #define statements must not end with a semi-colon.
6. After declaring a symbolic constant, we must not use it in an
assignment statement.
7. Symbolic names are not declared for data types. Its data type
depends on the type of the constant value.
8. #define statements may appear anywhere in the program, but
before they are referenced in the program. Generally they are
placed at the top of the program after the #include statements.
What’s wrong here?
• #define X = 2.5
• # define MAX 10
• #define N 25;
• #define N 5, M 10
• #Define ARRAY 11
• #define PRICE$ 100
stdio.h
• Each C program that uses a standard input or
output function must contain the statement
#include<stdio.h>
• stdio.h means the standard input output header
file.
• It contains the C object code for all the input and
output functions that C supports
• Standard input device is usually the keyboard and
the standard output device is the monitor(screen)
Reading data from the keyboard
• Formatted input
• Another way of giving values to variables is to input data
through the keyboard.
• Can be done using the scanf function as follows:
scanf (“control string”, &variable1, &variable2, …);
• Control string contains the format of data being input.
– Can contain field specification made up of % symbol, datatype
character (d, f, c, s) and optional number for width
• The & symbol before each variable name is an operator that
specifies the variable name’s address.
• For eg:
scanf(“%d”, &number);
scanf(“%2d %4d”, &num1, &num2);
scanf(“%f %d %lf”, &average, &total, &accuracy);
Printing a message to screen
• Formatted output
• It is necessary for a program to display messages or give results to
the user
• This can be done by using the printf function as follows:
printf(“prompt message”);
or
printf(“prompt message/control string”, variable names);
or
printf(“control string”, variable names);
• Prompt message can be anything that should be displayed on
screen.
• Control string should be specified if values of variables need to be
printed.
• Both scanf and printf functions are defined as a part of C language,
hence the #include<stdio.h> directive is not necessary
Formatted output
• Egs
printf(“Enter a number”);
printf(“The value of sum is %d”, sum);
printf(“%d + %f = %f”, n1, n2, sum);
printf(“Sum of %d and %d is %d”, a, b, sum);
printf(“%d”, n1);
Adding two numbers
1. Start
2. Get the first number, n1
3. Get the second number, n2
4. Perform Sum = n1+n2
5. Display/Print Sum.
6. Stop
Addition of two numbers
/* Program to add two numbers n1 and n2*/
#include<stdio.h>
int n1, n2, sum=0;
main()
{
printf (“Enter first number n1”);
scanf(“%d”, &n1);
printf(“Enter second number n2”);
scanf(“%d”, &n2);
sum = n1 + n2;
printf(“addition of %d and %d results in %d”, n1, n2, sum);
}
Program to swap two numbers
Given the radius, find area and
circumference of a circle
Factorial of a given number
Given n, generate Fibonacci sequence
till n
Program to read a number, find the sum of the digits,
reverse the number and check it for palindrome
Read numbers from keyboard continuously till the user
presses 999 and to find the sum of only positive
numbers
Remove Duplicate Element in a list
Program to find simple interest
Reading a character
• getchar()
• Used for reading a character from keyboard and
displaying on the screen
variable = getchar();
• Variable should be declared as a char
• The program waits until a character is entered
using the keyboard, and once this is done, it
stores the value of the character in the variable
char name;
name = getchar();
Character test functions
• These are inbuilt functions to test characters
• All these are part of ctype.h header file
isalnum(c) is c an alphanumeric character?
isalpha(c) is c an alphabet?
isdigit(c) is c a digit?
islower(c) is c a lowercase character?
isprint(c) is c a printable character?
ispunct(c) is c a punctuation mark?
isspace(c) is c a whitespace character?
is upper(c) is c an uppercase character?
#include<stdio.h>
#include<ctype.h>
char c;
main()
{
printf(“Enter a character”);
c = getchar();
if (isalpha(c)) then
printf(“The character is an alphabet”);
else
printf(“The character is not an alphabet”);
}
Writing a character
• putchar()
• Used for displaying characters one at a time on
the screen
putchar(variable_name);
• variable_name is of datatype char and contains a
character
• The program displays a character on the screen
char name;
name = getchar();
putchar(name);
Reading a string
• gets()
• Used for reading a string from keyboard and displaying
on the screen
gets(variable);
• Variable should be declared as a multi-character string
• The program waits until a string is entered using the
keyboard, and once this is done, it stores the value of
the string in the variable
char name[25];
gets(name);
Writing(printing) a string
• puts()
• Used for displaying a string on the screen
puts(variable);
• Variable should be declared as a multi-character
string
• The program displays a string on screen
char name[25];
gets(name);
puts(name);
Inputting data using scanf()
• Integer % d, eg “%d %3d”
• Float %f eg “%f, %5.2f”
• Char %c, %s eg “%c %s”
Commonly used format codes
• %c read single character
• %d read a decimal integer
• %e read a floating point value
• %f read a floating point value
• %g read a floating point value
• %h read a short int
• %l read a long int or double
• %L read a floating point value
• %i read decimal, hexadecimal or octal int
• %o read an octal int
• %s read a string
• %[..] read a string
• %u read an unsigned decimal int
Find the roots of quadratic equation
Read marks scored by a student and find
the average of marks

You might also like