0% found this document useful (0 votes)
2 views

module 1_part 2 (1)

The document provides an introduction to the C programming language, detailing its history, advantages, and fundamental concepts such as programming structure, algorithms, and data types. It covers essential elements like tokens, keywords, identifiers, constants, and the structure of a C program, including comments, preprocessor directives, and function definitions. Additionally, it explains the significance of algorithms and flowcharts in programming, along with the classification of data types and their sizes.

Uploaded by

Firelord Nayo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

module 1_part 2 (1)

The document provides an introduction to the C programming language, detailing its history, advantages, and fundamental concepts such as programming structure, algorithms, and data types. It covers essential elements like tokens, keywords, identifiers, constants, and the structure of a C program, including comments, preprocessor directives, and function definitions. Additionally, it explains the significance of algorithms and flowcharts in programming, along with the classification of data types and their sizes.

Uploaded by

Firelord Nayo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

C Programming for Problem Solving Module1

APTER-2
INTRODUCTION TO C LANGUAGE
C
H
Introduction to C
 C was evolved from ALGOL,BCPL, and B by Dennis Ritchie at the Bell laboratories.
 C is a general-purpose programming language developed by Dennis Ritchie at AT&T
Bell laboratories in 1972.
Advantages/Features /Characteristics of C Language
C language is very popular language because of the following features:
1. C is highly portable, which means program written for one computer can be run on
another with little or no modification.
2. C is structured Programming Language as the code can be organized as a
collection of one or more functions.
3. It is considered a high-level language because it allows the programmer to solve a
problem without worrying about machine details.
4. It has wide variety of operators using which a program can be written easily to solve
a given problem.
5. C is more efficient which increases the speed of execution and management of
memory compared to low level languages.
6. C is machine independent. The program written on one machine will work on
another machine.
7. C can be executed on many different hardware platforms.

1.1 Programming Concepts


 Program: A program is a group of instructions given by the programmer to perform a
specific task.
 These instructions are formed using symbols and words according to syntax rules.
1.2 Character set of C language
 Definition: A symbol that is used while writing a program is called a character.
 A character can be: .
 Alphabets/Letters (Lowercase a-z, Uppercase A-Z)
 Digits (0-9)
 Special Symbols ( ~ ‘ ! @ # % & * () - + / $ = \ {
} [ ] : ; “ “ ? etc)
 White spaces
 The entire character set is given in below table:

Alphabets/Letters (Lowercase a-z, Uppercase A-Z)


Digits (0-9)

Page 1
C Programming for Problem Solving Module1
1

White spaces

Sy Name Sym Name Sym Name
mb Bol bol
~ Tilde | [ Left bracket
Vertical bar
# Hash ( Left ] Right bracket
parenthesis
$ Dollar sign ) Right : Colon
parenthesis
% Percent _ Underscore ” Quotation
Sign mark
^ Caret + Plus sign ; Semicolon

& Ampersand { Left brace < Less than

* Asterisk } Right brace > Greater than

‘ Single . dot = Assignment


Quote


1.2 Structure of C Program
Comments/Documentation Section /* program to print a message */
Preprocessor Directives #include<stdio.h>
Global declaration section
Function declaration
void main( ) [Program Header] void main( )
{ {
Declaration part printf(“ good morning\n”);
Execution part
} }

User defined Functions


Function 1
Function 2

Comments/Documentation Section
 Comments are short explaining the purpose of the program or a statement.
 They are non executable statements which are ignored by the compiler.
 The comment begins with /* and ends with */.
 The symbols /* and */ are called comment line delimiters.
 We can put any message we want in the comments.
Example: /* Program to compute Quadratic Equation */
Note: Comments are ignored by C compiler, i.e. everything within comment delimiters
Page 2
C Programming for Problem Solving Module1
1

 Preprocessor Directives
 Preprocessor Directives begins with a # symbol
 Provides instructions to the compiler to include some of the files before compilation
starts.
 Some examples of header files are
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <math.h>
#include<stdlib.h> Etc…

Page 3
C Programming for Problem Solving Module1
1

 Global Declaration Section


 There will be some variable which has to be used in anywhere in program and used in
more than one function which will be declared as global.
 The Program Header
 Every program must contain a main() function.
 The execution always starts from main function.
 Every C program must have only one main function.
 Body of the program
 Series of statements that performs specific task will be enclosed within braces { and
}
 It is present immediately after program header.
It consists of two parts
1. Local Declaration part: Describes variables of program
Ex:int sum = 0;
int a , b:
float b;
2. Executable part: Task done using statements.
All statements should end with semicolon(;)

Subroutine Section: All user defined functions that are called in main function should be
defined.
1.3 Algorithm
 It is a step by step procedure to solve a problem
 A sequential solution of any problem that is written in natural language.
 Using the algorithm, the programmer then writes the actual program.
 The main use of algorithm is to help us to translate English into C.
 It is an outline or basic structure or logic of the problem.
Characteristics of Algorithm
 Each and every instruction must be precise and unambiguous
 Each instruction execution time should be finite.
 There should be a termination condition.
 It has to accept 0 or more inputs and produce compulsory an output.
 It can accept any type of input and produce a corresponding output.
General Way of Writing the Algorithm
 Name of the algorithm must be specified.
 Beginning of algorithm must be specified as Start
 Input and output description may be included
 Step number has to be included for identification
 Each step may have explanatory note provided with in square bracket followed by
operation.
 Completion of algorithm must be specified as end or Stop.

Ex 1: Write an algorithm to add two numbers

Page 4
C Programming for Problem Solving Module1
1

Algorithm: Addition of two numbers


Input: Two number a and b
Output: Sum of two numbers
Step 1: Start
Step 2: [input two number]
Read a and b
Step 3: [compute its addition]
Sum = a + b
Step 4: print Sum
Step 5: Stop
Ex 2: Write an algorithm to compute simple interest
Algorithm: To find Simple Interest
Input: p, t, r
Output: SI
Step 1: Start
Step 2: [input a principle p, time t and rate r]
Read p, t, r
Step 3: [compute simple interest]
SI  (p*t*r)/100
Step 4: display SI
Step 5: Stop
Flow charts
 A flowchart is a pictorial or graphical representation of an algorithm or a program.
 It consist of sequences of instructions that are carried out in an algorithm.
 The shapes represent operations.
 Arrows represent the sequence in which these operations are carried out.
 It is mainly used to help the programmer to understand the logic of the program.

Notations used in flowchart

Shape Name Meaning


Used to denote start and stop of
Start and Stop
Flowchart
Parallelogram used to read input and
Input and Output
display output
Rectangle used to include instructions or
Processing/computation
processing statements
To include decision making statements
Decision/ Condition
rhombus is used
Connector Join different flow chart or flow lines
Repetition/ Loop Hexagon is used for looping constructs

Page 5
C Programming for Problem Solving Module1
1

To include functions in a program, the


Functions name of function should be enclosed
with in the figure

Arrows denoting flow of control in flow


Control Flow Lines
chart

For including the comments, definition


Comment box
or explanation

Ex 1.Algorithm and Flowchart to Input the dimensions of a rectangle and print its area

Step 1: Start
Step 2: [input the values of length
and breadth]
read length, breadth
Step 3: [Compute ‘area’]
area=length * breadth
Step 4: display area
Step 5: Stop

Page 6
C Programming for Problem Solving Module1
1

1.4 C Tokens

 Tokens are the smallest or basic units of C program.


 One or more characters are grouped in sequence to form meaningful words. These
meaningful words are called as tokens.
 A token is a collection of characters.
 Tokens are classified in to 5 types as below:

C Tokens

strings

Page 7
C Programming for Problem Solving Module1
1

1.4.1 Keywords
 The tokens which have predefined meaning in C language are called keywords.
 They are reserved for specific purpose in C language they are called as Reserved
Words.
 There are totally 32 keywords supported in C they are:
auto Double if static
break Else int struct
case Enum long switch
char Extern near typedef
const Float register union
continue For return unsigned
default Volatile short void
do Goto signed while
Rules for keywords
1. Keywords should not be used as variables ,function names, array names etc.
2. All keywords should be written in lowercase letters.
3. Keywords meaning cannot be changed by the users.
1.4.2 Identifiers
Definition:
 Identifiers are the names given to program elements such as variables, constants
,function names, array names etc
 It consists of one or more letters or digits or underscore.
Rules for identifiers
1. The First character should be an alphabet or an underscore _
Then First character is followed by any number of letters or digits.
2. No extra symbols are allowed other than letters ,digits and Underscore
3. Keywords cannot be used as an identifier
4. The length can be 31 characters for external, 63 for internal.
5. Identifiers are case sensitive.
Example: Area, Sum_

Ex:-
Identifier Reasons for invalidity
india06 Valid
_india Valid
india_06 Valid
india_06_king Valid

06india not valid as it starts from digits


int not valid since int is a keyword

Page 8
C Programming for Problem Solving Module1
1

india 06 not valid since there is space between india and


06
india@06 not valid since @ is not allowed

1.2.3 Constants
 Definition: Constants refers to fixed values that do not change
during the execution of a program.

 The different types of constants are:


1. Integer constant
2. Real constant/Floating Pointing constant
3. Character constant
4. String constant
1. Integer constant
 Definition: An integer is whole number without any decimal point.no extra characters
are allowed other than + or _.
 Three types of integers namely:
Decimal integers Octal integers Hexadecimal integers
The integer constants with The integer constants Digits from 0 to 9 and
a combination of digits 0 to with a combination of characters from a/A to f/F it
9,optional + or - Digits from 0 to 7 but it has to start with 0X or 0x
Ex: 123 , -345, 0 , 5436 , has a prefix of 0 Ex: 0X2 0x56 0X5fd
+79 Ex: 027 , 0657 , 0xbdae
0777645

2. Real constants/Floating point:


 Integer numbers are inadequate to represent quantities that vary continuously such as
distances ,heghts,temperatures,prices.
 These quantities are represented by fractional parts, such as 10.5.They are called real
or floating point constants.

Page 9
C Programming for Problem Solving Module1
1

 Two forms are:


Fractional form:
 A floating point number represented using fractional form has an integer part
followed by dot and a fractional part.
 Ex: 0.0083
 215.5
 -71.
 +0.56 etc..
Exponential form:
 A floating point number represented using Exponent form has 3 parts :
MANTISSA E EXPONENT

 Mantissa is either real number expressed in decimal notation or integer.


 Exponent must be integer with optional + or –
 Ex: 7500000000 may be written as 75E8 or 7.5E9
 9.86 E 3 => 9.86*103
 9.86 E -3 => 9.86*10-3
3. Character constant
 A symbol enclosed within pair of single quotes is called character constant.
 Each character is associated with unique value called ASCII value.
 Ex: ‘9’ ,‘$’ , ’5’ , ‘;’
4 . String constant
 A sequence of characters enclosed within pair of double quotes is called string
constant.
 The characters can be letters,numbers,special characters and blank spaces.
 The string always ends with a NULL character.
 Ex: “9” , “SVIT” , “GOOD …….MORNING” , ”5+3= ”
Backslash constants(Escape sequence character)
 Definition: An escape sequence character begins with backslash and is followed by
one character.
 A backslash along with a character give rise to special print effects.
 It always start with backslash ,hence they are called as backslash constants.
character name Meaning

\a Bell Beep sound

\b Backspace Cursor moves towards left by one


Position
\n Newline Cursor moves to next line

\t Horizontal tab Cursor moves towards right by 8


Position
\r Carriage return Cursor moves towards beginning of the
same line

Page 10
C Programming for Problem Solving Module1
1

\” Double quotes Double quotes

\’ Single quotes Single quotes

\? Question mark Question mark

\\ Backslash Backslash

\0 NULL

1.3 Data types and sizes


 Definition: The data type defines the type of data stored in memory location or the type
of data the variable can hold.
 The classification of data types are:

 There are few basic data types supported in C.


1. int
2. float
3. double
4. char
5. void
1. Integer data type (int):
 It stores an integer value or integer constant.
 An int is a keyword using which the programmer can inform the compiler that the
data associated with this keyword should be treated as integer.
 C supports 3 different types of integer:
 short int,
 int,
 long int
n-bit Type size Range of unsigned Range of signed int
machine int be -2n to +2n -1
0 to 2n-1
Page 11
C Programming for Problem Solving Module1
1

16- bit short int 2 bytes 0 to 216-1 -215 to +215 -1


machine 0 to 65535
-32768 to +32767

Int 2 bytes 0 to 216-1 -215 to +215 -1


0 to 65535
-32768 to +32767

long int 4 bytes 0 to 232-1 -231 to +231 -1


0 to 4294967295 -2147483648 to
+ 2147483647
2. Floating data type (float):
 An float is a keyword using which the programmer can inform the compiler that the
data associated with this keyword should be treated as floating point number.
 The size is 4 bytes.
 The range is -3.4e38 to +3.4e38.
 Float can hold the real constant accuracy up to 6 digits after the decimal point.
3. Double data type (double):
 An double is a keyword using which the programmer can inform the compiler that the
data associated with this keyword should be treated as long floating point number.
 The size is 8 bytes.
 The range is from 1.7e-308 to 1.7 e+308.
 Double can hold real constant up to 16 digits after the decimal point.
4. Character data type (char):
 char is a keyword which is used to define single character or a sequence of character
in c language capable of holding one character from the local character set.
 The size of the character variable is 1 byte.
 The range is from -128 to +127.
 Each character stored in the memory is associated with a unique value termed as
ASCII (American Standard Code for Information Interchange).
 It is used to represent character and strings.
n-bit Type size Range of unsigned Range of signed
machine char char
n
0 to 2 -1 be -2n to +2n -1
16- bit short int 2 bytes 0 to 28-1 -27 to +27 -1
machine 0 to 255
-128 to +127

5. void data type (void):


 It is an empty data type.
 No memory is allocated.
 Mainly used when there are no return values.
1.4 variable
 A variable is a name given to memory location where data can be stored.

Page 12
C Programming for Problem Solving Module1
1

 Using variable name ,data can be stored in a memory location and can be accessed or
manipulated very easily.
 A variable may take different values during the execution of the program.
 A variable name can be chosen by a programmer in a meaningfull way.
Rules for variables
 The First character should be an letter(alphabet or an underscore _ )
 Then First character is followed by any number of letters or digits.
 No extra symbols are allowed other than letters ,digits and Underscore
 Keywords cannot be used as an identifier
 Case sensitive
 White space is not allowed
 Example:
Variables Valid /invalid Reason
Sum valid
For1 valid
distance valid
Sum1 valid
For invalid (it is a keyword)
123 invalid Cannot start with a digit

(area) invalid Special characters are not allowed

Declaration of variables:
 Giving a name to memory location is called declaring a variable.
 Reserving the required memory space to store the data is called defining a variable.
General Syntax of variable declaration :
datatype variable;
Example: int a; Syntax
double ratio;
datatype variable1, variable2,… ..... variable n;
Example: float x, y;

 From the above examples “a” is a variable of type integer and allocates 2 bytes of
memory. “
 x” and “y” are two variable of type float which will be allocated 4 bytes of memory for
each variable.
 “ratio” is a double data type variables which will be allocated with 8 bytes of memory
for each.
Variable Initialization/Assigning values to variables
 Variables are not initialized when they are declared and defined, they contain garbage
values(meaningless values)
 The method of giving initial values for variables before they are processed is called
variable initialization.

Page 13
C Programming for Problem Solving Module1
1

General Syntax:
Variable_name = constant;
Variable_name = expr;
Where,
 Var_name is the name of the variable given by the programmer ,
 expr is the value of the expression.
 The “expr” on the right hand side is evaluated and stored in the variable name (Var_name) on left
hand side.
 The expression on the right hand side may be a constant, variable or simple expressions . Examples:
int a=10; // assigns the value 10 to the integer variable a
float x; // creates a variable y of float type and assigns value 20 to it.
x=20;
price = cost*3; //assigns the product of cost and 3 to price.
sum=sum+2; // assigns the sum +2 value to sum variable

Formatted input /output statements


The function which is used to give the value of variable through keyboard is called input
function. The function which is used to display or print the value on the screen is called output
function.
Note : - In C language we use two built in functions, one is used for reading and another is used
for displaying the result on the screen. They are scanf() and printf() functions. They are stored in
the header file named stdio.h.
General format for scanf( ) function
scanf(“control string”, &variable1, &variable2,……)
The control sting specifies the field format in which the data is to be entered.
%d –integer
%f – float
%c- char
%s – string
% ld – long integer
%u – Unsigned Integer
Example:
scanf(“%d”,&x) – reading an integer value, the value will be stored in x
scanf(“%d%f”,&x,&a) - reading a integer and a float value In the above scanf ( ) function , we
don’t use any format. This type of Input is called as the Unformatted Input function.
C Programming for Problem Solving Module1
1

Formatted Input of Integer

The field speciation for reading the integer number is:


%wd
Where The percentage sign(%) indicates that a conversion specification follows. w – is
the field width of the number to be read. d will indicates as data type in integer number.
Example:
scanf(“%2d %5d”,&num1,&num2);
data line is 50 31425
the value 50 is assigned to num1 and 31425 is assigned to num2. suppose the input data is as
follows,
31425 50 , then the variable num1 will be assigned 31 and num2 will be assigned to 425 and
the 50 is unread.
An input field may be skipped by specifying * in the place of field width.
Example the statement scanf(“%d %*d %d),&a,&b); will assign the data 123 456 789
as follows: 123 is assigned to a , 456 skipped because of * and 789 to b

Output Function : To print the value on the screen or to store the value on the file, the output
functions are used. printf() is the function which is use to display the output on the screen.
The General format of the printf() function is

printf(“control string”,variable1,variable2,…..);
Example

printf(“%d”,x) – printing the integer value x.


printf(“%d%f”, x,a)- printing a integer and float value using a single printf function.

Formatted Output of Integer :Similar to formatted input , there is a formatted output also to have the
output in a format manner.
In this control string consists of three types of items.
 Characters that will be printed on the screen as they appear
 Format specification that define the output format for display of each item
 Escape sequence characters such as
\n – new line
C Programming for Problem Solving Module1
1

\b – back space
\f – form feed
\r – carriage return
\t - horizontal tab
\v – vertical tab
The format speciation is as follows
%wd
Where w – is the field width of the number to be write . d will indicates as data type in
integer number.
Examples:
Printf(“%d”,9876); // output:
9876

printf(“%6d”,19876);
output:
1 2 3 4 5 6
1 9 8 7 6

printf(“%-6d”,9876);
output:
1 2 3 4 5 6
9 8 7 6

printf(“%06d”,9876);
output:
1 2 3 4 5 6
0 0 9 8 7 6

Formatted input of Real(float) Numbers:


. The field speciation for reading the real number is:
%w.pf
Where w – is the field width of the number to be read . p indicates the number of digits
to be read after the decimal point f – indicates that data type in float(real) number.
C Programming for Problem Solving Module1
1

Example
scanf(“%2.1f %5.2f”,&num1,&num2);
data line is 50.1 31425.20

the value 50.1 is assigned to num1 and 31425.20 is assigned to num2. An


input field may be skipped by specifying * in the place of field width.
Example: the statement scanf(“%f %*f %f), &a,&b); will assign the data 12.3 4.56
78.9 as follows: 12.3 is assigned to a , 4.56 skipped because of * and 78.9 to b.
C Programming for Problem Solving Module1
1

Formatted output of Real(float) Numbers:


The field speciation for reading the real number is:
%w.pf
Where w – is the field width of the number to be read . p indicates the number of digits
to be displayed after the decimal point f – indicates that data type in float(real) number.
Example:
Float y = 98.7682
Printf(“ %f ”, y); // output:
98.7682

printf(“%7.2f ”,y);

output:
1 2 3 4 5 6 7
9 8 . 7 6

printf(“%-7.2f ”,y);

output:
1 2 3 4 5 6 7
9 8 . 7 6

Formatted input of Single characters or strings:

The field speciation for reading the character / strings:


%ws or %wc
where,
%c is used to read a single character.
%s is used to read a sequence of characters / a string
%c – can accept only 1 character
%s – can accept series of characters
C Programming for Problem Solving Module1
1

Example:
Char name;
Scanf(“%c”, &name); \\ I / P : a
Char name[20];
Scanf(“%s”,&name); \\ I / P : sathyabama

Printing of a Single Character:


The field speciation for reading the character strings:
%ws or %wc

where,
%s – A sequence of characters can be displayed.
%c – A single character can be displayed.
The character will be displayed right-justified in the field of w, left-justified by placing
a minus sign before the integer w.
Example:
Char x = ‘a’;
Char name[20] = “anil kumar gupta”;
Printf(“%c”, x); // output: a
Printf(“%s”,name); // output: anil kumar gupta
Printf(“%20s”, name);
Output:
1 2 3 4 5 6 6 8 9 10 11 12 13 14 15 16 17 18 19 20
a N I l k U m A R g u p t A

Printf(“%-20.10s”, name);
Output:
1 2 3 4 5 6 6 8 9 10 11 12 13 14 15 16 17 18 19 20
A N I l K U m A r
C Programming for Problem Solving Module1
1

Unformatted Input/Output functions –

getchar() –
putchar() –
getch() –
putch() –
gets() –
puts()

getchar()
 This function reads a character-type data from standard input.
• It reads one character at a time till the user presses the enter key.
Example: char c; c = getchar();
Syntax Variable-name = getchar

#include
void main()
{
char c;
printf(“enter a character”);
c=getchar();
printf(“c = %c ”,c);
}

putchar()
This function prints one character on the screen at a time which is read by standard input.
Example: char c= ‘c’; putchar (c);

#include
void main()
{ char ch;
printf(“enter a character: ”);
scanf(“%c”, ch);
putchar(ch);
}
getch() & getche()
These functions read any alphanumeric character from the standard input device
 The character entered is not displayed by the getch() function until enter is pressed
C Programming for Problem Solving Module1
1

 The getche() accepts and displays the character.


 The getch() accepts but does not display the character.
Syntax getche();

putch()
This function prints any alphanumeric character taken by the standard input device Example:
#include
void main()
{
char ch;
printf(“Press any key to continue”);
ch = getch(); printf(“ you pressed:”);
putch(ch);
}
gets() String I/O
This function is used for accepting any string until enter key is pressed (string will be covered later) Syntax char
str[length of string in number];
gets(str);

#include
void main()
{
char ch[30];

printf(“Enter the string:”);


gets(ch);
printf(“Entered string: %s”, ch);
}

puts()
This function prints the string or character array. It is opposite to gets()
Syntax char str[length of string in number]; gets(str); puts(str);

1.6 Format Specifiers


 Format specifiers are the character string with % sign followed with a character.
 It specifies the type of data that is being processed.
 It is also called conversion specifier or conversion code.
 There are many format specifiers defined in C.
C Programming for Problem Solving Module1
1

Symbols Meaning

%d Decimal signed integer number

%f float point number

%c Character
%o octal number

%x hexadecimal integer(Lower case letter x)

%X hexadecimal integer(Upper case letter X)

%e floating point value with exponent(Lower case letter e)

%E floating point value with exponent (Upper case letter E)

%ld long integer

%s String

%lf Double

Input Function ( scanf) Inputting Values Using


scanf
 To enter the input through the input devices like keyboard we make use of scanf statement.
General Syntax:
scanf(“format string”, list of address of variables);
 Where: Format string consists of the access specifiers/format specifiers.
 Format string also called as control string.
 Format string consist of format specifier of particular data type
 Format specifiers starts with % sign followed by conversion code.
 List of addresses of variables consist of the variable name preceded with & symbol(address
operator).
Example: int a; float b;
scanf(“%d%f”,&a,&b);

Rules for scanf


 No escape sequences or additional blank spaces should be specified in the format specifiers.
 Ex: scanf(“%d %f”,&a,&b); //invalid
scanf(“%d\n%f”,&a,&b); //invalid
& symbol is must to read the values, if not the entered value will not be stored in the variable specified. Ex:
scanf(“%d%f”,a,b);//invalid.
C Programming for Problem Solving Module1
1

Page 23

You might also like