Class 9 | Fundamentals of C Programming | C Programming Notes

  • Programming

 

  • is high level general-purpose programming language developed by Dennis Ritchie at AT and TS Bell Lab in 1972.

 

The popular networks OS and UNIX Operating System was created using C language at Bells Lab. It is developed to overcome the drawbacks of previous language B.

 

Features of C language:

 

1C is a simple language that provides a structure approach.

 

2 C program can be executed in different machine, so it is also called machine independent language.

 

3C language can support the feature of both low-level and high-level language thats why it is also known as mid-level language.

 

4C provides a lot of inbuilt function that make the development fast.

 

5compilation and execution time of c language is fast.

 

6C language is extensible because it can easily adopt new features.

 

Advantage of c:

 

  1. C programs are portable across different computer platforms.

 

  1. C programs are easy to debug, test and maintain.

 

  1. Use of pointers make it very strong for memory manipulation.

 

  1. It has only 32 keywords so, it is easy to remember.

 

  1. Programs written in C can be reused.

 

  1. Its compiler is easily available.

 

  1. C provides dynamic memory allocation which means you are free to allocate memory at runtime.

 

  1. It has the ability to extend itself. Users can add their own functions to the C library.

 

Limitation of C:

 

  • C language does not have run-time checking.

 

  • It is case-sensitive. So, programmers must be extra careful while writing programs.

 

  • C does not provide strict data type checking, i.e., an integer value can be passed for a floating data type.

 

  • It doesnt support the concept of OOP. It only follows the POP approach.

 

Basic program structure

 

The basic programs structures of C programming language are given below:

 

  1. Document section

 

  1. Pre-processor directive/Link section

 

  1. Global declaration section

 

  1. Main function

 

  1. Sub program section

 

  1. Documentation section:

 

It consists of the details associated with the program. Such as name of program, author and other details.

 

 

  1. B) Link section:

 

It consists of the header files used in a program. The compiler is told to link the header files to the system libraries.

 

  1. Definition section:

 

This part is optional. Here, all the symbolic constants are defined. The keywords define is used in this part.

 

  1. Global declaration section:

 

All the global variables used in a program are declared here.

 

  1. Main function section:

 

All the C programs should have main function.

 

The main function consists of two parts:

 

A Declaration part is the part where all the variables are declared.

 

B Execution part is the part where all the code are written.

 

  1. F) Sub program section:

 

This section contains all the user defined functions that are called the main function.

 

 

Execution of C program:

 

C program executes in following four steps:

 

Create program   Compile program
     
     

 

 

 

 

 

 

 

Link program

 

 

 

 

 

 

 

Execute program

 

 

  • Creating a program:

 

Use a text editor like notepad++, turbo c or Dev C++ to write a C program. This file contains a source code that consists of executable code. The file should be saved with c. extension only.

 

  • Compiling the program:

 

The next step is to compile the program. The code is compiled by using compiler. Compiler converts executable code to object code.

 

  • Linking a program to library:

 

The object code of a program is linked with libraries that are needed for execution of a program. The linker is used to link the program with libraries. It creates a file with exe. extension.

 

  • Execution of program:

 

The final executable file is then run by dos command prompt or by any other software.

 

 

1) Program to display hello world

 

#include<stdio.h>

 

#include<conio.h>

 

Void main()

 

{

 

Printf(hello world!);

 

}

 

Pre-processor directives:

 

The pre-processor directives like the header files to the program codes. A processor command being with# (pound) symbol and already is built in C compiler. When a program is to compiled, the source code is the first pre-processed.

 

  • pre-processor has the following format #include<Header File>. Thus, the pre-processor directives line mustnt begins with any symbol.

 

Header file:

 

A file that is defined to be included at the beginning of the program in C language that contains definition of data types and declaration of variable. Variable used by function in the program called header file.

 

The header file in C contains standard library function the entire header file has extension .h. There are large number of header file in the program and some of them are rarely used given below:

 

  • #include<Stdio.h>:

 

It is a standard input output header file which contains functions such as scanf() and printf().

 

  • #include<conio.h>:

 

It is console input output header file which contains functions like clrscr(), getch()etc.

 

  • #include<graphics.h>:

 

This header file includes the definition of graphic file in C such as line(), circle(), rectangle() etc.

 

  • #include<string.h>:

 

This header file include definition of string handling functions like strlen(), strcpy() etc.

 

  • #include<math.h>:

 

This header file is used for the mathematical functions such as pow(), sqrt(), sin() etc.

 

  • #include<stdlib.h>:

 

It is general purpose standard library of C programming language which includes functions involving memory allocation, process control, conversing and others.

 

 

Tokens in C

 

Tokens are the smallest unit of C program which are meaningful to the compiler. Some tokens of C are:-

 

  • Constant:

 

Constants are values that do not change during the execution of a program. In C, constants can be of various types, such Real constant, Integer constant, Character constant, String constant.

 

  • Variable:

 

Variables are named memory locations used to store data that can change during program execution.

 

While declaring variables following points should be considered:

 

  • First character should always be letter or alphabet or underscore(_).

 

  • Keywords cant be used as a variable name.

 

  • Whitespace is not allowed.

 

  • C is case sensitive.

 

  • String:

 

Strings are sequences of characters enclosed within double quotes (“). In C, strings can be represented using the string class from the Standard Template Library (STL).

 

 

 

  • Keyword:

 

Keywords are reserved words that have special meanings and purposes in the C language. They cannot be used as identifiers (such as variable names).There are 32 keywords and all are written in lowercase.

 

  • Identifiers:

 

Identifiers are names given to various program elements, such as variables, functions, classes, and labels. Identifiers are used to uniquely identify these elements within a program.

 

Rules for naming identifier:-

 

  • first character must be in underscore or character

 

  • must consist of only alphabet, digit or underscore

 

  • must not be a keyword

 

  • must not contain white space

 

  • Operator:

 

Operators are special symbols that are used to perform operations on one or more operand.

 

Types of operator:-

 

  1. i) Unary Operator

 

Those operator which need only one operand to act upon is called unary operator. There are two unary operator increment and decrement.

 

A’ Increment operator:

 

It is used to increment value of operand by 1. It can be either pre increment (++b) or

 

post increment (b++).

 

B’ Decrement operator:

 

It is used to decrement value of operand by 1. It can be either pre decrement (–b) or

 

post decrement (b- -).

 

  1. ii) Binary operator

 

Those operator which needs two operand to act upon is called Binary operator. Types of binary operator:

 

A’ Arithmetic operator:

 

It is used to perform arithmetic operations like addition, subtraction, multiplication, division, etc.

 

Eg:

 

#include<stdio.h>

 

Void main()

 

{

 

Int a=20, b=7, c;

 

C=a+b;

 

Printf(sum is %d, c);

 

C=a-b;

 

Printf(difference is %d, c);

 

C=a*b;

 

Printf(product is %d, c);

 

C=a/b;

 

Printf(division is %d, c);

 

C=a%b;

 

Printf(remainder is %d, c);

 

}

 

 

 

B’ Logical Operator:                                                                                                                                                            It is used to

 

evaluate either the operation Is true or false. These operators are used in decision making. AND(&&), OR(||), NOT(!), etc.

 

C’ Assignment operator:

 

It is used to assign value for variable. The most common assignment operator is equivalent symbol(=).

 

D’ Relational operator:

 

It is used to check if the given condition is true or false. If the condition is true it returns 1 else returns 0.

 

Eg:

 

#include<stdio.h>

 

Void main()

 

{

 

Int a=10, b=20;

 

If(a.b)

 

Printf(%d is greater than %d, a, b);

 

}

 

E’ Bitwise operator:                                                                                                                                                              It is used to

 

manipulate data on the bit level. Bitwise AND(&), Bitwise OR(/),etc.

 

iii) Ternary Operator

 

Those operator which need three operands to act upon is called ternary operator. Conditional operator is a type of ternary operator.Conditional operators are type of operator that make use of condition inside the program. syntax of conditional operator:

 

if(condition)? True statement: False statement;

 

Operator precedence and associatively:

 

It is the rule that specifies the order in which certain operations are performed in an expression.

 

It refers to the direction of processing of an expression. It is used when two operands of same precedence are in a expression.

 

Let us consider an expression:

 

X=4*5+10

 

The result will be X=30, because *has higher precedence than + and the numbers get multiplied first resulting is 20 which is added with 10 to give a result of 30.

 

 

operator

 

 

Meaning of operator

 

 

associatively

 

()         Function call  
[]       Array element reference Left to Right
_>   Indirect member section  
.             Direct member section  
               
!           Logical negation  
  ~           Bitwise(1s) complement  
  +           Unary plus  
              Unary minus  
  ++     Increment  
          Decrement Right to Left
  &       Address  
  *           Pointer reference  
  Size of(type)   Returns the size of an object  
                Typecast(conversion)  
               
*           Multiply  
/           Divide  
%     Remainder Left to Right
+           Addition  
          subtraction  
       
<<   Left shift  
>>   Right shift  
<           Less than  
<=   Less than or equal  
>           Greater than Left to Right
>=   Greater than or equal  
==   Equal to  
!=     Not equal to  
       
&&   Logical AND Left to Right
||     Logical OR  
         
?:     Conditional operator  
=           Simple assignment  
*=   Assign product  
/=     Assign quotient  
%=   Assign remainder Right to Left
+=   Assign sum  
-=     Assign difference  
<<=   Assign left shift  
>>=   Assign right shift  
                 
,             Comma operator Left to Right
                   

 

 

 

Character set:

 

The term “character set” refers to a specific collection of characters and symbols that a computer system can understand and manipulate. It’s essentially a mapping between numbers (codes) and characters. There are several characters in character set:-

 

  1. Alphabets:

 

These include letters from the alphabet, both uppercase and lowercase.

 

For example, ‘A’, ‘B’, ‘C’, …, ‘Z’ and ‘a’, ‘b’, ‘c’, …, ‘z’.

 

  1. Numeric Characters:

 

These are the digits used to represent numbers. They include ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, and ‘9’.

 

  • Whitespace Characters:

 

These characters represent space, tab, newline, carriage return, and other types of spacing characters used for formatting and layout.

 

  1. Special Characters:

 

Special characters encompass a wide range of symbols, such as mathematical symbols (‘+’, ‘-‘, ‘*’, ‘/’, ‘=’, etc.), currency symbols (‘$’,’€’,’¥’, etc.), copyright symbol (‘©’), trademark symbol (‘™’), and others.

 

 

Data Types:

 

Data types are a classification of the various types of data that a variable or expression can hold or produce in a program. These types define the operations that can be performed on the data and the way it is stored in memory. Data types can be broadly categorized into primary, derived, and user-defined types.

 

  1. Primary Data Types:

 

Primary data types, also known as fundamental data types, are the basic building blocks of data manipulation. They are directly supported by the programming language. These data types represent basic data entities like integers, floating-point numbers, characters, and boolean values. Examples of primary data types in C include:

 

Integer types: int, short, long, long long, unsigned int, etc.

 

Floating-point types: float, double, long double

 

Character types: char, unsigned char, wchar_t , char16_t, char32_t

 

Boolean type: bool

 

 

  1. Derived Data Types:

 

Derived data types are formed by combining primary data types or other derived types to create complex data strucures.

 

Examples of derived data types in C include:  
Arrays: Collection of
elements of the same data type  
Pointers: Variables that
store memory addresses of other variables  
References: Aliases
to other variables or objects  
Structures: User-defined
composite data types that group related data items together  
Classes: User-

 

defined data types that encapsulate data and methods to operate on that data, forming the basis of object-oriented programming in C.

 

iii) User-defined Data Types:

 

User-defined data types are created by the programmer based on their specific requirements. They are defined using primary and derived data types. User-defined data types allow programmers to model real-world entities more effectively and encapsulate complex functionality into reusable components. They play a crucial role in making code modular, maintainable, and easier to understand. Examples of user-defined data types in C include:

 

Structures and Classes:

 

As mentioned above, structures and classes allow programmers to create custom data types with specific attributes and behaviours.

 

 

Enumerations (enums):

 

to create a new integer type with a set of named constants.

 

 

A way

 

 

 

Type-defs:

 

way to create aliases for existing data types, improving code readability and portability.

 

 

A

 

 

 

Format specifiers :

 

specifiers are primarily used with the formatted input/output operations

 

 

Format

 

 

 

Program using printf() and scanf() function

 

#include<stdio.h>

 

Void main()

 

{

 

Int emp_id;

 

Char name[20];

 

Float sal;

 

Printf(enter employee id, name and salary:);

 

Scanf(%d %s %f, &emp_id, &name, &sal);

 

Printf(\n name is %s, name);

 

Printf(\n employee id is %d, emp_id);

 

Printf(\n salary is %.2f, sal);

 

}

 

 

 

provided by the <stdio> library, such as printf() for output and scanf() for input. The format specifiers are similar to those used in C, but with a slightly different syntax due to the POP nature of C. some common format specifiers used in C with printf() and scanf():

 

%d: Used to format integers (decimal).

 

%f: Used to format floating-point numbers.

 

%c: Used to format characters.

 

%s: Used to format strings (null-terminated character arrays).

 

%p: Used to format pointers (memory addresses).

 

%X: Used to format integers in hexadecimal format.

 

%o: Used to format integers in octal format.

 

%u: Used to format unsigned integers.

 

Program for format specifier:

 

#include<stdio.h>

 

Void main()

 

{

 

Int a=456;

 

Char b=y;

 

Float c=12.458;

 

Char name[100]=Rekha:;

 

Printf(a=%d, b=%c, c=%f, a, b, c);

 

Printf(\n Name is %s, name );

 

}

 

 

 

Comments

 

A comment is a descriptive sentence written in a program. A comment are not executable statements therefore, the compilers ignores comment. The comment can be written in two ways:

 

  1. Single line comment:

 

The comment that starts with(//) double forward slash is known as single line comment.

 

  1. Double line comment/ block comment:

 

The comment which starts with/* and ends with*/ is called double comment.

 

Escape sequence:

 

Escape sequence in C language is a sequence of character that doesnt represent itself when used inside string or character. An escape sequence always begin with a backward slash (/) and is followed by one on more followed by special character. Eg of escape sequence:

 

A’ \t (horizontal tab):

 

Move the cursor to the next horizontal tab position.

 

B’ \r (carriage return):

 

Move the cursor to the beginning of the current line.

 

C’ \b (back space):

 

Move the cursor back one position on the current.

 

D’ \n (new line):

 

Move the cursor to the beginning of the next line.

 

E’ \’ (single quote):

 

Output single quote character.

 

F’ \” (double quote):

 

Output the double quote character.

 

G’ \v (Vertical tab):

 

Used for vertical tab .

 

H’ \\ (Backslash):

 

It prints \.

 

I’ \? (Question Mark):

 

It prints ?.

 

J’ \a (Alarm or Beep ):

 

Alters by generating a beep.

 

 

Input/output built in function

 

Any data or value given to program is called input and the result comes according to the input after processing is called output. C provides the following Input/output function such as:

 

  • Formatted I/O function:

 

The I/O functions that used format specifiers like %C, %d, %f are known as formatted I/O functions. Some of the formatted I/O functions are given below:

 

A’ printf():

 

It is output function that prints character, string, numeric value on the screen. Eg:

 

Printf(hello).

 

B’ scanf():

 

 

It is a input function that reads the input from keyboard.

 

scanf(%d,&a).

 

 

Eg:

 

 

 

  • Unformatted I/O function:

 

The I/O function that do not use any format specifier are known as unformatted I/O functions.

 

Some of the unformatted I/O functions are given below:

 

A’ putch():

 

It is output function that outputs a single character on the screen.

 

B’ getchar():

 

It is input function to read a character given from keyboard.

 

C’ putchar():

 

It is output function to print a character on the monitor.

 

D’ gets():

 

Input function that reads single word at a time given from keyboard.

 

E’ getch():

 

It is input function ready only one character at a time.

 

F’ puts():

 

Output function that prints a single words on monitor.

 

Program for putchar() and getchar()

 

#include<stdio.h>

 

Void main()

 

{

 

Int a;

 

Printf(enter a value:);

 

A= getchar();

 

Printf(the character you entered is:);

 

Putchar(a);

 

}

 

Program for puts() and gets()

 

#include<stdio.h>

 

Void main()

 

{

 

Char[20]

 

Printf(enter your name:);

 

Gets(name);

 

Printf(your name is:);

 

Puts(name);

 

}

 

Program for putch() and getch()

 

#include<stdio.h>

 

Void main()

 

{

 

Int a;

 

Printf(enter a value:);

 

A= getch();

 

Printf(the character you entered is:);

 

Putch(a);

 

}

 

 

 

 

 

 

Programs

 

Example 1: WAP to find the simple interest where P,T and R are input by user.

 

#include <stdio.h>

 

int main()

 

{

 

int principal, time, rate, si;

 

printf(“Enter the principal, time and rate: “);

 

scanf(“%d %d %d”, &principal, &time, &rate);

 

si = (principal * time * rate) / 100;

 

printf(“Simple interest = %d\n”, si);

 

return 0;

 

}

 

 

Example 2: WAP in C program to find the smallest number among three number.

 

#include <stdio.h>

 

int main()

 

{

 

int num1, num2, num3;

 

printf(“Enter three numbers: “);

 

scanf(“%d %d %d”, &num1, &num2, &num3);

 

int smallest = num1;

 

if (num2 < smallest)

 

{

 

smallest = num2;

 

}

 

if (num3 < smallest)

 

{

 

smallest = num3;

 

}

 

printf(“The smallest number is: %d\n”, smallest);

 

return 0;

 

}

 

Example 3: WAP in C to input time in second and convert into hour, minutes and second

 

#include <stdio.h>

 

int main() {

 

int totalSeconds, hours, minutes, seconds;

 

printf(“Enter time in seconds: “);

 

scanf(“%d”, &totalSeconds);

 

hours = totalSeconds / 3600;

 

totalSeconds %= 3600;

 

minutes = totalSeconds / 60;

 

seconds = totalSeconds % 60;

 

printf(“Converted time is: %d hours, %d minutes, and %d seconds\n”, hours, minutes, seconds);

 

return 0;

 

}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *