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

chapter2 programming in C

The document provides an introduction to the C programming language, detailing its history, features, and structure. It covers fundamental concepts such as data types, operators, variables, and the syntax of C programs, along with examples and programming rules. Additionally, it discusses the execution process of C programs and includes homework questions for practice.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

chapter2 programming in C

The document provides an introduction to the C programming language, detailing its history, features, and structure. It covers fundamental concepts such as data types, operators, variables, and the syntax of C programs, along with examples and programming rules. Additionally, it discusses the execution process of C programs and includes homework questions for practice.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

CHAPTER 2

PROGRAMMING IN C
INTRODUCTION TO C

C is a Highlevel programming language


Developed by Dennis Ritchie in 1972

C is an offspring of the language B(by Ken Thompson)


The name C indicates the advancement of B

-
INTRODUCTION TO C

Why we are learning C


C is the programming language most commonly used and
recommended for writing operating systems.

However, other languages such as C++ and Python can


also be used.
UNIX was coded almost entirely in C
Microsoft Windows also is coded with C,C++etc...
INTRODUCTION TO C

FEATURES OF C
INTRODUCTION TO C

• It is a robust language with rich set of built-in functions


and operators that can be used to write any complex
program.
• The C compiler combines the capabilities of an assembly
language with features of a high-level language.
• Programs Written in C are efficient and fast. This is due
to its variety of data type and powerful operators.
• It is many time faster than BASIC.
INTODUCTION TO C

• C is highly portable this means that programs once written can be


run on another machines with little or no modification.
• Another important feature of C program, is its ability to extend
itself.
• A C program is basically a collection of functions that are
supported by C library. We can also create our own function and
add it to C library.
• C language is the most widely used language in operating
systems and embedded system development today.
STRUCTURE OF A C PROGRAM
Documentation Section
Link section
Definition setion
Global declaration section
main()
{
Declaration part
Executable part
}
Subprogram section
{
Function1
Function 2
.................
}
INTRODUCTION TO C
Example1:
Write a program to print the message “WELCOME”
PROGRAM:
/*program to print the message "welcome"*/
#include<stdio.h>
void main()
{
clrscr();
printf("WELCOME");
getch();
}
INTRODUCTION TO C
Example1:
Write a program to print the message “WELCOME”
PROGRAM:
/*program to print the message "welcome"*/ //documentation section
#include<stdio.h> //link section
void main() //main() section
{
clrscr(); //execution part
printf("WELCOME");
getch();
}
INTRODUCTION TO C

TURBOC++ IDE(Integrated Development Environment)


The IDE screen contains 4 parts

Main menu(Top line)


Edit window
Message window
Status line(Bottom line)
INTRODUCTION TO C

EXECUTION OF C PROGRAM

Creating the program


Compiling the program
Linking the program with C Library
Executing the program
INTRODUCTION TO C

CREATION AND EXECUTION OF C PROGRAM

Creating the program - source code .c


welcome.c
Compilig the program - object code .obj
welcome.obj
Executing the program - executable code .exe
welcome.exe
INTRODUCTION TO C
PROGRAMMING IN C
C FUNDAMENTALS
PROGRAM
A program set of instructions designed to perform a particular
task
C is called a structured programming language
because to solve a large problem, C programming language
divides the problem into smaller structural blocks each of which
handles a particular responsibility. These structural blocks are –
• Decision making blocks ( if-else-elseif,switch-case)
• Repetitive blocks like( for loop,while loop,do while loop)
• subroutines/procedures (functions)
C FUNDAMENTALS
PROGRAMMING RULES
Every statements in C program should written in lowercase letter
Every C statement ended with a semicolon(;)
The upper case letter is used for Symbolic constants
eg: #define PI=3.142
Blank space can be inserted between 2 words
Every C program must have one and only one main() function where the
program execution begins and also ends
Use beginning and ending curly braces({, })for functions
Used defined functions generally placed after main()
C FUNDAMENTALS
C DECLARATION
There are different elements in C program
❖ C character set
❖ Keywords
❖ Identifiers
❖ Constants
❖ variables
❖ Data types
❖ Operators
C FUNDAMENTALS

CHARACTER SET
The characters that can be used to form words, numbers and
expressions depend upon the computer on which the program is
run.
the characters in C are
• Letters
• Digits
• Special characters
• White spaces
C FUNDAMENTALS

Letters Numbers
Uppercase A,B,.......Z all decimal digits 0,1,....9
Lowercase a,b,........z
Special characters
,(comma) .(period) ;(semicolon) :(colon) ?(question mark) ‘(apostrophe) “(quotation mark) !(exclamation mark) |(vertical
tab) /(slash) \(back slash) ~(tilde) _(under score) $(dollar sign) %(percent sign) #(number sign) &(ampersand) ^(caret)

*(asterisk) -(minus sign) +(plus sign) <(opening angle bracket) >(closing angle bracket) ( (left paranthesis) )(right
paranthesis) [(left bracket) ](right bracket) {(left brace) }(right brace)

White spaces
Blank space
Horizontal tab
Carriage return
Newline
Form feed
C FUNDAMENTALS

C TOKENS
C
TOKENS

SPECIAL
KEYWORDS IDENTIFIERS SYMBOLS OPERATORS

CONSTANTS STRINGS
C FUNDAMENTALS
• KEYWORDS
Keywords are the basic building blocks for program statements. All keywords have fixed
meanings and these meaning cannot be changed,ie.they are reserved words
All keywords are written in lowercase letters

C KEYWORDS

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
C FUNDAMENTALS
• IDENTIFIERS
Identifiers are the names of variables ,functions and arrays
These are user defined names and consist of sequence of letters and digits
Both upper and lower case letters are permitted, although lowercase letters are commonly
used
The underscore character is also permitted in identifiers
• CONSTANTS
Constants in C refers to fixed values that do not change during the execution of a
program
CONSTANTS

NUMERIC CONSTATS CHARACTER CONSTANTS

INTEGER CONSTANTS REAL CONSTANTS SINGLE CHARACTER CONSTANTS STRING CONSTANTS


C FUNDEMENTALS
I. Numeric constants
these are holding the numeric values
Integer constants
An integer constant refers to a sequence of digits from 0 to 9 without any decimal point
It takes minimum 2 bytes and maximum 4 bytes of memory
Example:
int a=10;
3 types of integers are there
1.decimal:- consists of a set of digits 0-9,preceded by an optional + or –
Eg: 123,-324,0,654321,+78
2.octal:- it consists of any combination of digits from 0 to 7,with a leading 0
Eg: 037,0,0435,0551
3.hexadecimal :-a sequence of integer preceded by 0x or 0X,they also include alphabets A to F
Eg:- 0X2,0x9F,0Xbcd,0x
C FUNDEMENTALS
2.Real constants (floating point constants)
The numbers having fractional parts are called real constants or floating point
constants.
Example:17.548,215.65
A real number may also be expressed in exponential(or scientific)notation
Example: 215.65 can be written as 2.1565e2
e2 means 102
mantissa exponent
C FUNDAMENTALS
II. Character constants
These are holding characters
Single character constants
A single character constant contains a single character enclosed within a pair of
single quotes
Example: ‘a’,’5’,’?’ ,’ ‘etc….
Here character constant ‘5’ is not the same as the number 5
Character constants have integer values known as ASCII values(0->127)
A->65 B->66 C->67 …….Z-> 90
A->97 b->98 d->99 …….z->122
The first 32 characters and the last character are control characters,they can
not be printed and the others are special characters.(33->47, 58->64,91->96
and 123->126)
C FUNDAMENTALS
String constant
A string constant is a sequence of characters enclosed within a pair of
double quotes

Example: “hai”,“a”,”5”,”?”.” “ etc


Remember ‘a’ is not equivalent to “a”
A single character string constant does not have an equivalent ASCII
value
C FUNDAMENTALS
BACK SLASH CHARACTER constants(or Escape sequences)
C FUNDAMENTALS
SYMBOLIC CONSTANTS
symbolic constant is name that substitute for a sequence of character that cannot be changed.
The character may represent a numeric constant, a character constant, or a string. When the
program is compiled, each occurrence of a symbolic constant is replaced by its
corresponding character sequence. They are usually defined at the beginning of the
program. The symbolic constants may then appear later in the program in place of the
numeric constants, character constants, etc., that the symbolic constants represent.
Example
#define PI 3.141593
#define TRUE 1
#define FALSE 0
Here #define PI 3.141593 defines a symbolic constant PI whose value is 3.141593. When the
program is preprocessed, all occurrences of the symbolic constant PI are replaced with the
replacement text 3.141593.
When a constant is used at many places in a program ,due to some reason if the value of that
constant needs to be changed,then change at every statement where that constant occurs
in the program –so modification of program becomes difficult.if we are using only need to
change at the definition.
Sample Program :
program to calculate area and circumference of a circle */
#include<stdio.h>
#include<conio.h>
#define PI 3.1415 /* NO SEMICOLON HERE */
void main ()
{
float rad = 5; /*DECLARATION AND ASSIGNMENT*/
float area,circum; /* DECLARATION OF VARIABLE*/
area=PI*rad*rad;
circum=2*PI*rad;
printf(“AREA OF CIRCLE = %f\n”,area);
printf(“CIRCUMFERENCE OF CIRCLE =%f\n”,circum);
getch();
}
OUTPUT :
AREA OF CIRCLE =78.537498
CIRCUMFERENCE OF CIRCLE =31.415001
C FUNDEMENTALS

PREPROCESSOR DIRECTIVES
A preprocessor is a program that executes before a source program is passed
to the compiler. The preprocessor offers certain actions are known as
preprocessor directives. It performs actions like inclusion of header files,
definition of symbolic constants etc.
Preprocessor directives begin with # symbol.
The directives most often placed at the beginning of the program,before the
function definition.
Example:
#include<stdio.h>
#include<math.h> header files

#define PI 3.14
#define AGE 15 symbolic constants
C FUNDAMENTALS
• OPERATORS
An operator is a symbol that informs the computer to carry out certain
operations. The data item on which the operator will act are called operands.
The operators in C are
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operator
7. Bitwise operators
8. Special operators
C FUNDAMENTALS
DATA TYPES
The data type defines the operations that can be done on the data, the
meaning of the data, and the way values of that type can be stored.
C supports 4 classes of data types
1. Primitive data type(Primary/Basic/Fundamental/Built-in data type)
-int,char,float,double
2. Derived data type -array,pointer,function
3. User defined data type -structure, union
4. Empty set data type -void
C FUNDAMENTALS
C FUNDAMENTALS
C FUNDAMENTALS
C FUNDAMENTALS

SIGNED UNSIGNED
C FUNDAMETALS
VARIABLE
A variable is a data name that may be used to store a data value
The data value can be changed during program execution
Rules for naming a variable
1. Variable names must begin with a letter, some systems permit underscore(_) as the first
character
2. The variable name should not be a keyword
3. White space is not allowed
4. Uppercase and lowercase are significant ie total is not the same as Total or TOTAL
5. 8 characters are treated as significant for many compilers
C FUNDAMENTALS

EXAMPLES

Variable name Valid/invalid Remarks


1 First_tag valid Underscore character is permitted
2 char Not valid char is a keyword
3 Price$ Not valid Dollar sign is illegal
4 group one Not valid Blank space is not permitted
5 average_number Valid First 8 characters are significant
6 int_type valid Keyword may be part of a name
C FUNDAMENTALS

Declaration of variables
A variable can be used to store a value of any data type
Syntax:
datatype v1,v2,……vn;
Here v1,v2,…..,vn are the variables.
Variables are separated with commas.
A declaration statement must end with a semicolon.
Example:
int a,b,total;
float x;
char c;
double ratio;
C FUNDAMENTALS

Assigning values to variables


Values can be assigned to variables using the assignment operator(=)
Syntax: Variable name = constant;
Example :
a=5;b=a; total=a+b;
x=10.5;
c=‘a’;
ratio=75.1122;
The process of giving initial value is known as initialization
C permits the initialization of more than one variable in one statement using
multiple assignment operators
Ie.. int p,q,r;
p=q=r=0;
C FUNDAMENTALS

READING & WRITING FUNCTIONS IN C


Reading data from keyboard
Giving values to variables through keyboard using the function scanf()
Syntax:

scanf(“control string”,&variable1,&variable2,……..,&variablen);
Here the control string contains the format of data being received which is also
known as format specifiers.
The & symbol before each variable name is an operator that specifies the
variable name’s address.
We must always use this operator otherwise unexpected result may occur.
Example:
scanf(“%d”,&a);
C FUNDAMENTALS

Control strings(format specifiers) in c


C FUNDAMENTALS

Writing data to output screen


Writing value to the output screen using the function printf()
Syntax:

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

Example:
printf(“%d”,a);
C FUNDAMENTALS

QUESTIONS
1.Write a C program to read an integer number from input console and print its
value in the output console

2.Write a C program to assign value 15 to the variable x and display it in output


console

3.Write a C program to read 2 integer numbers and display its sum

4.Write a C program to print the sum of 2 numbers using assignment statement


C FUNDAMENTALS

HOME WORK QUESTIONS

1. Write a C program to accept 3 numbers find its sum and average


2. Write a program to find the area and perimeter of a rectangle
3. Write a program to find the area of a circle
4. Rite a program to print your name
C FUNDAMENTALS

HOME WORK QUESTIONS


1. Write a C program to accept 3 numbers find its sum and average
C FUNDAMENTALS

HOME WORK QUESTIONS


2.write a program to find the area and perimeter of a rectangle
C FUNDAMENTALS

HOME WORK QUESTIONS


3.Write a program to find the area of a circle
C FUNDAMENTALS

HOME WORK QUESTIONS


4.Write a program to print your name
C FUNDEMENTALS

OPERATORS
An operator is a symbol that tells the computer to perform certain mathematical
and logical manipulations.
Based on number of operands operators are classified into 3
1. Unary : An operator is act on one operand is known as unary operator
Eg: unary +,unary -,++,--
2. Binary : An operator is act on two operand is known as binary operator
Eg: +, -,*,/,%
3.Ternary: An operator is act on three operands is known as ternary operator
(conditional operator)
Eg: ?:
C FUNDEMENTALS

OPERATORS

1. Arithmetic operators
The operator which are use to perform some basic operation e.g
addition,subtraction,multiplication and division,are called arithmetic
operators.
C FUNDEMENTALS

2.Relational operators
We often compare 2 quantities, it can be done with the relational operators
C FUNDEMENTALS

3.Logical operators
An expression containing logical operator returns either 0 or 1
depending upon whether expression results true or false.
C FUNDEMENTALS

4.Assignment operators(=)
Assignment operators are used to assigning value to a variable. The left
side operand of the assignment operator is a variable and right side operand of
the assignment operator is a value.
Syntax: Variable=expression
C FUNDEMENTALS

5.Bitwise operators
Used to manipulate data at bit level. They may not be applies on float or
double
C FUNDEMENTALS

6.Conditional operator(?:)
These operators are used to perform logical operations on the given two
variables. ... Conditional operators return one value if condition is true and
returns another value is condition is false.
Syntax:

Example1: int x,y,z;


x=10,y=20;
z=(x>y)?x:y;
printf(“%d”,z); output:20
C FUNDEMENTALS

Example2:
int x=100,y=20 ;
(x>y)?printf(“hai”):printf(“hello”); output: hai

Questions
1. Write a program to enter 2 numbers and find out the largest among them by
using conditional operator.
2. Write a program to check whether the given number is odd or even using
conditional operator
C FUNDEMENTALS

Questions
1. Write a program to enter 2 numbers and find out the largest among them by
using conditional operator.

//(a>b)?printf(“%d”,a):printf(“%d”,b);
C FUNDEMENTALS

Questions
2.Write a program to check whether the given number is odd or even using
conditional operator

#include<stdio.h>
void main()
{
int a;
printf("enter the number");
scanf("%d",&a);
(a%2==0)?printf("even"):printf("odd");
getch();
}
C FUNDEMENTALS
Questions
3.Write a program to check whether the given number is positive,negative or
zero using conditional operator

#include<stdio.h>
void main()
{
int a;
clrscr();
printf("enter the number");
scanf("%d",&a);
(a==0)?printf("zero"):((a>0)?printf("positive"):printf("negative"));
getch();
}
C FUNDEMENTALS

7.Increment and Decrement operators


C has two special unary operators called increment ( ++ ) and decrement ( -- ) operators.
These operators increment and decrement value of a variable by 1 .

num
10 10

ans
10 11

num 11
11

Post increment Pre increment


C FUNDEMENTALS
Example:
1.Let a=10,b=15
c=a+--b will be the value of a,b and c
2.Let count=0
count++
++count
count--
--count what will be the value of count?
3.
C FUNDEMENTALS

HOME WORK
1.

what will be the value of sum?

2. a=5 b=10
b=a++ - --b what will be the value of b?
C FUNDEMENTALS

8. Special operators
C FUNDEMENTALS
C FUNDEMENTALS
C FUNDEMENTALS

Operator Precedence and Associativity


Operator precedence determines which operator is performed first in an expression with more
than one operators with different precedence.
Example: Solve 10 + 20 * 30
Operators Associativity is used when two operators of same precedence appear in an
expression. Associativity can be either Left to Right or Right to Left.
Example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the
expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
C FUNDEMENTALS

PRECEDENCE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
C FUNDEMENTALS

RULES FOR EVALUATING AN EXPRESSION


C FUNDEMENTALS

Let a = 2, b = 3, c = 7 and x = 5
Evaluate y = ( a * x * x ) + ( b * x ) + c;
C FUNDEMENTALS

Home work
Let a=9,b=12,c=3 evaluate the expressions
a. d=a-b/3+c*2-1
b. e=a-b/(3+c)*(2-1)
c. f=a-(b/3+c)*2)-1
C FUNDEMENTALS

EXPRESSIONS
An expression is a combination of variables ,operators and constants arranged as per syntax
Every expression in C results some value of certain type that can be assigned to a variable.

Example:
C FUNDEMENTALS

STATEMENTS
C FUNDEMENTALS
C FUNDEMENTALS
C FUNDEMENTALS
C FUNDEMENTALS
C FUNDEMENTALS
C FUNDEMENTALS
C FUNDEMENTALS

UNFORMATTED I/O FUNCTIONS


C FUNDEMENTALS

There are several standard library functions available under this category those which can deal
with a single character and those which can deal with a string of characters.
• getchar( ) Function
This function is used to read a single character. It is an unformatted input function. Its is found in
the header file <stdio.h>
Syntax :
variable = getchar();

• gets( ) Function
gets() Function is used to read a string i.e. group of characters; from the keyboard.
gets() is needed because scanf() discards the remaining string after a blank space where as
gets() is useful for inputting multiple lines statements.
Syntax:
char array-variable;
gets(array-variable);
C FUNDEMENTALS

• getche() Function
This function is also used to read a single character. It is also an uformatted input
function. It is found in the header file <conio.h>
Syntax:
variable = getche();

• getch() Function
This function is used to read an unformatted input funtion. Its prototype is found in
the header file <conio.h>
Syntax:
variable = getch();
C FUNDEMENTALS

• putch() & putchar() Function


This function is used to print a single character. It is an unformatted output
function. Its prototype is available in the header file <stdio.h>
Syntax:
putchar(variable);
putch(variable);

• puts()Function
puts() function is used to print the whole string including blank spaces.
Syntax:
puts(array-variable);
puts(str);

You might also like