[go: up one dir, main page]

0% found this document useful (0 votes)
82 views20 pages

Course Code: Scax1001 Course Name: Computer Applications in Business Chapter Name: C' Language Subject Coordinator: Mrs - Jancy - C Language

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

COURSE CODE: SCAX1001

COURSE NAME: COMPUTER APPLICATIONS IN BUSINESS


CHAPTER NAME: ‘C’ LANGUAGE
SUBJECT COORDINATOR: MRS.JANCY

UNIT I – C Language
Introduction to C
 C is a general purpose programming language.
 C was developed by Dennis Ritchie in 1972 at the Bell Telephone Laboratories in
USA.
 It is a middle level language (i.e.) it supports high level as well as low level
programming language.
Lowlevel -> it means Assembly language. Its easy to machine but its difficult
to user.
Highlevel -> It’s easy to user but difficult to machine. (i.e.) Now users can use
this language, such as c, c++, java/
 C was an offspring (Family) of the ‘BasicCombinedProgrammingLanguage’ (BCLP)
called B.
Advantages of C Language
 RobustLanguage
 It has rich set of built in Functions and Operators can be used to write any
complex program.
BuiltinFunction -> it means created already and it called as Library
Function. (i.e.) sin(x), cos(x), sqrt(x), tan(x).
Operators -> It is a symbol which is used for doing an operation. (i.e.)
+, -, *, /.
 EfficientandFast
 C has variety of data types and powerful operators.
 It has limited number of keywords (only 32 keywords).
Keyword -> It is a fixed meaning and user can’t change that
meanings. (i.e.) break, do, for, main, if.
 Portable
 C Language supporting the execution of C Program in different operating
system or different environment.

1
 C program written for one type of computer can be run on another type of
computer with no modification.

 Expandability

 Existing Program or Function may be included into another program is called


expandability. The general format : #include “Filename”
Ex.
P1. P2.
F1 F1 using the P1 filename
Filename a.c { transferred to P2. { #include “a.c” in P2.
…………….. ………………
} }
 Modularity
 C Language support the modular programming, the property of dividing a big
problem into sub problems is called the modularity.
 Sub problems are called as Modules or Functions or Sub Programs.
AdvantagesofModularity
 Workload can be divided a shared by more than one programmers.
 Errors can be identified and corrected easily.
StructureofCProgram
A C Program has the following format.
Documentation Section
Linkage Section
Data Definition
Global Declaration
Main()
{
Local Declaration
Procedural Stmt
}

2
DocumentationSection
 This section is used to specify the description about the program.
 Set of comment lines can be given to specify the name of the program.
There are two formats to enter the comments about the program.
 Starts with // - single line.
 Starts with /* --- */ multiple line.
 This section is optional section.

LinkageSection
 This section is used to link a header files or another ‘C’ files to our current program to
execute library function or user defined functions respectively.
 The header files are the special files with the extension.h which contain some pre-
defined function. These functions also called as library functions.
There are two formats
 Linking a header file
#include <header file name>
#include <stdio.h>
 To link another ‘C’ program to current ‘C’ program. The format will be
#include ‘C’ program name enclosed in double quotes.
#include “a.c”.
Note: More than one file can be linked in a single program by more than one linkage
statements.
 The functions which are written by the users are called as UserDefined
Functions.
 The functions which are not written by the user, but they are written already
(already defined) are called as Pre-definedFunctions (or) LibraryFunctions (or)
Built-inFunctions.
DataDefinitionSection
This section is used for defining the symbolic constants. Some variable
values are unchanged in a program.
E.g.: PI is a variable whose value is always 3.14127
GeneralFormat
#define variable constant value.
E.g.: #define Pi 3.14127

3
RulesforSymbolicConstant
 A single program may have more than one symbolic constant. There is no
space between # and define.
 It shall not end with semicolon.
 If constant value is assigned to a symbolic name we cannot change its value.
 The differentiate variables and symbolic names can be written in Capital
Letters.

GlobalDeclarationSection
The variables which are used in more than one function are called global
variables. They should be declared in this section before all the function.

Main()Function
Every ‘C’ Program has a main() function to be executed. A main() function is
a function from which the execution start. There are two sections. They are
i. LocalVariableDeclarationSection
The value of this variable is available to the current functions only.
ii. ExecutablePart(or)ProceduralStatementSection
 It is used for defining the executable/procedural statements. In this
section we have to include the statements which are to be executed.
 The two parts appear between the opening and the closing braces.
All the procedural statements and declaration statement parts end
with semicolon.
E.g.: Addition of two numbers.
Documentation -> // Addition of two numbers
Linkage -> #include<stdio.h>
#include<conio.h>
Main() -> void main()
{
Local declaration -> int a,b,c; clrscr();
scanf(“%d\n%d”,&a,&b);
Statements -> c=a+b;

4
printf(“The value of c is : %d”,c);
getch();
}

ENTERING AND EXECUTING C PROGRAM

Execution is the process of executing a C program, we need to follow the steps given
below.
I. Creating the Program
II. Compiling the Program
III. Linking the Program with system Library
IV. Executing the Program
The Below figure, Illustrates the process of creating ,compiling and executing a ‘c’ program.

ENTER C PROGRAM

SOURCE CODE EDIT C PROGRAM

COMPILER COMPILE C PROGRAM

SYNTA
X
ERROR
S
Yes
OBJECT CODE LINK WITH SYSTEM LIBRARY

EXECUTE PROGRAM
INPUT DATA

No
LOGIC
AL&D
ATA
ERROR

CORRECT OUTPUT

yes
STOP

5
CreatingtheProgram:
Creating the Program means entering and editing the program in standard ‘c’ editor
and save the program with .C as an execution.
CompilingtheProgram:
This is the process of converting the high level language program in to machine
understandable form(Machine Language).Usually this can be done in ‘c’ language by
pressing ALT+F9 or choose compile option in the menu System.
Here there is a possibility to show errors.i.e,syntax errors,means the statements
written in program are not in proper systax.
LinkingtheProgramwithsystemLibrary:
‘C’ language program is the collection of predefined functions.These functions are
already written in some standard ‘c’ header files. Therefore before executing a ‘C’
program,We need to link wit system library.This can be done automatically at the time of
execution.

ExecutingtheProgram:
This is the process of running and testing the program with sample data. At this time
there is a possibility to show types of errors given below.
a) Logical Errors: These are the errors to specify the errors in the logic (Semantic) of the
program.
b) Syntax Errors: This type of error specifies if any statement is not in a proper syntax as
specified in general syntax.
A program which has a logical error gives invalid output and a program which has syntax error
does not run and not giving any output.
Usually , executing the program can be done by pressing CTRL+F9 or choose RUN option
from the menu system.

ASSIGNMENT QUESTIONS:

6
1. Write a C program to display the following information ”SATHYABAMA
UNIVERSITY”.
2. Write a C program to calculate sum of three numbers..
3. Write a C program to find average of any float values.
4. Write a C program to calculate the value for COMPOUND INTEREST.
5. How to define the symbolic constant
6. Write the two formats in the documentation section.

Input and Outputofthevariables


Input:
 Input data can be entered into memory from standard input device.
 It is a process of getting the values of one or more variables.
 In the ‘C’ program, inputting process is done by a function called as scanf(). It
is a built-in function stored under a header file called as stdio.h.
GeneralFormat: scanf(“ format specification” , & variables);
The Format specifies the field format in which the data is to be entered.
%d Integer Variable
%f Float Variable
%s String Variable
%c Character Variable
%u Unsigned Integer Variable
%ld Long Integer Variable

Eg: scanf(“%d”,&x);

 In the scanf function there is no &symbol if the variable is string.


 To get the value of character variable instead of using scanf(), we can
use getchar() (or) getche() functions.
Syntax: Charactervariable = getchar ();
 Instead of using scanf () function , we can used gets() function which is
available in a header file called as string.h
Syntax: gets(string variable);
Output:
 It is a built in function stored under a header file called as stdio.h.

7
 It is a process of producing the output of the program on the screen.
Syntax: printf (“format specification”, variables);
 In the printf() function, we can include the comment also. The comment can be
given in the double quotes with format specifies.
Eg: printf(“%d”,x)……> Printing the integer value x
Eg prg:
#include<stdio.h>
#include<conio.h>
void main()
{
int p,n,r,si;
clrscr();
printf(“Enter the p, n, r values :\n”);
scanf(“%d\n%d\n%d”,&p,&n,&r);
si=(p*n*r)/100;
printf(“The simple interest : %d”,si);
getch();
}
ASSIGNMENT QUESTIONS:
1. What is the difference between getchar(),getc() and getch().
2. What is the use of gets() and puts().
3. Write the syntax for scanf() and printf().
Variables:
 It is a quantity whose value can be changed during the execution of the
program.
 It is a dataname used to store data value.
 The variable may take different values at different situation during execution. A
variable name can be chosen by the programmer in meaningful way.
E.g.: Amount, Height, and Salary.
TheRulesforfarmingtheVariable
 It is a collection of alphabet, numeric digit and the special character underscore ( _ ).
 White space not allowed.
 A variable must start with an alphabet. The variable contains maximum of 36
characters.

8
 Uppercase and lowercase are significant.
E.g.: xyz, x_y_z_1 ------------------------------------------ Valid variable
x+y, 1xyz ---------------------------------------------- Invalid variable
The variables are divided into two types, they are
GlobalVariable – If a variable is used in all the functions then the variable is called
Global Variable. The variable should be declared before call the main().
LocalVariable – If a variable is used with in a current function only then the variable
is called Local Variable. The variable should be declared inside the function.
ASSIGNMENTQUESTIONS:
1. List the two different types of variables.
2. Write the format to assign the variables.
3. What is the format specification for the following datatype
(i) Integer
(ii) Float
(iii) Char
(iv) Double
(v) Long double
‘C’Tokens: (Lexical Issues)
 In the ‘C’ language, the compiler recognises the some basic elements. Those basic
elements are called Tokens.
 These Tokens are used to building a block program.
 ‘C’ has 6 types of Tokens.
 Keyword.
 Identifier.
 Constant.
 String.
 Special Symbol Operator.
 Operator.
Keyword:
 Keyword has fixed meaning and this meaning can’t be changed.
 All Keywords must be written in lowercase. It also called as reserved words.
E.g: main, if, scanf, while, do, for, printf, default, int, char, switch, float etc.
(Totally 32 Keywords).
Identifier:

9
 Identifiers are referring to the name of variable, functions and array in a
program.
 User define the words are called Identifiers.
 It consists of sequence of letters A - Z and digit 0 – 9.
Constant:
 It is a quantity whose value can’t be change during the execution of the
program.
 It has fixed value that does not change.
 There are two types, they are
Numeric Constant.
Character Constant (non numeric).

NumericConstant
 It is collection of numeric digit with a special character (+, - and .).
 There are two types, they are
Integer.
Float.
IntegerConstant
o It is a sequence of digit. It has three types
Decimal – It is sequence of digit starting from 0 – 9 with
proceeding by optional sign. (+ or -).
E.g.: -8, +52.
Octal -- It is sequence of digit starting from 0 – 7 with leading
0.
E.g.: 05, 07.
Hexadecimal -- It is sequence of digit starting from 0 – 16 (0 –
9 is numeric value, 10 – 16 alphabets (A – F))
With proceeding by 0x, 0X.
E.g.: 0x 29f.
FloatConstant
o It refer to an sequence of a digit with a decimal point
E.g.: 0.52, 4.56.
CharacterConstant (non numeric)

10
 It is a collection of one or more characters. It has two different types,
they are
Single Character.
String.
SingleCharacter
It has single character enclosed with in pair of single quote (‘)
marks.
E.g.: ‘x’.
Stringconstant
It has sequence of character enclosed with in double quotes
(“). The character may be letters, numbers and special characters.
E.g.: “Hello”.

StringFunction
 A string is a sequence of character enclosed with in double quotes (“) but
ends with \0. The compiler puts \0 at the end of string to specify the end of the
string.
 To get a value of string variable we can use the two different types of format.
Using scanf() function as: scanf(“%s”, string variable);
Using gets() function as : gets(string variable);
C library supports a large number of string handling functions. That functions are
stored under the header file string.h in the program.
strlen()function:
This function counts and returns the number of characters in a
string. The length does not include a null character.
Syntax: n=strlen(string);
Where n is integer variable. This receives the value of length of the
string.
E.g.: length=strlen(“Hollywood”);
The function will assign number of characters 9 in the string to a integer
variable length.
strcat()function:

11
when you combine two strings, you add the characters of one string to the
end of other string. This process is called concatenation. The strcat() function joins
2 strings together. It takes the following form.

strcat(string1,string2);

string1 & string2 are character arrays. When the function strcat is
executed string2 is appended to string1. the string at string2 remains unchanged.

E.g string1=”hello”;
string2=”welcome” ;
strcat(string1,string2);
The output will be “hellowelcome”
strcmp()function:
In c you cannot directly compare the value of 2 strings in a condition like
if(string1==string2) Most libraries however contain the strcmp() function, which
returns a zero if 2 strings are equal, or a non zero number if the strings are not the
same. The syntaxofstrcmp() is given below:

strcmp(string1,string2) ;

String1 & string2 may be string variables or string constants. String1, &
string2 may be string variables or string constants some computers return a
negative if the string1 is alphabetically less than the second and a positive number
if the string is greater than the second.

Example:

strcmp(“Newyork”,”Newyork”) will return zero because 2 strings are equal.

strcmpi()function

This function is same as strcmp() which compares 2 strings but not


case sensitive.

Example : strcmpi(“THE”,”the”); will return 0.

strcpy()function:
C does not allow you to assign the characters to a string directly as in the
statement name=”Robert”;
syntax of the function is illustrated below.

strcpy(string1,string2);

12
strcpy function assigns the contents of string2 to string1. string2 may
be a character array variable or a string constant.

strcpy(Name,”Robert”);

strlwr()function:
This function converts all characters in a string from uppercase to
lowercase.

Syntax: strlwr(string);

For example:

strlwr(“WELCOME”) converts to welcome

strrev()function:
This function reverses the characters in a string.

Syntax : strrev(string);

For ex: strrev(“program”) reverses the characters in a string into


“margrop”. strupr()function:
This function converts all characters in a string from lower case to
uppercase.

Syntax : strupr(string);

For example strupr(“welcome”) will convert the string to WELCOME.

EgPgm: To check whether a given string is a palindrome or not

#include<stdio.h>
#include<conio.h>
void main()
{
Char s[20],rs[20];
clrscr();
printf(“Enter the original string :\n”);
scanf(“%s”,s);
strcpy(rs,s);
strrev(rs);
printf(“The Reverse string is:%s”,rs);
if(strcmp(s,rs)==0)
printf(“The given string is palindrome ”);

13
else
printf (“\n The given string is not palindrome”);
getch();
}
SpecialCharacter(Backslashcharacters)orEscapeSequences:

 Some characters start with backslash(\).

 These characters are used for producing the output of the program in clear
format.

\n – It is used to move the cursor to next line.

Eg: a=5, b=25

printf(“%d\n%d”,a,b)

The output will be 5

25

\v – It is used to give 5 vertical spaces in between two values.

Eg: a=5, b=25

printf(“%d\v%d”,a,b)

The output will be 5

25

\t – It is used to give 5 horizontal spaces in between two values.

Eg: a=5, b=25

printf(“%d\t%d”,a,b)

The output will be 5 . . . . . 25

\r – It is used to move the cursor to the beginning o the value.

\a – It is used to produce a beep sound for alert.(audiable alert).

\b – backspace.It is used to give a backspace.

Eg: a=5, b=25

printf(“%d\b%d”,a,b)

14
The output will be 25…………..> First print the value of a then remove value
of a after that print the value of b.

ASSIGNMENT QUESTIONS:
1. How many number of keywords are there in C language.
2. What is the use Escape Sequences\Backslash Character.
3. What is the difference between strcmp() and strcmpi().
Operator

It is a symbol which is used to doing an operations. C language has different types of


operators. They are

 Arithmetic

 Relational

 Logical

 Assignment

 Increment And decrement

 Conditional

 Bitwise

 Comma

 Sizeof()

ArithmeticOperators:

 It is used to developing the arithmetic expressions.

 This operators are used to do arithmetic operations.

+…… Addition.

- …… Subtraction.

* ……. Multiplication.

/ …….. Division.

% ……. Modulator.

Eg: a+b, a-b

RelationalOperators:

 It is used to developing the relational expressions.

15
 This operators are used to compare more than one values.

<…….Less than,

>…….Greater than

<=…… Less than or equal to

>=…...Greater than or equal to

==…… Equal to

!=……. Not equal

Eg: a>b, a>=b

LogicalOperators:

 It is used to developing the logical expressions.

 This operators are used to combine more than one conditions.

&& …….. Logical AND

||……… Logical OR

! …….. Logical NOT

Eg : (a>b) && (a>c)

AssignmentOperator:

It is used to minimize the statement which has an expression on RHS


and a variable is present both LHS and RHS.

Syntax: variable operator = value;

This syntax is equivalent to

variable = variable operator value;

Eg: a=a+10…………..a+=10

b=b-10 ……………b-=10

IncrementAnddecrement:
These operators are used to increment and decrement the value of
variable.

Two types: Pre and Post

Operators: ++variable, variable++, --variable, variable--.

16
Pre increment post increment pre decrement post decrement

Incremented by one Decremented by one

Eg: x=10; x=10;

X++; or (++x) x--; or (--x)

printf(“%d”,x); printf(“%d”,x);

The Output is 11 The output is 9

There is no change between There is no change between pre

and post increment operator pre and post decrement operator except

they are assigned to variable. except they are assigned to variable. Eg:

x=10; x=10;

y=x++; y=++x

printf(“%d\n%d”,x,y) printf(“%d\n%d”,x,y)

The output is x=11 The output is x=11

y=10 y=11

ConditionalOperator:

It is used to check the condition that’s why it’s called if...else structure.

Operator - ? :

Syntax: variable= (condition)? stmt1:stmt2

If condition is true means it’s execute the stmt1 otherwise it’s execute
the stmt2.

Eg: a=1,b=2

Big= (a>b)?a:b; …………… the result will be Big=b.

BitwiseOperator:

It is used to doing bitwise operations. A bit is a binary digit whose value


may be either 0 or 1.

17
& …….>Bitwise AND

| ……...>Bitwise OR

Shift right >>

Sift left <<

Exclusive OR ~

Nagation !

CommaOperator:

It is used to minimize the more than one statement into single statement.

Syntax : variable=(expression, stmt1,stmt2…..stmtn);

Eg: x=1; It can be minimized in a single statement using

y=20; comma operator as z=(x+y,x=1,y=20);.

z=x+y

Sizeof()Operator:

It is used to return the size of variable or datatype in no. of bytes.

Syntax : sizeof(variable/datatype);

Eg: x=sizeof(int); …………. > x=2.

Expression

It is a collection of variables and constants with operators. There are three types,
they are

 Arithmetic Expression : It is a collection of variable and


constant with arithmetic operator. The resultant value of arithmetic expression
always numeric values. Eg:( a+b),(b%c).

EvaluationofArithmeticExpression:

When an arithmetic expression given to be evaluated, it follow


some predefined rules called as hierarchy rules / priority rules.

Rules:

 Multiplication, division and modulo divisor will be evaluated


first.

 Subtraction and addition is performed next.

18
 If there is any parenthesis in an expression, the expression in
parenthesis will be performed first by following hierarchy ruls.

 If more than one operators with the same priority are present,
its evaluated from left to right.

 LogicalExpression : It is a collection of variable and constant


with arithmetic operator. Eg:( a>b)&&(b<=c)

 Relational Expression : It is a collection of variable and


constant with arithmetic operator. The resultant value of relational expression is
either true or false values Eg:( a>b),(b<=c).

EgPrg:programtofindtheaverageof3floatvalues

#include<stdio.h>
#include<conio.h>
void main()
{
float a, b, c, d;
clrscr();
printf(“Enter the 3 values :\n”);
scanf(“%f\n%f\n%f”,&a,&b,&c);
d=(a+b+c)/3;
printf(“The result is : %f ”,d);
getch();
}
ASSIGNMENT QUESTIONS:
1. What is the difference between OR and AND operator.
2. How to evaluate an arithmetic expression.
3. Use of assignment operator write one simple program.
4. What is the other name for conditional operator.
5. Write one simple program use of sizeof() operator.
6. Why we are using the comma operator.
7. How to reduce the statement a=a*10.
8. What is the output for the following program

(i)#include <stdio.h>

19
void main()
{
int i=1;
i++;
printf("%d ",i);

}
(ii) #include<stdio.h>
Void main()
{
int x,i=5;
x=i++;
printf(“%d”,x);
}

Links for Reference

http://www.tutorialspoint.com/
http://a4academics.com/
http://www.programiz.com/c-programming

20

You might also like