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

Mod1 CS

Uploaded by

Shruthi Iyer
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Mod1 CS

Uploaded by

Shruthi Iyer
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 86

C PROGRAMMING FOR PROBLEM

SOLVING
MVJ21CS13
MODULE

Prepared by:
POSHITHA.M
ASP, Dept. of CSE,
MVJCE, Bangalore
UNIX SYSTEM
1) Creating the program
2) Compiling and linking
3) Executing the program
• Executing the program
 It’s a simple task
 a.out would load the executable object code into the
computer memory and execute the instructions
 During the program user inputs are required and
output is produced
 Sometime if no output then programlogic is wrong
 check the errors in the source code. After that again
compiling,linking and executing will be repeated.
Creating your own executable file
1) Linker will assign the same name a.out when we compile
the other program
2) That object code will be overwritten by the other executable
object code.
3) If we want to prevent from happening
4) Rename the file immediately by using the command
mv a.out file1
suppose you have written the prg in hello.c file
Compiling command is cc hello.c
Executable form object code is created and stored in a.out
Now again if u create the calci.c file and compile it with cc
calci.c then a.out file will be overwritten.
Creating your own executable file

•You can archieve this by specifying an option in the cc


command as follows
cc –o file1 sourcefile
•This will store the executable object code in the file (file1)
and prevent the old file a.out from being destroyed
Multiple source files
•To compileand link multiple source programs files, we must
append all the files names to cc command
Cc filename1.c,filename2.c,filename3…………filenamen.c
•These files will be separetly compiled into object file called
Filename1.o,filename2.o……filenamen.o
•And the linked to produce an executable prog file a.out
•Is is also possible to compile each file separetly and link them
alter
cc –c mod1.c
cc –c mod2.c
•This will compile the source files mod1.c and mod2.c into object
file mod1.0 and mod2.o

•Then they can be linked together by the command


cc mod1.o mod2.o
• we may also combinethe source files and object filesas follows
cc mod1.c mod2.o
Only mod1.c is complied and then linked with the object file
mod2.0
MS-DOS SYSTEM
• The program can be created using any word processing software
in non document mode
• The file name should end with the c
• Ex MSC PAY.C
• MS-DOS operating system will load the program in the file
pay.c and generate object code pay.obj and error then
compilation not completed
• Linking LINK pay.obj
• Executing Executable code with the filename pay.exe
• Execute the program and gives the results
QUIZ SESSION
State true or false
1) Every line in a C program should end with a semicolon
2) The closing brace of the main() in a program is the logical
end of the program
3) Comments cause the computer to print the text enclosed
netween /* and */ when executed
4) Every c program ends with an END word
5) A printf statement can generate only one line of output
6) the purpose of the header file such as stdio.h is to store the
source code of a program
7) A line in a program may have more than one statement
8) Syntax errors will be detected by the computer
9) In C language lowercase letters are significant
10) The main() is where the program begins its execution
QUIZ SESSION
1) Every c program must have at least one user defined function
2) Declaration section contains instructions to the computer
3) Only one function may be named main()
4) Comments serve as internals documentation for programmers
5) Use of comments reduces the speed of execution of a program
6) A comment can be inserted in the middle of the statement
7) The _____ function is used to display the output on the screen
8) The____ header file contains mathematical functions
9) The escape sequence character ___ cause the cursor to move
to the next line on the screen
End of UNIT 2
UNIT 3
CONSTANTS ,VARIABLES AND DATATYPES

• A programming language is designed to help process certain


kinds of data consisting of numbers,character and strings and to
provide useful output knows as information.
• The task of processing of data is accomplished by executing a
sequence of precise instructions called a program.
• These instructions are formed using certain symbols and words
according to some rigid rules known as syntax rules
• Every program instruction must confirm precisely to the syntax
rules of the language
• C has its own vocabulary and grammer
CHARACTER SETS
The character that can be used to form words, numbers and
expressions depend upon the computer on which the program
is running
The computer in c are group into following categories
1) Letters
2) Digits
3) Special characters
4) White spaces
The compiler ignores whitespace unless they are a part of
string constant
CHARACTER SETS
• Whitespace may be used to separate words, but are prohibited
between characters of keywords and identifiers
• Letters
1) uppercase A-Z
2) lowercase a-z
• Special characters , . ; : ? ‘ ‘’ ! | / \ ~ _ $ % & ^ * - + < > { }
()[]#
• Whitespace
• Blankspace , horizontal tab, carriage return, new line, form
feed.
TRIGRAPGH CHARACTERS
• Many non english keyboards do not support all the characters
mentioned
• ANSI c introduced a concept of “trigraph “ sequences to provide
a way to enter certain characters that are not available on some
keyboards
• Each trigraph consists of three characters
• ??
• Another characters
• For example: if the keyboard doesn’t support the square barckets
[] , ??( and ??)
TRIGRAPH SEQUENCES
Trigraph sequences transalation

??= #number sign

??( [

??) ]

??< {

??> }

??! | vertical bar

??/ \ back slash


C TOKENS
• In a C prgram the smallest individuals units are known as C
tokens
• C has six types of tokens
• C program are written using these tokens and the syntax of the
language
C TOKENS
C tokens

Keywords Constants
(int,float) (-15.5,100)

Strings(“h Identifiers
ello”) (main amount)

Special
KEYWORDS AND INDENTIFIERS

• Every c word is classified as either a keyword or an


identifier
• All keywords have fixed meaning and these meaning
cannot be changed
• Keywords serve as a basic building blocks for
program statements
• All keywords must be written in lowercase
• int floar char case break
KEYWORDS AND INDENTIFIERS
auto double int struct
break else long switch
case enum register typedef
Char extern return union
Const float short unsigned
Continue for signed void
default goto sizeof volatile
Do if static while
IDENTIFIERS
• It refers to the name of variables function and arrays
• There are user-defined names and consist of a
sequence of letters and digits with a letter as a first
character
• Both uppercase and lowercase letters are permitted
• The underscore is also permitted
• The can used as a link between two words in long
identifiers
Rules for indentifiers

1) First character must be an alphabets


2) Must consist of only letters, digits or underscore
3) Only first 31 characters are significiant
4) Cannot use a keyword as indentifiers
Example:- int whilea,caseb;
5) Must not contain whitespace
avrg_height
CONSTANTS
Constants in C refer to fixed values that do
not change during the execution of a program
C supports several types of constants
1) Integer constant
2) Real constant
3) Single character constant
4) String constant
Ex:-CONST pi=3.14
CONSTANTS

Character constants
Numeric constant

Integer Real Single character


constants constants constants and string
constants
INTEGER CONSTANTS
• An integer constant refers to a sequence of digits
• There are 3 types of integers
1. Decimal integer
2. Octal integer
3. Hexadecimal integer
Decimal integer

 It consist of a set of digits from 0-9, preceded by an


optional – or + sign
 Example :-
1. 123
2. -321
3. 0
4. 654321
5. +78
Octal integer

 It consist of a any combination of digits from set


0-7, with a leading O
 Example :-
1. O 37
2. O
3. O435
4. O 551
Hexadecimal constant
•It is a sequence of digits preceded by ox or oX is
considered as hexadecimal integer.
•They may also include alphabets A through F or
• a through f
Example:-
1.ox2
2.ox9F
3.Oxbcd
4.ox
• The largest integer value that can be stored is machine
dependent
It is 16 bit machine 32767
It is 32 bit machine 2,147,483,647

It is also possible to store larger integer constants on


these machines by appending qualifiers such as U,L
and UL to the constants
•56789U or 56789u (unsigned integer)
•987612347UL or 987612347ul(unsigned long integer)
•9876543L or 9876543l (long integer)
REAL CONSTANTS

•Integer constants are inadequate to represent quantities that


vary continuously.
•Such as distances,heights,temperature,prices and so on
•These quantites are represented by numbers containing
fractional partls like 17.548
Examples:-
1) 0.0083
2) -0.75
3) 435.36
4) +247.0
REAL CONSTANTS

These numbers are shown in decimal notation , having a whole


number followed by a decimal point and the fractional part

It is possible to omit the digits before the decimal point, or digits


after the decimal point

Example:-
1) 215. 0.21500 .215
2) .95
3) -.71
4) +.5
MANTISSA e EXPONENT
• A real number can also be expressed in
exponential notation
• Example:- 215.65 = 2.1565e²
• e² means multiply by 10²
• The general form mantissa e exponent
• This mantissa is either a real number expressed
in decimal or an integer.
• The exponent for integer number will have an
optional plus or minus sign
MANTISSA e EXPONENT
• The letter e separating the mantissa and the exponent
can be written in either lowercase or uppercase
• Since the exponent causes the decimal point to “float”,
this notation is said to represent a real number in
floating point form
• Example:-
1) 0.65e4
2) 12e-2
3) 3.18E3
4) -1.2E-1
MANTISSA e EXPONENT
• Embedded whitespace is not allowed
• This is used for representing number that
either very large or very small in magnitude
• Example:-
1) 75000000000=7.5E9
2) -0.000000368=-3.68E-7
MANTISSA e EXPONENT
• 698354L
• 25,000
• -5.0E3
• 3.5e-5
• 7.1e 4
• -4.5e-2
• 1.5E+2.5
• $255
• ox7B
SINGLE CHARACTER CONSTANTS
• It contains the character enclosed within a
pair of single quote marks
• Example:-
• ‘5’ ‘p‘ ‘6’
• ’x’
• ’:’
• ’;’
• ’‘
• Character constants have integer value known as ASCII
values
• Printf(“%d”, ‘a’);
• Output 79
• Printf(“%c”, ‘97’);
• Output a
• Printf(“%d”, ‘z’);
• Output 122
• Printf(“%c”,’122’);
• Output z
STRING CONSTANTS
• It is the sequence of characters enclosed in
double quotes
• The characters can be numbers,special
characters and blankspace
• Example:- “hello”, “1998”, “?...1”, “X”
• Note “X” is not same as ‘x’
BACKSLASH CHARACTER CONSTANTS
• It is used in output functions
• They consist of two characters
\a Audible alert
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quote
\” Double quote
\? Question mark
\\ Backslash
\o null
VARIABLES
• A variable is a data name that may be used to
store a data value
• The variables remains unchanged during the
execution time
• A variable name can be chosen the
programmer in a meaningful way so as to
reflect its function in the program
• Ex:- sum,average,height,mod.
CONDITIONS
• They must begin with a letter _ is also
permitted in some system
• The length of a variable should not be more
than 8 characters avg_num; AVG_NUM;
• Uppercase and lowercase are significant
• It should not be a keyword
• Whitespace is not allowed
• John
• Delhi
• Sum1
• T_raise
• 123
• %
• (area)
• 25th
• float
• If only the first eight characters are recognised
by a compiler
• For example:-average_height
average_weight
• This both mean same thing to the computer so
rewritten as
• Avg_height and avg_weight
DATA TYPES
• C language is rich in its datatypes
• Storage representations and machine
instructions to handle constants differ from
machine to machine
• The variety of data types available allow the
programmer to select the the appropriate to the
needs of the application as well as machine
DATA TYPES
• ANSI C supoorts three classes of datatypes
1) Primary (or fundamental datatypes)
2) Derived datatypes
3) User-defined datatypes
DATA TYPES
• All C compliers support five fundamentals
datatypes namely
1) integer(int)
2) Character(char)
3) Floating point (float)
4) Double precision floating point (double)
5) Void (no return type)
Many of them also offer extended data types
such as long int and long double
Size and range of the data types
16 bit machines
Size and range of the data types
32 bit machines
INTEGER TYPES
• Integer are whole numbers with a range of
values supported by a particular machine
• Generally integers occupy one word of storage
and since the word sizes of machines vary
(16 to 32 bits)
• In order to provide some control over the
range of numbers and storage space
INTEGER TYPES
• C has three classes of integers storage namely
• Short int
• Int
• Long int
These integers are available in both signed and
unsigned forms
INTEGER TYPES
• For example:- short int represnts fairly small
integer values and requires half the amount of
storage as a regular int.
• Unlike signed integers use all the bits fir the
magnitude of the number and are always
positive
• Therefore the range of a unsigned integer
number in 16bit machine is from 0 to 65,535.
INTEGER TYPES
• We declare long and unsigned integers to
increase the range of values
• The use of qualifer signed on integers is
optional because the defaults declaration
assumes a signed number
FLOATING POINT TYPES
• Floating point (or real) numbers are stored in
32 bits (on all 16 bit & 32 bit machines) with 6
digits precisions
• Floating point numbers are defined in C by the
keyword float.
• When the accuracy provided by a float number
is not sufficient, the tyoe double can be used to
define the number.
FLOATING POINT TYPES
• A double data types number uses 64 bits
giving a precision of 14 digits
• These are known as double precision
numebers
• To extend the precision futher we may use
long double which uses 80bits
VOID TYPES
• The void type has no values
• This is usually used to specify the type of
functions
• The type of a function is said to be void when
it does not return any value to the calling
function.
• It can represent any of the other standard
types.
CHARACTER TYPES
• A single characters can be defined as a
character(char) type data
• Characters are usually stored in 8bits of
internal storage.
• The qualifer signed or unsigned may be
explicitly appiled to char
• While unsigned char have vslues 0 and 255
• Signedchars have values from -128 to 127
Declaration of variables
• After designing suitable variable names, we
must declare them to the complier
• It tells the complier what the variable name is
• It specifies what type of data the variable will
hold
• The declaration of variables must be done
before they are used in the program
Primary Type declaration
• A variable can be used to storea value of any
datatypes.
• Syntax:- datatype v1,v2…..vn;
• V1,v2…vn are the variables separted by commas
and it should end with a semicolon
• Valid declarations are
int count;
int number; total;
double ratio;
Primary Type declaration
• When an adjective short,long or unsigned is
used without basic datatypes specifier.
• C compiler treat the datatypesas an int.
• If we want to declare a character variable as
unsigned ,then we must do so using both the
terms like unsigned char.
Default values of constants
• Integers constants, by default represent int type
data. We can override this default by specifying
unsigned or long after the number by appending U
or L
• Floating point constants, by default represent
double type data.
• If we want the resulting data type to be float or
long double, we must append the letter f or F to the
number for float and letter l or L for long double
Defaults values of constants
User-defined type declaration
• C supports a feature known as “type
definition” that allows users to define an
identifer that would represent an existing data
type.
• The user defined data typeindentifer can later
be used to declare varaibles.
• It takes the general forms
typedef type identifer;
• Where type refers to an existing data type and
“identifers” refers to the “new” name given to
the data types.
• The existing data type may belong to any class
of type, including the user-defined ones.
• typedef int units;
• typedef float marks;
• Here units symbolizes int and marks
symbolizes float.
• They can be later used to declare variables as
follows:
• Units batch1,batch2;
• Marks name1[50],name2[50];
• Another user defined datatype is enumerated
data type provided by ANSI standard.
• It is defined as
enum identifier {value1,value2,…..valuen};
• The identifer is a use defined enumerated data
type which can be used to declare variables
that can have one of the values enclosed
within the braces.
• Enum identifier v1,v2,…vn;
• The enumerated variables v1,v2….vn can only
have one of the values value1,value2,
….valuen
• The assignments of the following types are
valid.
• V1=value3;
• V5=value1;
• Enum day{Monday,Tuesday,……Sunday};
• Enum day week_st,week_end;
• Week_st=Monday;
• Week_end=Friday;
• If(week_st == Tuesday)
• Week_end= Saturday;
Declaration of storage class
• Variables of c have not only datatype but also
storage class that provide information about
their location and visibility
• The storage class decides the portion of the
program within which the variables are
recognized
Global variables and local variables
int m;
main()
{
int i;
float balance;
----
----
function1();
}
function1()
{
int i;
float sum’
-----
------
}
Scope and lifetime of variables
• The concept of scope and lifetime of varibales
are important only in multifunction and multiple
file programs and therefore the storage classes
are considered
• There are four storage class specifies
1) Auto
2) Register
3) Static
4) extern
• auto int count;
• register char ch;
• static int x;
• extern long total ;
• Static and extern variables are automatically
initialized to zero.
• Auto variables contain undefined values (known
as garbage variables)
• Unless they are initialized explicitly.
Storage classes and there meanings
Assigning values to variables
• Variables are created for use in program
statements such as:
Assignment statement
• Values can be assigned to variables using the
assignment operator =
• Variable_name=constant
• Example:-
initial_value=0;
Balance=75.84;
• C permits multiple assignments in one line
• Initial_value=0; final_value=100;
• Year=year+1;

• During assignment operation, C converts the


type of value on the right hand side to the type
on the left
• This may involve truncation when real value is converted to an integer
datatype variables_name=constant;
• Examples:
int final_value=100;
Char yes=‘x’;
Double balance=75.84;
The process of giving initial values to variables is called initialization
C permits the initialization of more than one variables in one statement
using multiple assignment operators
Example:-
P=q=s=0;
X=y=z=MAX (MAX is symbolic constant defined at the beginning)
Reading data from keyboard
• Another way of giving the values to variables is to
intput data through keyboard using scanf function
• It is a general input function available in C and is
very similar in concept to the printf function
• The general format scanf is
• Scanf(“%d”,&variables1);
• & symbol specifies the variable1 address
• We must always use the operator otherwise
unexpected results may occur.
Defining symbolic constants
• The constants may appear repeatedly in a number of place in the program
Example:-
value of PI=3.142
Test analysis for the total number of students=50
• We face 2 problems in the subsequent use of such programs
• Problem in modification of the program
Example:- Modifying the PI value from 3.142 to 3.14159
• Problem in understanding the program
Example:- The number to may mean the number of students in one place of the
program and it can mean as maximum pass_marks to another place in the
same program

STRENGH (for defining the number of students)


PASS_MARK (for defining the pass marks)
• A constant is defined as
• #define symbolic_name value of constant
Example:-
#define STRENGTH 100
#define PASS_MARKS 50
#define PI 3.14159
• Symbolic names are some time called constant identifiers
• Since the symbolic names are constants they do not appear
in declarations.
Rules for defining the symbolic constants
Declaring a variable as constant
• If the value of certain variables to remian
constant during the execution of the program
• We can achieve this by declaring the variable
with the qualifier const at the time of
initialization
• Example
const int class_size=40;
const is a new datatype qualifier defined by ANSI
standard
Defining a variable as volatile
• ANSI standard defines another qualifer volatile that could be
used to tell explicitly the complier that a variables’s value may
be changed at any time by some external sources
• Volatile int date;
• The value of the variable declared as volatile can be modified
by its own program well
• If we wish that the value must not be modified by the program
while it may be altered by same other process then we many
declare the varibale as both const and volatile as shown below
• volatile const int location = 100;
• #include<stdio.h> // C header file for standard input and output
int a = 0 ; // initilaizing and declaring the integer a to value 0.
int main () // main class
{
if ( a == 0 ) // This condition will be true
{
printf ( " a = 0 \n " ) ;
}
else // Else part will be optimized
{
printf ( " a ! = 0 \n " ) ;
}
return 0 ; // returning value
}
Textbook link
• https://books.google.co.in/books?
id=3fZa9af1KtYC&lpg=PR4&pg=PA37#v=on
epage&q&f=true

You might also like