Unit - 1 Summary CPRGM

You might also like

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

UNIT 1:Introduction Programming in C

OVERVIEW OF C
C is a general-purpose, procedural computer programming language developed in 1972 by
Dennis M. Ritchie at the Bell Telephone Laboratories to develop the Unix operating system.
C is a very popular programming language because it is simple, efficient and reliable. C has
now become a widely used professional language for various reasons.
• Easy to learn
• Structured language
• It produces efficient programs.
• It can handle low-level activities
• It can be compiled on a variety of computer platforms.
It is considered to be a middle level language since it has the features of both the low level
and the high level languages. Some examples of the use of C is used to develop Operating
Systems, Language compilers, Assemblers, Text Editors, Network Drivers, Data Bases,
Language Interpreters, Utilities etc.
THE STRUCTURE OF A C PROGRAM
Every C program includes the following components:
➢ Documentation Section →comments
➢ Preprocessor directives →Header Files
➢ Definition Section →Defining Symbolic Constants
➢ Global variable Declaration Section →Global variables declared
➢ main( ) function →Function heading
➢ A pair of flower brackets { }
➢ Declarations and executable statements
➢ User created sub-programs or functions
The above described components are organized as follows:
Documentation Section
Preprocessor directives
Definition Section
Global variable Declaration Section
main( )
{
Variable Declarations
Executable Statements
}
User created sub-programs or functions

Example:
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Explanation for the above example:
1. The first line of the program #include <stdio.h> is a preprocessor command which
tells a C compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where program execution begins.

I Semester BCA Kristu Jayanti College, Bengaluru Page |1


UNIT 1:Introduction Programming in C

3. The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program. Comments are like helping text in your C program and they are ignored by
the compiler.
4. The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
5. The next line return 0; terminates main( )function and returns the value 0.
6. In C program, the semicolon is a statement terminator. Each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.

**************************

DATA TYPES, CONSTANTS, VARIABLES

COMPONENTS OF ‘C’ LANGUAGE


The four main components of C language are:
1. The character set
2. Tokens
3. Variables
4. Data types
The character set:
Character set is set of valid characters that a language can recognize. A character represents
any letter, digit, or any other sign that can be used in a program.
Tokens:
The smallest individual unit in a program is known as a token. C has five tokens : Keywords,
Identifiers, Constants, Punctuations and Operators.
1. Keywords: Keywords are words which have been assigned specific meanings in the
context of C language programs.These reserved words may not be used as constant or
variable or any other identifier names. The following table gives a list of C keywords.
auto Else Long switch
break Enum Register typedef
case Extern Return union
char Float Short unsigned
const For Signed void
continue Goto Sizeof volatile
default If Static while
do Int Struct _Packed
double
2. Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item.
An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more
letters, underscores, and digits (0 to 9).C does not allow punctuation characters such as @, $,
and % within identifiers. C is a case sensitive programming language.

3. Constants:
Constants in C refer to fixed values that do not change during the execution of a program. Several
types of constants supported in C are shown in the chart below
I Semester BCA Kristu Jayanti College, Bengaluru Page |2
UNIT 1:Introduction Programming in C

4. Punctuations: Few characters are used as punctuators in C:

Example : + , - . . / : : < > ? @ [ \ ] { }

5. Operators: An operator is a symbol that tells the computer to perform certain mathematical
or logical manipulation on data stored in variables. The variables that are operated are termed
as operands. C operators can be classified into 8 types. These operators are given below.
1. Arithmetic operators +.-.*,/,%
2
- Assignment operators =
3. Relational operators <,<=,>,>=.= =,!=
4. Logical operators !,&&, | |
5. Conditional operators ?:
6. Increment and decrement ++,--
7. Bitwise operators !,&,|,~,^ ,<<,>>
8. Special operator sizeof , (comma)

Whitespace in C
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to
identify where one element in a statement.
Variables
A variable is an element that may take on any value of a specified type. Variables represent
named storage locations, whose value can be manipulated on running the program. A variable
is nothing but a name given to a storage area that our programs can manipulate. Each variable
in C has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable. The name of a variable can be composed of letters, digits, and the
underscore character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. The variables can be of the following types,
Type Description
char Character data type. Occupies 1 byte.
int Integer data type. Occupies 2 bytes.
I Semester BCA Kristu Jayanti College, Bengaluru Page |3
UNIT 1:Introduction Programming in C

float A single-precision floating point value. Occupies 4 bytes


double A double-precision floating point value. Occupies 8 bytes
void Represents the absence of type.

Variable Declaration in C
All variables must be declared before we use them in C program. Declaration specifies a
type, and contains a list of one or more variables of that type as follows:
datatype variable_list;
Here,datatype must be a valid C data type including char, int, float, double, or any user
defined data type etc., and variable_list may consist of one or more identifier names
separated by commas.
Example:
int i, j, k;
char c, ch;
float f, salary;
double d;

Variable Initialization in C
Variables are initialized (assigned a value) with an equal sign followed by a constant
expression. The general form of initialization is:
variable_name = value;
Example: a=10;
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows:
datatype variable_name = value;
Example: int n = 0; float avg=0;

Data types
The types in C can be classified as follows:
Types and Description
Basic Types:
1
They are built in data types and consists of integer, char, float and double type.
Enumerated types:
2 They used to define variables that can only be assigned certain discrete integer
values throughout the program.
The type void:
3
The type specifier void indicates that no value is available.
Derived types:
4 They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union
types and (e) Function types.
Integer Types
The table gives the detail about standard integer types with its storage sizes and value
ranges:
Type Storage size Value range
Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255

I Semester BCA Kristu Jayanti College, Bengaluru Page |4


UNIT 1:Introduction Programming in C

signed char 1 byte -128 to 127


-32,768 to 32,767 or -2,147,483,648 to
Int 2 or 4 bytes
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

To get the exact size of a type or a variable on a particular platform, the sizeof operator. The
expressions sizeof(type) yields the storage size of the object or type in bytes. Example to get
the size of int type on any machine:
#include <stdio.h>
#include <limits.h>
void main()
{
printf("Storage size for int : %d \n", sizeof(int));

Floating-Point Types
The table gives detail about standard float-point types with storage sizes and value ranges
and their precision:

Type Storage size Value range Precision


float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
3.4E-4932 to
long double 10 byte 19 decimal places
1.1E+4932

The void Type


The void type specifies that no value is available. It is used in three kinds of situations:
Types and Description
Function returns as void
There are various functions in C who do not return value or you can say they
1
return void. A function with no return value has the return type as void.
For example void fun (int a);
Function arguments as void
2 There are various functions in C who do not accept any parameter. A function
with no parameter can accept as a void. For example int rand(void);
Pointers to void
A pointer of type void * represents the address of an object, but not its type. For
3
example a memory allocation function void *malloc( size_t size ); returns a
pointer to void which can be casted to any data type.

I Semester BCA Kristu Jayanti College, Bengaluru Page |5


UNIT 1:Introduction Programming in C

Constants
The 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 also enumeration constants.
The constants are treated just like regular variables except that their values cannot be
modified after their definition.
Integer literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Examples:
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

Floating-point literals
A floating-point literal has an integer part, a decimal point, a fractional part and an exponent
part. Floating point literals either in decimal form or exponential form.The signed exponent
is introduced by e or E.
Examples of floating-point literals:
3.14159 /* Legal */
314159E-5L /* Legal */

Character constants
Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple variable
of char type.A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g.,
'\t'), or a universal character (e.g., '\u02C0').

Escape Characters
There are certain characters in C when they are preceded by a back slash they will have
special meaning and they are used to represent like newline (\n) or tab (\t). Here you have a
list of some of such escape sequence codes:

Escape
Meaning
sequence
\\ \ character
'
\'
character
"
\"
character
\? ?

I Semester BCA Kristu Jayanti College, Bengaluru Page |6


UNIT 1:Introduction Programming in C

character
Alert or
\a
bell
\b Backspace
\f Form feed
\n Newline
Carriage
\r
return
Horizontal
\t
tab
Vertical
\v
tab

String literals
String literals or constants are enclosed in double quotes "". A string contains characters that
are similar to character literals: plain characters, escape sequences, and universal characters.
Example: "hello dear"

Defining Constants
There are two simple ways in C to define constants:
1. Using #define preprocessor.
2. Using const keyword.

1.The #define Preprocessor


This is how to use #define preprocessor to define a constant:
#define identifier value

Example :
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
void main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
}
When the above code is compiled and executed, it produces following result:
value of area : 50

2.The const Keyword


The const prefix can be used to declare constants with a specific type as follows:
const type variable = value;
Example:
#include <stdio.h>
I Semester BCA Kristu Jayanti College, Bengaluru Page |7
UNIT 1:Introduction Programming in C

void main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
}
Storage Class
A storage class defines the scope (visibility) and life time of variables within a C program.
These specifiers precede the type that they modify. The storage classes which can be used in
a C Program are,
➢ auto
➢ register
➢ static
➢ extern

1. The auto Storage Class


The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto-which can only
be used within functions, i.e. local variables.

2. The register Storage Class


The register storage class is used to define local variables that should be stored in a register
instead of RAM.
Example:
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It
should also be noted that defining 'register' does not mean that the variable will be stored in
a register. It means that it MIGHT be stored in a register depending on hardware and
implementation restrictions.

3. The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence during
the lifetime of the program instead of creating and destroying it each time it comes into and
goes out of scope. Therefore, making local variables static allows them to be initialized only
once.
The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.

4. The extern Storage Class

I Semester BCA Kristu Jayanti College, Bengaluru Page |8


UNIT 1:Introduction Programming in C

The extern storage class is used to give a reference of a global variable that is visible to
ALL the program files.
Example:
{
extern int a;
}

*********************************

INPUT AND OUTPUT

Input refers to accepting data and output refers to displaying data. I/O functions together
form a library named stdio.h All data transfer operations in C are carried out using functions
available in the standard library. These library functions are classified into three types:
i) Console I/O Junctions: Functions which accept input from keyboard and produce output on
the screen.
ii) Disk I/O Junctions :Functions which perform I/O operations on secondary storage
devices like floppy disks or hard disks.
iii) Port I/O Junctions: Functions which perform I/O operations on various ports like printer
port, mouse port, etc.

Console I/O refers to the operations that occur at the keyboard and the screen of the
computer. Console I/O functions can be further classified into:
i. Formatted Console I/O
ii. Unformatted Console I/O

When we are saying Input that means to feed some data into program. This can be given in
the form of file or from command line. C programming language provides a set of built-in
functions to read given input and feed it to the program as per requirement.When we are
saying Output that means to display some data on screen, printer or in any file. C
programming language provides a set of built-in functions to output the data on the computer
screen as well as you can save that data in text or binary files.
The Standard Files
C programming language treats all the devices as files. So devices such as the display are
addressed in the same way as files and following three files are automatically opened when a
program executes to provide access to the keyboard and screen.
Standard File
Device
File Pointer
Standard
Stdin Keyboard
input
Standard
Stdout Screen
output
Standard Your
Stderr
error screen

The file pointers are the means to access the file for reading and writing purpose.
The getchar() & putchar() functions

I Semester BCA Kristu Jayanti College, Bengaluru Page |9


UNIT 1:Introduction Programming in C

The int getchar(void) function reads the next available character from the screen and returns
it as an integer. This function reads only single character at a time. This method can be used
in the loop in case you want to read more than one characters from the screen.
The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time. This method can be used in the
loop in case you want to display more than one character on the screen.

Example:
#include <stdio.h>
void main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
}
Output:
Enter a value : this is test
You entered: t

The gets() & puts() functions


The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until
either a terminating newline or EOF.
The int puts(const char *s) function writes the string s and a trailing newline to stdout.
Example:
#include <stdio.h>
void main( )
{
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
}
Output:
Enter a value : this is test
You entered: This is test

The scanf() and printf() functions


The int scanf(const char *format, ...) function reads input from the standard input stream stdin
and scans that input according to format provided.
Usage:
scanf(“Control string”, list of address of variables);

The int printf(const char *format, ...) function writes output to the standard output stream
stdout and produces output according to a format provided.
Usage:
printf(“Control string”, list of variables);

I Semester BCA Kristu Jayanti College, Bengaluru P a g e | 10


UNIT 1:Introduction Programming in C

The format can be a simple constant string, but you can specify %s, %d, %c, %f etc to print
or read strings, integer, character or float respectively.
Example:
#include <stdio.h>
void main( )
{
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s, %d ", str, i);

************************

I Semester BCA Kristu Jayanti College, Bengaluru P a g e | 11

You might also like