Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CCP 3 Unit

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

C Programming Notes

3rd Unit

A programming language is a computer language programmers use to develop software


programs, scripts, or other sets of instructions for computers to execute.

Computers “think” in binary — strings of 1s and 0s.

Programming languages allow us to translate the 1s and 0s into something that humans can understand
and write.

A programming language is made up of a series of symbols that serves as a bridge that allow humans to
translate our thoughts into instructions computers can understand.

There are two type of programming langauges

1. High Level Programming language


2. Low level Programming language

High Level Languages


When we think about computer programmers, we are probably thinking about people
who write in high-level programming languages.

High level languages are written in a form that is close to our human language, enabling
to programmer to just focus on the problem being solved.
These programmer friendly languages are called ‘high level’ as they are far removed
from the machine code instructions understood by the computer.

Examples include: C++, Java, Pascal, Python, Visual Basic.

Advantages

 Easier to modify as it uses English like statements


 Easier/faster to write code as it uses English like statements
 Easier to debug during development due to English like statements
 Portable code – not designed to run on just one type of machine

Low Level Languages


Low level languages are used to write programs that relate to the specific architecture
and hardware of a particular type of computer.

They are closer to the native language of a computer (binary), making them harder for
programmers to understand.

Examples of low level language:

 Assembly Language
 Machine Code

Assembly Language

Few programmers write programs in low level assembly language, but it is still used for
developing code for specialist hardware, such as device drivers.

It is easy distinguishable from a high level language as it contains few recognisable


human words but plenty of mnemonic code.

Machine Code

Programmers rarely write in machine code (binary) as it is difficult to


understand.
C Language Introduction
C is a procedural programming language.

It was initially developed by Dennis Ritchie in the year 1972.

It was mainly developed as a system programming language to write an operating system.

C programming is considered as the base for other programming languages, that is why it is known as
mother language.

It is one of the most popular computer languages today because of its structure, high-level
abstraction, machine independent feature etc.

Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around the early 1970s.
 The language was formalized in 1988 by the American National Standard
Institute (ANSI).
 The UNIX OS was totally written in C.
 Today C is the most widely used and popular System Programming Language.
 Most of the state-of-the-art software have been implemented using C.

It can be defined by the following ways:

1. Mother language

2. System programming language

3. Procedure-oriented programming language

4. Structured programming language

5. Mid-level programming language


C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as B, BCPL, etc.

Initially, C language was developed to be used in UNIX operating system. It inherits many features of
previous languages such as B and BCPL.

History of C language
C language has evolved from three different structured language ALGOL, BCPL and B
Language.
It uses many concepts from these languages while introduced many new concepts such
as datatypes, struct, pointer etc.
In 1989, the language was formalised by American National Standard
Institute(ANSI).

In 1990, a version of C language was approved by the International Standard


Organisation(ISO) and that version of C is also referred to as C89.
Latest Version of C
The current latest version of C language is C11, which was introduced in 2011. It is
supported by all the standard C language compilers.

Features of C language
 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.

 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 functions and add it to C library.

 C language is the most widely used language in operating systems and embedded

system development today.

Compilation Process in C language

What is the Compilation Process?

The compilation is a method whereby the source code is converted into object code.
It is achieved with compiler assistance.

The compiler tests the source code for syntactic or structural errors and produces the
object code if the source code is error-free.

The method of compiling can be divided into four stages, i.e., pre-processing, compilation,
assembly, and linking.

 Preprocessor
 Compiler
 Assembler
 Linker
 First, the input file is transferred to the preprocessor, i.e., hello.c, and then the preprocessor
transforms the source code to extended source code. The expanded source code extension
will be hello.i.
 The expanded source code is transferred to the compiler, and this expanded source code is
converted to assembly code by the compiler. The assembly code extension will be a hello.s.
 It then sends this assembly code to the assembler, which transforms the assembly code into
object code.
 When an object code has been developed, the linker generates the executable file.

C Token

A smallest individual unit in C program is known as C Token.


Tokens are either keywords, identifier, constants, Variables or
any symbol which has some meaning in C language.
A C program can also be called as a collection of various tokens.
Semicolon ;
Semicolon ; is used to mark the end of a statement and beginning of another statement.
Absence of semicolon at the end of any statement, will mislead the compiler to think
that this statement is not yet finished and it will add the next consecutive statement
after it, which may lead to compilation(syntax) error.

#include

int main()

printf("Hello,World")

return 0;

Comments
Comments are plain simple text in a C program that are not compiled by the compiler.
We write comments for better understanding of the program.

There are two ways in which we can write comments.

1. Using // This is used to write a single line comment.


2. Using /* */: The statements enclosed within /* and */ , are used to write multi-
line comments.

Some basic syntax rule for C program

 C is a case sensitive language so all C instructions must be written in lower case letter.

 All C statement must end with a semicolon.

 Whitespace is used in C to describe blanks and tabs.

 Whitespace is required between keywords and identifiers.

Basic Structure of C Program

1) Documentation Section- Here we write comments

 Single Line Comment //


 Multiline Comment /* */

2) Pre-processor Directive

 Link Section
 Definition Section

3) Global Declaration Section

4) Main Function Section

 Declaration Part
 Executable Part

5) Sub Program Section

User Defined Function 1


User Defined Function 2
.
.
.
User Defined Function n

Compile and Run C Program

1. Download a full-fledged IDE like Turbo C or Microsoft Visual C++, which comes along

with a C language compiler.

Using an IDE - Turbo C


We will recommend you to use Turbo C IDE, oldest IDE for c programming. It is freely
available over internet and is good for a beginner.
Step 1 : Open turbo C IDE(Integrated Development Environment), click on File and then
click on New
Step 2 : Write the above example as it is

Step 3 : Click on compile or press Alt+f9 to compile the code

Step 4 : Click on Run or press Ctrl+f9 to run the code


Step 5 : Output

First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run the first c
program.

To write the first c program, open the C console and write the following code:

#include <stdio.h>

int main(){
printf("Hello C Language");

return 0;

#include <stdio.h> includes the standard input output library functions. The printf() function is
defined in stdio.h .

To compile and run a C language program, you need a C compiler. To setup a C language
compiler in your Computer/laptop, there are two ways:

Difference between int main() and void main()


and main()

Like any other function, main is also a function but with a special
characteristic that the program execution always starts from the ‘main’.
‘int’ and ‘void’ are its return type. So, let’s discuss all of the three one by
one.

 void main – The ANSI standard says "no" to the ‘void main’ and thus
using it can be considered wrong. One should stop using the ‘void
main’ if doing so.

 int main – ‘int main’ means that our function needs to return some
integer at the end of the execution and we do so by returning 0 at the
end of the program. 0 is the standard for the “successful execution of
the program”.

 main – In C89, the unspecified return type defaults to int. So, main is
equivalent to int main in C89. But in C99, this is not allowed and thus
one must use int main.

So, the preferred way is int main.


C Keywords:
Keywords are reserved words that have special meaning in the C language.

The meaning of C language keywords has already been described in the C compiler.

These meanings cannot be changed.

Thus, keywords cannot be used as Variables names because that would try to change the
existing meaning of the keyword, which is not allowed.

There is a total of 32 keywords in the C language.

Example of keyword:
int marks;

List of Keywords in C:

auto double int struct

break else long switch

case enemy register typedef

const extern return union

char float short unsigned

continue for signed volatile

default goto sizeof void

do if static while
Note:
 A keyword name cannot be used as a variable name.
 Keywords must be written in lower case.
 It specifies the type/kind of entity.

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

Data types in c refer to an extensive system used for declaring variables or functions of different
types.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum


Void Data Type void

Following are the examples of some very common data types used in C:
 char: The most basic data type in C.
It stores a single character and requires a single byte of memory in almost all compilers.

 int: As the name suggests, an int variable is used to store an integer.

 float: It is used to store decimal numbers (numbers with floating point value) with single
precision.

 double: It is used to store decimal numbers (numbers with floating point value) with
double precision.

Different data types also have different ranges upto which they can store numbers. These
ranges may vary from compiler to compiler. Below is list of ranges along with the
memory requirement and format specifiers on 32 bit gcc compiler.

Memory Format
Data Type (bytes) Range Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short
int 2 0 to 65,535 %hu
Memory Format
Data Type (bytes) Range Specifier

unsigned int 4 0 to 4,294,967,295 %u

-2,147,483,648 to
int 4 2,147,483,647 %d

-2,147,483,648 to
long int 4 2,147,483,647 %ld

unsigned long
int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long 0 to
long int 8 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 %f

double 8 %lf

long double 16 %Lf


We can use the sizeof() operator to check the size of a variable. See the following C
program for the usage of the various data types:

Variables in C

Variable in C
When we want to store any information, we store it in an address of the computer.

Instead of remembering the complex address where we have stored our information, we name
that address.

The naming of an address is known as variable.

Variable is the name of memory location.

In other words, variable is a name which is used to store a value of any type during program
execution.

A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can
be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Variable Declaration:

A typical variable declaration is of the form:

type variable_name;
or for multiple variables:
type variable1_name, variable2_name, variable3_name;

The example of declaring the variable is given below:

int a;

float b;

char c;
Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

int a=10,b=20;//declaring 2 variable of integer type

float f=20.8;

char c='A';

Rules for defining variables


o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:

int a;

int _ab;

int a30;

Invalid variable names:

int 2;

int a b;

int long;

Types of Variables in C
There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

1. void function1(){
2. int x=10;//local variable
3. }

You must have to initialize the local variable before it is used.

Global Variable
A variable that is declared outside the function or block is called a global variable.

Any function can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

int value=20;//global variable

void function1(){

int x=10;//local variable

Static Variable
A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1(){

int x=10;//local variable

static int y=10;//static variable

x=x+1;

y=y+1;

printf("%d,%d",x,y);

}
If you call this function many times, the local variable will print the same value for each function call,
e.g, 11,11,11 and so on. But the static variable will print the incremented value in each function call,
e.g. 11, 12, 13 and so on.

Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We can explicitly
declare an automatic variable using auto keyword.

void main(){

int x=10;//local variable (also automatic)

auto int y=20;//automatic variable

External Variable
We can share a variable in multiple C source files by using an external variable. To declare an external
variable, you need to use extern keyword.

myfile.h

extern int x=10;//external variable (also global)

program1.c

#include "myfile.h"

#include <stdio.h>

void printValue(){

printf("Global variable: %d", global_variable);

Constants In C

Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.

Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants as
well.
Constants are treated just like regular variables except that their values cannot be
modified after their definition.

Defining Constants:
In C/C++ program we can define constants in two ways as shown below:
1. Using #define preprocessor directive
2. Using a const keyword

Literals: The values assigned to each constant variables are referred to as the literals.
Generally, both terms, constants and literals are used interchangeably. For eg, “const int =
5;“, is a constant expression and the value 5 is refered to as constant integer literal.

Let us now learn about above two ways in details:

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


 identifierName: It is the name given to constant.
 value: This refers to any value assigned to identifierName.

Example

#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;
}

using a const keyword: Using const keyword to define constants is as simple as defining
variables, the difference is you will have to precede the definition with a const keyword.

#include <stdio.h>

int main()
{
// int constant
const int intVal = 10;

// Real constant
const float floatVal = 4.14;

// char constant
const char charVal = 'A';

// string constant
const char stringVal[10] = "ABC";

printf("Integer constant:%d \n", intVal );


printf("Floating point constant: %.2f\n", floatVal );
printf("Character constant: %c\n", charVal );
printf("String constant: %s\n", stringVal);

return 0;
}

What are C Identifiers?


In C language identifiers are the names given to variables, constants, functions, and
user-defined data. These identifiers are defined against a set of rules.

Rules for an Identifier:


 An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and
underscore(_).
 The first character of an identifier can only contain alphabet(a-z, A-Z) or
underscore (_).
 Identifiers are also case sensitive in C. For example, name and Name are two
different identifiers in C.
 Keywords are not allowed to be used as Identifiers.
 No special characters, such as a semicolon, period, whitespaces, slash, or comma
are permitted to be used in or as an Identifier.
When we declare a variable or any function in C language program, to use it we must
provide a name to it, which identified it throughout the program, for example:

int myvariable = "Studytonight";

Difference between Variable and Identifier?


An Identifier is a name given to any variable, function, structure, pointer or any other
entity in a programming language. While a variable, as we have just learned in this
tutorial is a named memory location to store data which is used in the program.

Identifier Variable

Identifier is the name given to a variable, function While, variable is used to name a memory location which
etc. stores data.
An identifier can be a variable, but not all All variable names are identifiers.
indentifiers are variables.

Example:
Example:
// int variable
// a variable
int a;
int studytonight;
// float variable
// or, a function
float a;
int studytonight() {

..

C Character set
In C language characters are grouped into the following categories,
 Letters(all alphabets a to z & A to Z).
 Digits (all digits 0 to 9).
 Special characters, ( such as colon :, semicolon ;, period ., underscore _,
ampersand & etc).
 White spaces.

What Is Console In C
A console is an operating system window through which a user can communicate with the
operating system or we can say a console is an application in which we can give text as an input
from the keyboard and get the text as an output from the computer end.
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:

1. 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.

1. scanf("format string",argument_list);

Program to print cube of given number


Let's see a simple example of c language that gets input from the user and prints the cube of the given
number.

#include<stdio.h>

int main(){

int number;

printf("enter a number:");

scanf("%d",&number);

printf("cube of number is:%d ",number*number*number);

return 0;

Output
enter a number:5
cube of number is:125

The scanf("%d",&number) statement reads integer number from the console and stores the given value
in number variable.

The printf("cube of number is:%d ",number*number*number) statement prints the cube of number
on the console.

Program to print sum of 2 numbers


Let's see a simple example of input and output in C language that prints addition of 2 numbers.

#include<stdio.h>

int main(){

int x=0,y=0,result=0;

printf("enter first number:");

scanf("%d",&x);

printf("enter second number:");

scanf("%d",&y);

result=x+y;

printf("sum of 2 numbers:%d ",result);

return 0;

Output

enter first number:9


enter second number:9
sum of 2 numbers:18

C Input and Output


C programming language provides many built-in functions to read any given input and
to display data on screen when there is a need to output the result.
All these built-in functions are present in C header files, we will also specify the name of
header files in which a particular function is defined while discussing about it.

scanf() and printf() functions


The standard input-output header file, named stdio.h contains the definition of the
functions printf() and scanf(), which are used to display output on screen and to take
input from user respectively.

You must be wondering what is the purpose of %d inside the scanf() or printf() functions.
It is known as format string and this informs the scanf() function, what type of input to
expect and in printf() it is used to give a heads up to the compiler, what type of output to
expect.

Format String Meaning

%d Scan or print an integer as signed decimal number

%f Scan or print a floating point number

%c To scan or print a character

%s To scan or print a character string. The scanning ends at whitespace.

NOTE : printf() function returns the number of characters printed by it,


and scanf() returns the number of characters read by it.

int i = printf("studytonight");
getchar() & putchar() functions
The getchar() function reads a character from the terminal and returns it as an integer.
This function reads only single character at a time. You can use this method in a loop in
case you want to read more than one character.
The putchar() function displays the character passed to it on the screen and returns the
same character.
This function too displays only a single character at a time. In case you want to display
more than one characters, use putchar() method in a loop.

#include <stdio.h>

void main( )

int c;

printf("Enter a character");

/*

Take a character as input and

store it in variable c

*/

c = getchar();

/*

display the character stored

in variable c

*/

putchar(c);

}
C printf and scanf functions:

 printf() and scanf() functions are inbuilt library functions in C programming language which are
available in C library by default. These functions are declared and related macros are defined in
“stdio.h” which is a header file in C language.
 We have to include “stdio.h” file as shown in below C program to make use of these printf() and
scanf() library functions in C language.
1. PRINTF() FUNCTION IN C LANGUAGE:
 In C programming language, printf() function is used to print the (“character, string, float, integer,
octal and hexadecimal values”) onto the output screen.
 We use printf() function with %d format specifier to display the value of an integer variable.
 Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double
and %x for hexadecimal variable.
 To generate a newline,we use “\n” in C printf() statement.
Note:
 C language is case sensitive. For example, printf() and scanf() are different from Printf() and Scanf().
All characters in printf() and scanf() functions must be in lower case.

2. SCANF FUNCTION IN C LANGUAGE:


 In C programming language, scanf() function is used to read character, string, numeric data from
keyboard
 Consider below example program where user enters a character. This value is assigned to the
variable “ch” and then displayed.
 Then, user enters a string and this value is assigned to the variable “str” and then displayed.

EXAMPLE PROGRAM FOR C PRINTF AND SCANF FUNCTIONS IN C PROGRAMMING


LANGUAGE:
C

1 #include <stdio.h>

2 int main()

3 {

4 char ch;

5 char str[100];

6 printf("Enter any character \n");

7 scanf("%c", &ch);
8 printf("Entered character is %c \n", ch);

9 printf("Enter any string ( upto 100 character ) \n");

10 scanf("%s", &str);

11 printf("Entered string is %s \n", str);

12 }

OUTPUT :
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai

 The format specifier %d is used in scanf() statement. So that, the value entered is received as an
integer and %s for string.
 Ampersand is used before variable name “ch” in scanf() statement as &ch.
 It is just like in a pointer which is used to point to the variable. For more information about how
pointer works, please click here.
KEY POINTS TO REMEMBER IN C PRINTF() AND SCANF():
1. printf() is used to display the output and scanf() is used to read the inputs.
2. printf() and scanf() functions are declared in “stdio.h” header file in C library.
3. All syntax in C language including printf() and scanf() functions are case sensitive.

getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-
DOS compilers like Turbo C. It is not part of the C standard library or ISO C

Like above functions, it reads also a single character from keyboard. But it does not use
any buffer, so the entered character is immediately returned without waiting for the enter
key.
Syntax:
int getch();

// Example for getch() in C


#include <stdio.h>
#include <conio.h>
int main()
{
printf("%c", getch());
return 0;
}

getche()
Like getch(), this is also a non-standard function present in conio.h. It reads a single
character from the keyboard and displays immediately on output screen without waiting
for enter key.
Syntax:
int getche(void);

#include <stdio.h>
#include <conio.h>
// Example for getche() in C
int main()
{
printf("%c", getche());
return 0;
}

Operators in C Language
C language supports a rich set of built-in operators.

An operator is a symbol that tells the compiler to perform a certain mathematical or logical
manipulation.

Operators are used in programs to manipulate data and variables.

C operators can be classified into following types:

 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Special operators
Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic
arithmetic operators.

I. Unary Operators: Operators that operates or works with a single operand are
unary operators. For example: (++ , –-)
II. Binary Operators: Operators that operates or works with two operands are
binary operators. For example: (+ , – , * , /)

You might also like