[go: up one dir, main page]

0% found this document useful (0 votes)
7 views19 pages

Chapter 2

Chapter 2 provides an overview of C programming, covering its introduction, history, features, and basic structure. It discusses essential components such as preprocessor directives, data types, variables, and constants, along with the significance of the main function and C tokens. The chapter emphasizes C's role in system programming and its applications in various fields, highlighting its efficiency and versatility.
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)
7 views19 pages

Chapter 2

Chapter 2 provides an overview of C programming, covering its introduction, history, features, and basic structure. It discusses essential components such as preprocessor directives, data types, variables, and constants, along with the significance of the main function and C tokens. The chapter emphasizes C's role in system programming and its applications in various fields, highlighting its efficiency and versatility.
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
You are on page 1/ 19

Chapter 2 Overview of C Programming (3 hours)

2.1 Introduction to C programming

2.2 History and Importance of C

2.3 C Headers and Library Functions

2.4 Basic Structure of a C Program

2.5 Preprocessor Directives

2.6 Tokens in C (Character set, Keywords and Identifiers)

2.7 Type Casting (Implicit and Explicit)

2.8 Data Types, Variables and Constants

2.9 Compiler and IDE for C Programming

Introduction to C Programming
• C is general purpose Structured programming language.

• C is high level language and is the upgraded version of ‘Basic Combined Program
Language’

• C language was designed at Bell laboratories in the early 1970’s by Dennis Ritchie.

• C being popular in the modern computer world can be used in Mathematical


Scientific, Engineering and Commercial applications.

• The most popular Operating system UNIX is written in C language.

• This language also has the features of low level languages and hence

called as “System Programming Language”


History of C Programming

C is one of the high-level programming languages developed by Dennis Ritchie.


C was originally developed for UNIX operating system to beat the issues of previous
languages such as B, BCPL, etc.
The UNIX operating system development started in the year 1969, and its code was
rewritten in C in the year 1972.
In 1985, Windows 1.0 was released. Even though Windows source code isn’t publicly
available on the market, it’s been stated that its kernel is mostly written in C.
In 1991, Linux kernel development started, and it’s additionally written in C.
After a year it was released under the GNU license and was used as part of the GNU
Operating System.
The GNU operating system was started using C and Lisp programming languages. So,
many of its components are written in C.
In 1977, Oracle database development started, and in 1983 its code was rewritten from
assembly to C. It became one in all the foremost widespread databases within the world.
Now a days C is exclusively used for building OS, application packages and customized
software. Because of its power and efficiency, it has gained more popularity.
C is increasingly used by system programmers, application developers and researchers for
a spread of programming tasks.

Features of C language
• Simple general purpose language
• It has rich set of Operators
• Program execution are fast and efficient
• Can easily manipulates with bits, bytes and addresses
• Varieties of data types are available
• Separate compilation of functions is possible and such functions can be called by any C
program
• Can be applied in System programming areas like operating systems, compilers &
Interpreters, Assembles, Text Editors, Print Spoolers, Network Drivers, Modern Programs,
Data Bases, Language Interpreters, Utilities, etc.
Execution of C Program

Preprocessor directives

C Preprocessor is a collection of special statement called directives that are


executed at the beginning of compilation process.
Preprocessor programs provide preprocessor directives that tell the compiler
to preprocess the source code before compiling.
Preprocessor directives change the text of the source code and the result is a
new source code without these directives.
Usually appears beginning of a program
It follows special syntax rule
All begin with symbol # in column and do not require semicolon at end
Example:

#define age 20
#define PI 3.1415 // symbolic constant
#define:

It substitutes a preprocessor using macro.

#include:

It helps to insert a certain header from another file.

#undef:

It undefines a certain preprocessor macro.

#define PI 3.14

#undef PI

#ifdef:

It returns true if a certain macro is defined.

#ifndef:

It returns true if a certain macro is not defined.

#if, #elif, #else, and #endif:

It tests the program using a certain condition; these directives can be nested too.

#include <stdio.h>
#define xyz 10
int main()
{
#ifdef xyz
printf("Your lottery number is %d.\n", xyz);
#else
printf("error printing lottery number");
#endif
return 0;
}
Header files

A C header file is a text file that contains pieces of code written in the C programming language.
The name of a header file, by convention, ends with the .h extension.

It is inserted inside a program by coding the #include preprocessor directive.

In C language, header files contain a set of predefined standard library functions. The .h is the
extension of the header files in C and we request to use a header file in our program by
including it with the C preprocessing directive “#include”.

C Header files offer the features like library functions, data types, macros, etc by importing
them into the program with the help of a preprocessor directive “#include”.

There are two forms of including header file:


#include<file>
#include "file"

C Standard Library Functions


printf () and scanf () in C

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);
getch() function

The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly
used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes
a single value to exit from the console screen. It can also be used to read a single byte character
or string from the keyboard and then print.
syntax:
getch());

Use of main function


A function is a block of code that performs a specific task.

The main function is an integral part of the programming languages such as C, C++, and Java.

The main function in C is the entry point of a program where the execution of a program
starts.

It is a user-defined function that is mandatory for the execution of a program because when a
C program is executed, operating system starts executing the statements int main () function.

return_type main ()
{
// Statement 1;
// Statement 2;
// and so on..
return;
}

Important Points about C main Function

It is the function where the program’s execution starts.


Every program has exactly one main function.
The name of this function should be “main” not anything else.
The main function always returns an integer value or void.
The main function is called by OS, not the user.
Structure of C Program

A C program basically consists of the following parts −

• Document section
comments lines
• Link Section
provides instruction to compiler to link function with program: preprocessor directives
and header files
• Definition Section
all symbolic constants are defined
• Global Declaration Section
global variables are defined
• Main Function
void main() {}
• Subprogram Section
user defined functions

#include<stdio.h>
#include<conio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}

C Tokens
• C tokens are basic building block in c language
• Individual words and punctuation marks are called tokens

• Similarly, the smallest individual unit in a c program is known as a token.

• C program is also a collection of tokens, comments, and whitespaces.

In C Programming, tokens are of six types. They are:


Keyword

• C keywords are the words that convey a special meaning to the c compiler.

• The keywords cannot be used as variable names because by doing so, we are trying to
assign a new meaning to the keyword which is not allowed.

• There are 32 Keywords in C


• C Keywords are also called as Reserved words
Identifiers
• Identifiers are used as the general terminology for the names of variables, functions and
arrays.

• These are user defined names consisting of arbitrarily long sequence of letters and
digits with either a letter or the underscore (_) as a first character.

There are certain rules that should be followed while naming c identifiers:

• They must begin with a letter or underscore (_).

• They must consist of only letters, digits, or underscore. No other special character is
allowed.

• It should not be a keyword.

• It must not contain white space.

• It should be up to 31 characters long as only first 31 characters are significant


Questions: Which of the followings are identifiers.

• record1
• file_3
• #tax
• goto

• Name-and-address

• void

Operators
• C operators are symbols that triggers an action when applied to C variables and other
objects. The data items on which operators act upon are called operands.

• Depending on the number of operands that an operator can act upon, operators can be
classified
• Unary Operators:

Those operators that require only single operand to act upon are known as unary
operators. Eg: (x++)

• Binary Operators:

Those operators that require two operands to act upon are called binary operators. Eg:
(x+y)

• Ternary Operators:

These operators requires three operands to act upon. Eg: (A > 100 ? 0 : 1)

Constants
• C constants refers to the data items that do not change their value during the program
execution.

• These fixed values are also called literals.

For example “13” is a string literal and not number 13. ‘a’ and “a” are different.

Several types of C constants that are allowed in C are:


1.Integer Constants

2.Real Constants

3.Character Constants

1.Integer constants

• Integer constants are whole numbers without any fractional part.

• It must have at least one digit and may contain either + or – sign.

• A number with no sign is assumed to be positive

• Decimal Integer Constants:

Integer constants consisting of a set of digits, 0 through 9

• Octal Integer Constants:

Integer constants consisting of sequence of digits from the set 0 through 7

• Hexadecimal Integer Constants:

Hexadecimal integer constants are integer constants having sequence of


digits preceded by 0x or 0X
2.Floating / Real constants

• The numbers having fractional parts are called real or floating point constants.

• These may be represented in one of the two forms called fractional

form or the exponent form and may also have either + or – sign preceding it.

Eg: 0.05, -0.905, 562.05, 0.015

3. Character Constants

• A character constant contains one single character enclosed within single quotes.

Examples of valid character constants: ‘a’ , ‘Z’, ‘5’

• It should be noted that character constants have numerical values known as ASCII
values, for example, the value of ‘A’ is 65 which is its ASCII value.
String

• String constants are sequence of characters enclosed within double quotes.

For example,

• “hello”
• “abc”
• “hello911”

Special Symbols
• The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose.

[](){},;:*…=#

• Braces {}: These opening and ending curly braces marks the start and end of a block of
code containing more than one executable statement.

• Parentheses (): These special symbols are used to indicate function calls and function
parameters.

• Brackets [ ]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Data Types in ‘C’

• There are four basic data types in C language.

- They are

i. Integer data,

ii. Character data,

iii. Floating point data

iv. Double data types.

a. Character data:

• Any character of the ASCII character set can be considered as a character data types and
its maximum size can be 1 byte or 8 bits long.

• Char is the keyword used to represent character data type in C.

• Char - a single byte size, capable of holding one character


b. Integer data:

• The keyword ‘int’ stands for the integer data type in C and its size is either 16 or 32 bits.
C. Floating point data: -

• The numbers which are stored in floating point representation with mantissa and
exponent are called floating point (real) numbers.
• These numbers can be declared as ‘float’ in C.
Variables

• In programming, a variable is a container (storage area) to hold data.

• To indicate the storage area, each variable should be given a unique name (identifier).

• Variable names are just the symbolic representation of a memory location.

For example: int playerScore = 95;

• Here, playerScore is a variable of integer type. The variable is assigned value: 95.

• The value of a variable can be changed, hence the name 'variable'.

• In C programming, we have to declare a variable before you can use it

Constants

If you don't want others (or yourself) to change existing variable values, you can use
the const keyword.

This will declare the variable as "constant", which means unchangeable and read-only:

#define TRUE 1

#define pi 3.14

const int a=5;

Use of escape sequences

The escape sequence in C is the characters or the sequence of characters that can be
used inside the string literal.
The purpose of the escape sequence is to represent the characters that cannot be
used normally using the keyboard.
Some escape sequence characters are the part of ASCII charset but some are not.
Sequence Name Description

\b Backspace It is used to move the cursor one place backward.

\n New Line It moves the cursor to the start of the next line.

Horizontal It inserts some whitespace to the left of the cursor and moves
\t
Tab the cursor accordingly.

\v Vertical Tab It is used to insert vertical space.

\\ Backlash Use to insert backslash character.

\’ Single Quote It is used to display a single quotation mark.

Double
\” It is used to display double quotation marks.
Quote

Question
\? It is used to display a question mark.
Mark

\0 NULL It represents the NULL character.

Type Conversions
The operands of a binary operator must have the same type and the result is also of the same
type.
Integer division:
c = (9 / 5)*(f - 32)

The operands of the division are both int and hence the result also would be int. For correct
results, one may write

c = (9.0 / 5.0)*(f - 32)


In case the two operands of a binary operator are different, but compatible, then they are
converted to the same type by the compiler. The mechanism (set of rules) is called Automatic
Type Casting.

c = (9.0 / 5)*(f - 32)

It is possible to force a conversion of an operand. This is called Explicit Type casting.

c = ((float) 9 / 5)*(f - 32)

Typecasting in C is the process of converting one data type to another data type by the
programmer using the casting operator during program design.

In typecasting, the destination data type may be smaller than the source data type when
converting the data type to another data type, that’s why it is also called narrowing conversion.

Syntax:
int x;
float y;

y = (float) x;

1. Implicit Type Casting

Implicit type casting in C is used to convert the data type of any variable without using
the actual value that the variable holds.
It performs the conversions without altering any of the values which are stored in the
data variable.
Conversion of lower data type to higher data type will occur automatically.
Integer promotion will be performed first by the compiler. After that, it will determine
whether two of the operands have different data types.

Using the hierarchy below, the conversion would appear as follows if they both have varied
data types:

Example:
int x = 1;
char y = 'A';
x = x + y;
Ans:
x=int+char;
x=int+ASCII Value of char; x=1+65; x=66
float z = x + 1.0;
printf("x = %d, z = %f", x, z);

int a = 15, b = 2;
float div;
div=a/b;
div=?
Ans: a/b=15/2=7; div=7.0

2. Explicit Type Casting

There are some cases where if the datatype remains unchanged, it can give incorrect
output. In such cases, typecasting can help to get the correct output and reduce the
time of compilation.
In explicit type casting, we have to force the conversion between data types.
This type of casting is explicitly defined within the program.

double x = 2.6;
int sum = (int)x + 1;
printf("sum = %d", sum);

What is IDE

IDE stands for Integrated Development Environment. It is a software application that provides
facilities for developing software. It consists of tools such as source code editor, automation
tools, and debugger. Most IDEs have compilers and interpreters. Therefore, it is easier to write
the code and compile it. Some IDEs support various languages.
Tubo C
Code::Blocks
Visual Studio
NetBeans
Eclipse
Dev C++

You might also like