0% found this document useful (0 votes)
3 views25 pages

Unit 2 C Programming

This document provides an introduction to the C programming language, including its history, characteristics, and applications. It covers fundamental concepts such as data types, program structure, input/output functions, and the syntax for writing C programs. Additionally, it outlines the importance of C as a foundational language for learning other programming languages and its role in operating systems and software development.

Uploaded by

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

Unit 2 C Programming

This document provides an introduction to the C programming language, including its history, characteristics, and applications. It covers fundamental concepts such as data types, program structure, input/output functions, and the syntax for writing C programs. Additionally, it outlines the importance of C as a foundational language for learning other programming languages and its role in operating systems and software development.

Uploaded by

shreyashumale115
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 2

_________________________________________________________

Contents
• Introduction to C

• History of C

• Characteristics of C

• Application of C

• Building blocks of C

• Data Type

• Program Structure

• Input and Output

• First C Program
Computer is an electronic device. It can perform arithmetic and logical
operations. Computer consist of two types of elements. Hardware and Software.

Hardware – Parts of computer to which we can touch.


Software – Set of programs that when executed provide some desired output.
Programs – Set of Instructions.
To write those instructions in computer we need language that can be
understood by both user and the computer. For this purpose we will use a
Computer programming language called C. But before going to C first understand
some related terms.

Operating System. (OS)

It acts as an interface between the user and the hardware. A user cannot
run an application program on computer without OS.
Introduction to Software.

Ex- Windows 7, Linux, Mac, etc.

Software.

Software is the collection of programs and program is the set of instruction.


It tells the computer what to do and how to do it.

No Name Description
The software that helps the system to run
1 System Software. and manage all its task are called system
software.
These are the software developed as per
the user need of user. User can install these
2 Application software. software when required or can use it if
already available.
Ex- MS Office, Tally, Calculator.
The computer languages are called
programming languages. With the help of
3 Programming Languages. these languages user/ developer can
develop system or application software,
Ex- C, C++, Java.
The tools in which user can develop system
or application software are called
development tools. It is of two types.
Advanced web Front End Development tool- Tools to create
4
development tools. screens and reports or User Interface. Ex-
TurboC++, Netbeans.
Back end tools- Tools to store data entered.
Ex- Oracle , MySQL
These tool allows to create web sites and
5 Web based tools. web pages.
Ex- HTML, PHP.

C Programming
C is a computer programming language. It is a middle level language
developed by Dennis Ritchie in 1970.

History of C

C was invented and first implemented by Dennis Ritchie in 1970. For many
years the version used was supplied by the UNIX operating system. In the summer
of 1983 a committee was established to create an ANSI (American National
Standards Institute) standard that would define the C language. The
standardization process took 6 years. The ANSI (American National Standard
Institute) C was finally adopted in 1938 with the first copies became available in
early 1990.

C Programming Language Timeline:


Programming Development
Developed by
Language Year
ALGOL 1960 International Group

BCPL 1967 Martin Richards

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&R C 1978 Brain Kernighan and Dennis


Ritchie
ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

What is C? / C characteristics.
• C is computer programming language.
• It is a high level language sometimes called middle level language.
• It is a block structured programming language.
• It is a Procedure Oriented Programming Language.
• It follows top down approach.

Applications developed in C

Programming language: JAVA, C++, python (not jpython) e.t.c

Operating system Kernel (Heart of OS)

Operating System: Linux OS and its variants, Unix and it's variants like
BSD, Sun OS e.t.c.

Web browser: Firefox, Google Chrome etc.

Database: MySql, DB2 etc.

Web server: Apache HTTP server, Nginx


Programming Languages Ranking – TOIBE

TIOBE stands for The Importance of Being Earnest. The software quality
company. The TIOBE Programming Community index is an indicator of the
popularity of programming languages

Mar Mar Programming


Ratings Change
2020 2019 Language

1 1 Java 17.78% +2.90%

2 2 C 16.33% +3.03%

3 3 Python 10.11% +1.85%

4 4 C++ 6.79% -1.34%

5 6 C# 5.32% +2.05%

C as a procedural language

A procedure is known as a function, method, routine, subroutine, etc. A


procedural language specifies a series of steps for the program to solve the
problem.

A procedural language breaks the program into functions, data structures, etc.

C is a procedural language. In C, variables and function prototypes must be


declared before being used.

C as a structured programming language

A structured programming language is a subset of the procedural language.


Structure means to break a program into parts or blocks so that it may be easy
to understand.

In the C language, we break the program into parts using functions. It makes
the program easier to understand and modify.

C as a mid-level programming language

C is considered as a middle-level language because it supports the feature of


both low-level and high-level languages. C language program is converted into
assembly code, it supports pointer arithmetic (low-level), but it is machine
independent (a feature of high-level).
A Low-level language is specific to one machine, i.e., machine dependent.A
High-Level language is not specific to one machine, i.e., machine independent. It
is easy to understand.

Why to Use C/ ‘C’ the beginners First Step.

C is efficient, string, simple programming language. C is called the mother


of all programming languages. Following are the reasons for why to use C.

• The basic concept and programming skills are used in C++, Java, and
C#. SO without learning C it is very difficult to learn these languages.
• Major parts of OS like windows, UNIX, are written in C language.
• Device drivers are also written in C language.
• OS used in electronic devices are written in C.

Steps in Learning ‘C’.


As like English language the first step is to know the alphabets, digits and
special symbol. Next step is to learn constants, variables, keywords, Identifiers.
The next step is to write programming instructions that will lead to development
of a particular program.

Tokens
Tokens are the smallest individual unit in a C program. Token include
Identifier, Variables, special Symbol, etc.

Keywords

Identifie
rs

Special
Tokens Symbol

Constants
Strings

Operators

The C character Set

A character denotes any alphabet, digit or special symbol used to represent data
or information.
Digits 0–9
Alphabets A to Z and a to z
Special Symbol / * - + # @ ! & * ^, etc.

Variables

It is the name given to a memory location. It is an entity that may changes


during the execution of the program.

a=5; here a is variable

Constants-

C Constants are also like normal variables. But, only difference is, their
values cannot be modified by the program once they are defined. Constant in C
means the content whose value does not change at the time of execution of a
program.

a = 5 // 5 is constant

Types of constants

• Integer constants
• Real or Floating point constants
• String constants

RULES FOR CONSTRUCTING C CONSTANT:

INTEGER CONSTANTS IN C:

• An integer constant must have at least one digit.


• It must not have a decimal point.
• It can either be positive or negative.
• The allowable range for integer constants is -32768 to 32767.

REAL CONSTANTS IN C:

• A real constant must have at least one digit


• It must have a decimal point
• It could be either positive or negative
• If no sign precedes an integer constant, it is assumed to be positive.
• No commas or blanks are allowed within a real constant.

Character Constant in C

• A character constant is a single alphabet, a single digit or a single special


symbol enclosed within single quotes.
• The maximum length of a character constant is 1 character.
• String constants are enclosed within double quotes.

Integer Constant Real Constant Character Constant


345 125.34 'B'
-543 -45.98 'c'
+6725 567.0 '3'
-5643 -456.0

ASCII character Set (American Standard Code for Information Interchange)

In computer system different characters are represented by their ASCII values.


The range for them are given below.

Character Set ASCII Range


Special Symbol 0 to 47
0–9 48 to 57
Special Symbol 58 to 64
A–Z 65 to 90
Special Symbol 90 to 96
a–z 97 to 122
Special Symbol 123 to 127

Data Types-

Data types are used to specify which kind of value we are going to use in
our programs. Consider the example of an Employee which may have data like his
ID, salary and name. Here name of employee is set of alphabets, whereas ID is
whole number and salary may be in decimal point. To use data we require different
kind of data types to be matched with the information we are going to use.

Categories of data type

• Primary/Fundamental
• Derived
• User defined
C data types

Derived Built in data type User defined

Array Structure

Function Union

Pointer

Integer Void Floating

int char float double

First we will see what is Primary or Fundamental Data type

Data Keyword
Description Size(Bytes) Range
Type Used
Use to represent a single
Character char character. Alphabet, 1 -128 to +127
Digit, etc.
Use to indicate whole -32767 to
Integer int 2
number. +32767
3.4E-38 to
Float float Use for decimal value 4
3.4E+38
Use for precise decimal 1.7E-308 to
Double double 8
value. 1.7E+308

Syntax-

datatype variablename;

Example-

char name;

int age;

float percentage; float temp

Type Qualifiers
C – Type qualifiers: The keywords which are used to modify the properties
of a variable are called type qualifiers. These qualifiers are used with data type
to modify their range.

There are four types of qualifiers

Long

Short

Signed

Unsigned

Long and unsigned are used to increase the range of values at the time of
declaration.

If sign is not specified for the integer, float & double then by default sign is
‘+’ i.e. positive. If sign is required i.e., negative sign and the short values then
signed and short qualifiers are used data types with their extended data types.

Variables

Variables are the name given to a memory location. Variables are defined
as the entities which can be changed at different times. One variable stores one
value at a time. To store the value in a variable data type and variable name is
required. The variable name is also called identifier. Real values can be stored
using float or double data type.

Variable declaration

datatype variable_name;

Variable Initialization

For example:

int num; //variable declaration

num =1; //variable initialization

int num2 = 28;


ELEMENTS OF C PROGRAM

Header file

#include Instruction
#include statement is used to include the standard library functions. The
definition of these library functions are written in the header files. To carry out the
input and output operations we need to include <stdio.h> header file. Header file
is the first line in any C program. Including a header file can be stated in other
meaning as including the contents of that file in our program.

Header file Description


<stdio.h> Input/output
<conio.h> Console Input/output
<math.h> Common mathematics functions
<time.h> Time/date utilities

Header files are included as per the programming requirement. It is


compulsory to include <stdio.h> because every C program contains at least one
input or output function.

Executing a C program

Main function-
Program execution always start from main function. The main function is
called by the operating system. It is necessary to write main function in the
program. Main function can be written in many ways.

void main()
int main()
int main(void)

void is used when the main is not returning any value. Main function can
return value or not. If main is written as int main() then it is necessary to write
return 0; statement at the end of main function.

Input and Output

As we all know the three essential functions of a computer are reading,


processing and writing data. Majority of the programs take data as input, and then
after processing the processed data is being displayed which is called information.
In C programming you can use scanf() and printf() predefined function to read
and print data.

printf() and scanf() in C – Formatted I/O functions


The printf() and scanf() functions are used for input and output in C
language. Both functions are inbuilt library functions, defined in stdio.h (header
file).

printf() function

The printf() function is used for output. It prints the given statement to
the console.

The syntax of printf() function is given below:

printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f


(float) etc.

scanf() function

The scanf() function is used for input. It reads the input data from the console.

scanf("format string",argument_list);

Example
printf("enter a number:");
scanf("%d",&number);
Structure of C Program-

Documentation Section Comments (Optional)

Link Section Header File

Definition Section Symbolic constant (if required)

Global Declaration Section Global variable and function

main() Function Section main()


Definition of other user defined
Subprogram Section
function

Example-

Based on the above structure the sample program in given below. This
program do not include any user defined functions or any symbolic constant.

My First C Program
Program to display hello World message.

// Welcome message Program in C


#include<stdio.h> // Link Section
void main() // main function
{
printf("Welcome to C langauge"); // displaying output
}

#include<stdio.h>
void main()
{
// addition
int a,b,c;

a=10,b=20;
c=a+b;
printf("Addition is %d",c);
}

Comments

We can add comments in our program to describe what we are doing in the
program. These comments are ignored by the compiler and are not executed.

To add a single line comment, start it by adding two forward slashes //


followed by the comment. To add multiline comment, include it between /* .... */,
just like in the program above.
Escape Sequence in C

An escape sequence in C language is a sequence of characters that doesn't


represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example:


\n represents new line.

List of Escape Sequences in C

Escape Sequence Meaning


\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\t Tab (Horizontal)
\v Vertical Tab
\? Question Mark
\0 Null

#include<stdio.h>
int main(){
printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\
"");
return 0;
}

C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to
transform your code before compilation. It is called micro preprocessor
because it allows us to add macros.

All preprocessor directives starts with hash # symbol.

Let's see a list of preprocessor directives.

#include #define #undef #endif #error

Formatted and Unformatted I/O in C


Input output functions in C programming falls into two categories, namely,
formatted input output (I/O) functions and unformatted input output (I/O)
functions.

Formatted Unformatted
These functions allow to supply input These functions are the most basic
or display output in user desired form of input and output and they do
format. not allow to supply input or display
output in user desired format.
printf() and scanf() are examples for getch(), getche(), getchar(), gets(),
formatted input and output functions. puts(), putchar() etc. are examples of
unformatted input output functions.

Formatted input and output functions Unformatted input and output


contain format specifier in their functions do not contain format
syntax. specifier in their syntax.
They are used for storing data more They are used for storing data more
user friendly. compactly.
They are used with all data types. They are used mainly for character
and string data types.

Unformatted input/output functions

Unformatted console input/output functions are used to read a single


input from the user at console and it also allows us to display the value in the
output to the user at the console.

Some of the most important formatted console input/output functions are -

Functions Description
getch()
Reads a single character from the user at the console,
without echoing it.
getche()
Reads a single character from the user at the console,
and echoing it.
getchar()
Reads a single character from the user at the console,
and echoing it, but needs an Enter key to be pressed at
the end.
gets()
Reads a single string entered by the user at the
console.
puts()
Displays a single string's value at the console.
putch()
Displays a single character value at the console.
putchar()
Displays a single character value at the console.
// program for getche and putchar // program for gets and puts
#include<stdio.h> #include<stdio.h>
#include<conio.h> void main()
{
void main() char str[20];
{ printf("Enter your name \n");
char ch ; gets(str);
clrscr(); puts(str);
printf(“Press any character:”); }
ch = getche();
printf(“\nYou pressed :”
putchar(ch);
getch();
}

// getchar and putchar demo //Program to take string and print using scanf
program and gets.
#include <stdio.h>
void main( ) #include<stdio.h>
{ void main()
int c; {
printf("Enter a character\n"); char name[20];
printf("Enter your name\n");
c = getchar(); scanf("%s",name); //only accept first word
ex- welcome
putchar(c);
} gets(name); //it will accept whole string with
blank space. //ex- Welcome java
printf("Hello %s Welcome to C language
\n",name);
puts(name);
}
Declaring Constants.

Constant variables can be defined as the variables whose Value once


assigned cannot be changed throughout the execution of the program

e.g. variable pi can be assigned a value [Link] Value does not change
throughout the program. So these types of Variable can be declare using ‘const’
keyword or by using #define preprocessor

Using const keyword

e.g. const float pi = 3.14;

#include <stdio.h>
void main()
{
const float pi = 3.14;
printf("value of PI :%f \n", pi );
}

Using #define preprocessor directive: This directive is used to declare an alias


name for existing variable or any value. We can use this to declare a constant as
shown below:

#define identifierName value

• Identifier Name: It is the name given to constant.


• value: This refers to any value assigned to identifierName.

#include<stdio.h>
#define val 10
#define floatVal 4.5
#define charVal 'G'

int main()
{
printf("Integer Constant: %d\n",val);
printf("Floating point Constant: %.1f\n",floatVal);
printf("Character Constant: %c\n",charVal);

return 0;
}
Operators
Operators are defined as the symbols used to indicate the operations on
the operands (values). Where operand are the entities on which operation is
performed.
For example:

Operand

100 + 80

Operator

In programming format the expression can be written as

c= a+b;

Here a and b are the operands and + is the operator. The addition of a
and b is assigned to c

The different types of operators available in C are as follows:

Increment and Assignment Relational


Arithmetic decrement

Logical Bitwise Conditional Special

Arithmetic Operator-
Operator Description
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Remainder after division
Program-

#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

c = a+b;
printf("a+b = %d \n",c);

c = a-b;
printf("a-b = %d \n",c);

c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);

c=a%b; // gives the remainder


printf("Remainder when a divided by b = %d \n",c);

return 0;
}

Note – The difference between division / and remainder % is that division gives
the quotient and % modulus operator % gives the remainder.

2- Increment and Decrement

C programming has two operators increment ++ and decrement -- to


change the value of an operand (constant or variable) by 1. Increment ++
increases the value by 1 whereas decrement -- decreases the value by 1.

Operator Description
++ Increases the value by 1
-- Decreases the value by 1

Type of Increment Operator

• pre-increment
• post-increment

pre-increment (++ variable)

In pre-increment first increment the value of variable and then used inside
the expression (initialize into another variable).

Syntax

++ variable;

post-increment (variable ++)

In post-increment first value of variable is used in the expression


(initialize into another variable) and then increment the value of variable.

Syntax

variable ++;

#include<stdio.h>
void main()
{
int a,b,result;
a=10,b=5;

printf("value of a is %d\t\n",a);
result=++a;
printf("value of a is %d\t\n",result);

printf("value of b is %d\t\n",b);
result=b++;
printf("value of b is %d\t\n",result);
}

3- Assignment Operator

An assignment operator is used for assigning a value to a variable. The


most common assignment operator is =, along with equal operator the other
operators used are given in the list. They are called as short hand assignment
operator.
Operator Example Can also be written as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b
/= a /= b a = a/b

%= a %= b a = a%b

#include <stdio.h>
int main()
{
int a = 22, c;
c = a;
printf("c = %d \n", c);

c += a; // c = c+a
printf("Addition is c = %d \n", c);

c -= a; // c = c-a
printf("Substraction is c = %d \n", c);
c *= a; // c = c*a
printf("Multipliaction is c = %d \n", c);

c /= a; // c = c/a
printf("Division c = %d \n", c);
c %= a; // c = c%a
printf("Remainder is c = %d \n", c);
return 0;
}

4- Relational Operator

A relational operator checks the relationship between two operands.


Generally used with decision making two check between conditions.

Operator Description
== Equal to
> Greater than
< Less than
!= Not equal to
>= Greater than or equal to
<= Less than or equal to

// C Program to demonstrate the working of relational operators


#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d = %d \n", a, b, a == b); // true
printf("%d > %d = %d \n", a, b, a > b); //false
printf("%d < %d = %d \n", a, b, a < b); //false
printf("%d < %d = %d \n", a, c, a < c); //true
printf("%d != %d = %d \n", a, b, a != b); //false
printf("%d >= %d = %d \n", a, b, a >= b); //true
printf("%d <= %d = %d \n", a, c, a <= c); //true

5- Logical Operator
An expression containing logical operator returns either 0 or 1 depending
upon whether expression results true or false. Logical operators are commonly
used in decision making in C programming.
C language supports following 3 logical operators. Suppose a=1 and b=0,

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false


// C Program to demonstrate the working of logical operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) equals to %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) equals to %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) equals to %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) equals to %d \n", result);
return 0;
}

6- Bitwise Operator

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Truth table for Bit wise Operator -

a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0
Bitwise operators perform manipulations of data at bit level. These
operators also perform shifting of bits from right to left. Bitwise operators are
not applied to float or double.

/* C Program to demonstrate use of bitwise operators */


#include<stdio.h>
int main()
{
unsigned char a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a&b); // The result is 00000001
printf("a|b = %d\n", a|b); // The result is 00001101
printf("a^b = %d\n", a^b); // The result is 00001100
printf("~a = %d\n", a = ~a); // The result is 11111010
printf("b<<1 = %d\n", b<<1); // The result is 00010010
printf("b>>1 = %d\n", b>>1); // The result is 00000100
return 0;
}

7- Conditional Operator

A conditional operator is a ternary operator, that is, it works on 3 operands.

conditionalExpression ? expression1 : expression2

If conditionalExpression is true, expression1 is evaluated.


If conditionalExpression is false, expression2 is evaluated.
Program-

#include<stdio.h>
void main()
{
int n1,n2,max;
printf("Enter any two number \n");
scanf("%d%d",&n1,&n2);
max=(n1>n2)?n1:n2;
printf("Greater number is %d",max);
}

8 – Special Operator

Operator Description Example

sizeof(x) return size of the


sizeof Returns the size of an variable
variable x
Returns the address of an &x ; return address of the
&
variable variable x

* Pointer to a variable *x ; will be pointer to a variable x

Program-

#include<stdio.h>
void main()
{
printf("Size of char is %d ",sizeof(char));
printf("\nSize of int is %d ",sizeof(short int));
printf("\nSize of float is %d ",sizeof(float));
printf("\nSize of double is %d ",sizeof(double));
}

Operator precedence and associativity

Precedence

The precedence of operators determines which operator is executed first if


there is more than one operator in an expression.

10 + 20 * 30 is calculated as 10 + (20 * 30)

Associativity

Associativity is used when there are two or more operators of same


precedence is present in an expression. For example multiplication and division
arithmetic operators have same precedence, lets say we have an expression
5*2/10, this expression would be evaluated as (5*2)/10 because the associativity
is left to right for these operators. Similarly 20/2*5 would be calculated as
(20*2)/5.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift <<>> Left to right

Relational <<= >>= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

#include <stdio.h>
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}

Data Type Conversion/Type Casting

When variables and constants of different types are combined in an


expression then they are converted to same data type. The process of converting
one predefined type into another is called type conversion.

Type conversion in c can be classified into the following two types:

Implicit Type Conversion

When the type conversion is performed automatically by the compiler

Explicit Type Conversion

The type conversion performed by the programmer by posing the data type
of the expression of specific type is known as explicit type conversion.

You might also like