C Programming Module 1 For BP&CO

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

Module 1: C Programming

The C Language is developed by Dennis Ritchie for creating system applications that directly interact
with the hardware devices such as drivers, kernels, etc.

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

It can be defined by the following ways:


Mother language
System programming language
Procedure-oriented programming language
Structured programming language
Mid-level programming language

C Program
File: main.c

#include <stdio.h>
int main() {
printf("Hello C Programming\n");
return 0;
}

History of C Language
Dennis Ritchie - founder of C language
History of C language is interesting to know. Here we are going to discuss a brief history of the c
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.

Features of C Language
C features
C is the widely used language. It provides many features that are given below.
 Simple
 Mid-level programming language
 structured programming language
 Rich Library
 Memory Management
 Fast Speed
 Pointers
 Recursion
 Extensible
General Overview of a Simple C Program's Structure:
The general architecture of a simple C program typically consists of several vital components. Below is
an outline of the essential elements and their purposes:

Header Files:
The #include directives at the beginning of the program are used to include header files. Header files
provide function prototypes and definitions that allow the C compiler to understand the functions
used in the program.

Main Function:
Every C program starts with the main function. It is the program's entry point, and execution starts
from here. The main function has a return type of int, indicating that it should return an integer value
to the operating system upon completion.

Variable Declarations:
Before using any variables, you should declare them with their data types. This section is typically
placed after the main function's curly opening brace.

Statements and Expressions:


This section contains the actual instructions and logic of the program. C programs are composed of
statements that perform actions and expressions that compute values.

Comments:
Comments are used to provide human-readable explanations within the code. They are not executed
and do not affect the program's functionality. In C, comments are denoted by // for single-line
comments and /* */ for multi-line comments.

Functions:
C programs can include user-defined functions and blocks of code that perform specific tasks.
Functions help modularize the code and make it more organized and manageable.

Return Statement:
Use the return statement to terminate a function and return a value to the caller function. A return
statement with a value of 0 typically indicates a successful execution in the main function, whereas a
non-zero value indicates an error or unexpected termination.

Standard Input/Output:
C has library functions for reading user input (scanf) and printing output to the console (printf). These
functions are found in C programs and are part of the standard I/O library (stdio.h header file). It is
essential to include these fundamental features correctly while writing a simple C program to ensure
optimal functionality and readability.

Additional Information:
There is some additional information about the C programs. Some additional information is as follows:

Preprocessor Directives:
C programs often include preprocessor directives that begin with a # symbol. These directives are
processed by the preprocessor before actual compilation and are used to include header files, define
macros, and perform conditional compilation.
Data Types:
C supports data types such as int, float, double, char, etc. It depends on the program's requirements,
and appropriate data types should be chosen to store and manipulate data efficiently.

Control Structures:
C provides control structures like if-else, while, for, and switch-case that allow you to make decisions
and control the flow of the program.

Error Handling:
Robust C programs should include error-handling mechanisms to handle unexpected situations
gracefully. Techniques like exception handling (using try-catch in C++) or returning error codes are
commonly employed.

Variables in C
A variable is the name of the memory location. It is used to store information. Its value can be altered
and reused several times. It is a way to represent memory location through symbols so that it can be
easily identified.

Variables are key building elements of the C programming language used to store and modify data in
computer programs. A variable is a designated memory region that stores a specified data type value.
Each variable has a unique identifier, its name, and a data type describing the type of data it may hold.

Syntax:
The syntax for defining a variable in C is as follows:

data_type variable_name;
Here,

data_type: It represents the type of data the variable can hold. Examples of data types in C include int
(integer), float (a floating-point number), char (character), double (a double-precision floating-point
number),
variable_name: It is the identifier for the variable, i.e., the name you give to the variable to access its
value later in the program. The variable name must follow specific rules, like starting with a letter or
underscore and consisting of letters, digits, and underscores.
For example, to declare the integer variable age:

int age;
It declares an integer variable named age without assigning it a specific value. Variables can also be
initialized at the time of declaration by assigning an initial value to them. For instance:

int count = 0;

Rules for defining variables


In C, Variable names must follow a few rules to be valid. The following are the rules for naming
variables in C:

Allowed Characters:
Variable names include letters ( uppercase and lowercase ), digits, and underscores. They must start
with a letter (uppercase or lowercase) or an underscore.

Case Sensitivity:
C is a case-sensitive programming language. It means that uppercase and lowercase letters are
considered distinct.

For example, myVar, MyVar, and myvar are all considered different variable names.

Keywords:
Variable names cannot be the same as C keywords (reserved words), as they have special meanings in
the language.

For example, you cannot use int, float, char, for, while, etc., as variable names.

Length Limitation:
There is no standard limit for the length of variable names in C, but it's best to keep them reasonably
short and descriptive.
Some compilers may impose a maximum length for variable names.

Spaces and Special Characters:


Variable names cannot contain spaces or special characters (such as !, @, #, $, %, ^, &, *, (, ), -, +, =, [, ],
{, }, |, \, /, <, >,., ?;, ', or ").
Underscores are the only allowed special characters in variable names.

Reserved Identifiers:
While not strictly a rule, it is advisable to avoid specific patterns or identifiers common in libraries or
standard usage.
For example, variables starting with __ (double underscores) are typically reserved for system or
compiler-specific usage.

Valid examples of variable names:

int age;
float salary;
char _status;
double average_score;
int studentCount;
Invalid examples of variable names:

int 1stNumber; // Starts with a digit


float my-salary; // Contains a hyphen (-)
char int; // Same as a C keyword
int double; // Same as a C keyword
float my$var; // Contains an unsupported special character
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

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

Keywords in C

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

C Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.

 Arithmetic Operators
 Relational Operators
 Shift Operators
 Logical Operators
 Bitwise Operators
 Ternary or Conditional Operators
 Assignment Operator

Arithmetic Operators:
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example


+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Assignment Operators:
Assignment operators are used to assign values to variables.

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison Operators:
Comparison operators are used to compare two values:

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators:
Logical operators are used to determine the logic between variables or values:

Operato Name Description Example


r
&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result !(x < 5 && x < 10)
is true

Comments in C
Comments in C language are used to provide information about lines of code. It is widely used for
documenting code. There are 2 types of comments in the C language.

 Single Line Comments


 Multi-Line Comments
 Single Line Comments

Single line comments are represented by double slash \\. Let's see an example of a single line
comment in C.

#include<stdio.h>
int main(){
//printing information
printf("Hello C");
return 0;
}
Output:

Hello C
Even you can place the comment after the statement. For example:

printf("Hello C");//printing information

Mult Line Comments


Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code, but it
can't be nested. Syntax:

/*
code
to be commented
*/
Let's see an example of a multi-Line comment in C.

#include<stdio.h>
int main(){
/*printing information
Multi-Line Comment*/
printf("Hello C");
return 0;
}
Output:

Hello C
C Format Specifier
The Format specifier is a string used in the formatted input and output functions. The format string
determines the format of the input and output. The format string always starts with a '%' character.

The commonly used format specifiers in printf() function are:

Format Description
specifier

%d or %i It is used to print the signed integer value where signed integer means that the variable can
hold both positive and negative values.

%u It is used to print the unsigned integer value where the unsigned integer means that the
variable can hold only positive value.

%o It is used to print the octal unsigned integer where octal integer value always starts with a 0
value.

%x It is used to print the hexadecimal unsigned integer where the hexadecimal integer value
always starts with a 0x value. In this, alphabetical characters are printed in small letters such
as a, b, c, etc.

%X It is used to print the hexadecimal unsigned integer, but %X prints the alphabetical
characters in uppercase such as A, B, C, etc.

%f It is used for printing the decimal floating-point values. By default, it prints the 6 values after
'.'.

%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.

%g It is used to print the decimal floating-point values, and it uses the fixed precision, i.e., the
value after the decimal in input would be exactly the same as the value in the output.

%p It is used to print the address in a hexadecimal form.

%c It is used to print the unsigned character.

%s It is used to print the strings.

%ld It is used to print the long-signed integer value.

C Control Statements
C if else Statement
The if-else statement in C is used to perform the operations based on some specific condition. The
operations specified in if block are executed if and only if the given condition is true.

There are the following variants of if statement in C language.


 If statement
 If-else statement
 If else-if ladder
 Nested if

If Statement
The if statement is used to check some given condition and perform some operations depending upon
the correctness of that condition. It is mostly used in the scenario where we need to perform the
different operations for the different conditions. The syntax of the if statement is given below.

if(expression){
//code to be executed
}

Let's see a simple example of C language if statement.

#include<stdio.h>
int main(){
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
return 0;
}
Output

Enter a number:4
4 is even number
enter a number:5

If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else statement is
an extension to the if statement using which, we can perform two different operations, i.e., one is for
the correctness of that condition, and the other is for the incorrectness of the condition. Here, we
must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always
preferable since it always invokes an otherwise case with every if condition. The syntax of the if-else
statement is given below.

if(expression){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}

Let's see the simple example to check whether a number is even or odd using if-else statement in C
language.

#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
else{
printf("%d is odd number",number);
}
return 0;
}
Output

enter a number:4
4 is even number
enter a number:5
5 is odd number

If else-if ladder Statement


The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where
there are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a
condition is true then the statements defined in the if block will be executed, otherwise if some other
condition is true then the statements defined in the else-if block will be executed, at the last if none of
the condition is true then the statements defined in the else block will be executed. There are multiple
else-if blocks possible. It is similar to the switch case statement where the default is executed instead
of else block if none of the cases is matched.

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

The example of an if-else-if statement in C language is given below.

#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number==10){
printf("number is equals to 10");
}
else if(number==50){
printf("number is equal to 50");
}
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute
multiple operations for the different possibles values of a single variable called switch variable. Here,
We can define various statements in the multiple cases for the different values of a single variable.

The syntax of switch statement in c language is given below:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

C Program:

#include <stdio.h>
int main() {
int num = 2;
switch (num) {
case 1:
printf("Value is 1\n");
break;
case 2:
printf("Value is 2\n");
break;
case 3:
printf("Value is 3\n");
break;
default:
printf("Value is not 1, 2, or 3\n");
break;
}

return 0;
}

Let's try to understand it by the examples. We are assuming that there are following variables.

int x,y,z;
char a,b;
float f;

Valid Switch Invalid Switch Valid Case Invalid Case

switch(x) switch(f) case 3; case 2.5;

switch(x>y) switch(x+2.5) case 'a'; case x;

switch(a+b-2) case 1+2; case x+2;

switch(func(x,y)) case 'x'>'y'; case 1,2,3;

You might also like