0% found this document useful (0 votes)
4 views23 pages

Basic of C Programming

The document provides an overview of C programming, covering key concepts such as programming languages, variable naming rules, operators, data types, control structures, functions, and structures. It details the basic structure of a C program, including sections like documentation, linking, and main functions. Additionally, it explains the differences between various operators and data types, as well as the advantages of using functions in programming.

Uploaded by

ratul.siyam1
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)
4 views23 pages

Basic of C Programming

The document provides an overview of C programming, covering key concepts such as programming languages, variable naming rules, operators, data types, control structures, functions, and structures. It details the basic structure of a C program, including sections like documentation, linking, and main functions. Additionally, it explains the differences between various operators and data types, as well as the advantages of using functions in programming.

Uploaded by

ratul.siyam1
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

Basic of C programming

Questions:
[Link] is programming Language? What is the purpose of programming Language?
A programming language is a computer language programmers use to develop software
programs, scripts, or other sets of instructions for computers to execute.
Although many languages share similarities, each has its own syntax. Once a programmer learns
the languages rules, syntax, and structure, they write the source code in a text editor or IDE.
Then, the programmer often compiles the code into machine language that can be understood
by the computer. Scripting languages, which do not require a compiler, use an interpreter to
execute the script.
It is a set of instructions written in any specific language ( C, C++, Java, Python) to perform a
specific task. A programming language is mainly used to develop desktop applications,
websites, and mobile applications.
A prominent purpose of programming languages is to provide instructions to a computer. As such,
programming languages differ from most other forms of human expression in that they require a
greater degree of precision and completeness. The purpose of programming language is to find a
sequence of instructions that will automate the performance of a task which can be as complex as an
operationg system on a computer often for solving a given problem.

[Link] down the variable naming rules.

Rules for naming variables:


Variable names in Visual C++ can range from 1 to 255 characters. To make variable names portable
to other environments stay within a 1 to 31 character range.

All variable names must begin with a letter of the alphabet or an


underscore( _ ). For beginning programmers, it may be easier to begin all variable names with a letter of
the alphabet.

After the first initial letter, variable names can also contain letters and numbers. No spaces or
special characters, however, are allowed.

Uppercase characters are distinct from lowercase characters. Using all uppercase letters is used
primarily to identify constant variables.

You cannot use a C++ keyword (reserved word) as a variable name.


C-Operation with operator and oparend
Operator in C: C language supports a rich set of built-in operators. An operator is a special
symbol that tells the compiler to perform specific mathematical or logical operations
Operand: In computer programming, an operand is a term used to describe any object that is
capable of being manipulated. For example, in "1 + 2" the "1" and "2" are the operands and the
plus symbol is the operator.
C language is rich in built-in operators and provides the following types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B % A = 0


++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then −

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not. If the values are not (A != B)
equal, then the condition becomes true. is true.

> Checks if the value of left operand is greater than the value of right (A > B)
operand. If yes, then the condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of right operand. If (A < B)
yes, then the condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand. If yes, then the condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the value of right (A <= B)
operand. If yes, then the condition becomes true. is true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then the (A && B)
condition becomes true. is false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is


the condition becomes true. true.

! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it false. B) is
true.

Misc Operators ↦ sizeof & ternary


Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.

Operator Description Example

sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.

& &a; returns the actual address of the


Returns the address of a variable.
variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value X :


Conditional Expression.
otherwise value Y
Basic Structure Of C programming
In this article, we are going to learn about the basic structure of a C program. A C program is
divided into different sections. There are six main sections to a basic c program.
The six sections are,
• Documentation
• Link
• Definition
• Global Declarations
• Main functions
• Subprograms
So now that the introduction is out of the way, let us jump to the main discussion. The whole
code follows this outline. Each code has a similar outline. Now let us learn about each of this
layer in detail.
Figure: Basic Structure Of C Program
Documentation Section
The documentation section is the part of the program where the programmer gives the details
associated with the program. He usually gives the name of the program, the details of the
author and other details like the time of coding and description. It gives anyone reading the
code the overview of the code.
Example
/**
* File Name: Helloworld.c
* Author: Manthan Naik
* date: 09/08/2019
* description: a program to display hello world
* no input needed
*/
Link Section
This part of the code is used to declare all the header files that will be used in the program. This
leads to the compiler being told to link the header files to the system libraries.
Example
1 #include<stdio.h>
Definition Section
In this section, we define different constants. The keyword define is used in this part.
1 #define PI=3.14
Global Declaration Section
This part of the code is the part where the global variables are declared. All the global variable
used are declared in this part. The user-defined functions are also declared in this part of the
code.
1 float area(float r);
2 int a=7;
Main Function Section
Every C-programs needs to have the main function. Each main function contains 2 parts. A
declaration part and an Execution part. The declaration part is the part where all the variables
are declared. The execution part begins with the curly brackets and ends with the curly close
bracket. Both the declaration and execution part are inside the curly braces.
1 int main(void)
2 {
3 int a=10;
4 printf(" %d", a);
5 return 0;
6 }
Sub Program Section
All the user-defined functions are defined in this section of the program.
1 int add(int a, int b)
2 {
3 return a+b;
4 }
Basic Data Types in C
Basic types
Here's a table containing commonly used types in C programming for quick
access.

Type Size (bytes) Format Specifier

int at least 2, usually 4 %d, %i

char 1 %c

float 4 %f

double 8 %lf

int

Integers are whole numbers that can have both zero, positive and negative
values but no decimal values. For example, 0 , -5 , 10

We can use int for declaring an integer variable.

int id;

Here, id is a variable of type integer.


You can declare multiple variables at once in C programming. For example,

int id, age;


The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states
from -2147483648 to 2147483647 .

float and double

float and double are used to hold real numbers.

float salary;
double price;

In C, floating-point numbers can also be represented in exponential. For


example,

float normalizationFactor = 22.442e2;

What's the difference between float and double ?

The size of float (single precision float data type) is 4 bytes. And the size
of double (double precision float data type) is 8 bytes.

char

Keyword char is used for declaring character type variables. For example,

char test = 'h';

The size of the character variable is 1 byte.


void

void is an incomplete type. It means "nothing" or "no type". You can think of
void as absent.
For example, if a function is not returning anything, its return type should
be void .

Note that, you cannot create variables of void type.

Difference between ++i & i++


• ++i will increment the value of i, and then return the
incremented value.
• i = 1;
• j = ++i;
• (i is 2, j is 2)
• i++ will increment the value of i, but return the original
value that i held before being incremented.
• i = 1;
• j = i++;
• (i is 2, j is 1)
Switch & If
Switch Statement in C/C++
Switch case statements are a substitute for long if statements that compare a
variable to several integral values
• The switch statement is a multiway branch statement. It provides an
easy way to dispatch execution to different parts of code based on the
value of the expression.
• Switch is a control statement that allows a value to change control of
execution.
Syntax:
switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}

If statement in C

The if statement evaluates the test expression inside the parenthesis () .

• If the test expression is evaluated to true, statements inside the body


of if are executed.
• If the test expression is evaluated to false, statements inside the body
of if are not executed.
While Loop Do-While Loop

This is entry controlled loop. It checks condition This is exit control loop. Checks condition
before entering into loop when coming out from loop

The while loop may run zero or more times Do-While may run more than one times but at
least once.

The variable of test condition must be initialized The variable for loop condition may also be
prior to entering into the loop initialized in the loop also.

while(condition){ do{
//statement //statement
} }while(condition);
Looping Statements in C execute the sequence of statements many
times until the stated condition becomes false. A loop in C consists of two parts, a
body of a loop and a control statement. The control statement is a combination of
some conditions that direct the body of the loop to execute until the specified
condition becomes false. The purpose of the C loop is to repeat the same code a
number of times.
FUNCTION IN C
A function is a group of statements that are executed whenever the function is called to perform a
specific designated task.

The most common function that we use in our day-to-day programming is the main () function. The
compiler always executes the main () function first and then any other function (if it is called from the
main method).

1. Advantages of Using a Function


▪ Use of functions enhances the readability of a program.
▪ The C compiler follows top-to-down execution, so the control flow can
be easily managed in case of functions. The control will always come back to
the main() function.
▪ It reduces the complexity of a program and gives it a modular structure.
▪ In case we need to test only a particular part of the program we will have to
run the whole program and figure out the errors which can be quite a
complex process. Another advantage here is that functions can
be individually tested which is more convenient than the above mentioned
process.
▪ A function can be used to create our own header file which can be used in
any number of programs i.e. the reusability.

2. Types of Functions
▪ Built-in Functions/library Functions
▪ User-defined Functions

2.1. Library Functions

There functions are already defined in the C compilers. They are used for String
handling, I/O operations, etc. These functions are defined in the header file. To use
these functions we need to import the specific header files.

Eg:

The library function <stdio.h> includes these common functions(there are many other
functions too):

▪ printf() shows the output in the user’s format.


▪ scanf() used to take the user’s input which can be a character, numeric
value, string,etc.
▪ getchar() takes character input from the user.
▪ gets() reads a line.

The library function <math.h> includes these common functions(there are many other
functions too):

▪ pow() finds the power of the given number.


▪ sin() finds the sine of the given number.
▪ exp() finds the exponent of the given number.
▪ cos() finds the cosine of the given number.
▪ sqrt() finds the square root of the number.
▪ log() finds the logarithmic value of the number.

Apart from <stdio.h> and <math.h> there are many other header files that contain
library functions such as <conio.h> that contains clrscr() and getch().

2.2. User-defined Functions


User-defined functions are the ones created by the user. The user can program it to
perform any desired [Link] is like customizing the functions that we need in a
program. A program can have more than one user-defined functions. All the user-
defined functions need to be called(directly or indirectly) inside the main() function in
order to be executed. User-defined functions can be added to the program in two ways.
Either through user-defined header files or by adding a function block directly to the
program. But the most important thing is to have a main() function. It makes it easier to
code and call in other functions in its body.

Any function has 4 building blocks to be declared –

▪ Function name
▪ Function Parameters
▪ Return type
▪ Statements to be executed

For more details on all the building blocks and complete information about the functions
please read the next post of User Defined Functions.

Structures in C
What is a structure?
A structure is a user defined data type in C/C++. A structure creates a data type that can be used to
group items of possibly different types into a single type.

How to create a structure?

‘struct’ keyword is used to create a structure. Following is an example.


struct address

char name[50];

char street[100];

char city[50];

char state[20];

int pin;

};

ARRAY STRUCTURE

Array refers to a collection consisting of elements of Structure refers to a collection consisting of


homogeneous data type. elements of heterogeneous data type.

Array uses subscripts or “[ ]” (square bracket) for Structure uses “.” (Dot operator) for element
element access access

Array is pointer as it points to the first element of the


collection. Structure is not a pointer

Instantiation of Array objects is not possible. Instantiation of Structure objects is possible.

Array size is fixed and is basically the number of Structure size is not fixed as each element of
elements multiplied by the size of an element. Structure can be of different type and size.

Bit filed is not possible in an Array. Bit filed is possible in an Structure.

Array declaration is done simply using [] and not any Structure declaration is done with the help of
keyword. “struct” keyword.

Arrays is a non-primitive datatype Structure is a user-defined datatype.


Structure traversal and searching is complex and
Array traversal and searching is easy and fast. slow.

struct sruct_name{ data_type1 ele1; data_type2


data_type array_name[size]; ele2; };

Array elements are stored in continuous memory Structure elements may or may not be stored in
locations. a continuous memory location.

Array elements are accessed by their index number Structure elements are accessed by their names
using subscripts. using dot operator.

Advantage of File-oriented system:


o Backup:
o Compactness:
o Data Retrieval:
o Editing:
o Remote Access:6. Sharing:

Disadvantage of File-oriented system:


o Data Redundancy:
o Data Inconsistency:
o Difficulty in Accessing Data:
o Limited Data Sharing:
o Integrity Problems:
o Atomicity Problems:
o Concurrent Access Anomalies:
o Security Problems:
Array is different from ordinary variable because Array holds multiple
values,whereas an ordinary variablehold a single [Link] is true when the elements of the array are
treated as individual entities,and when thevariables such as an [Link] is not generally right to
distinguish between a variable and an array.

For example: for(int i=0;i<=5;i++){……} In above example int i=0 is a local variable
declaration. Its scope is only limited to the for loop.
A Global Variable in the program is a variable defined outside the subroutine or
function. ... Hence, it can be accessed throughout the program by any function defined within
the program, unless it is shadowed. Example: int a =4; int b=5; public int add(){ return a+b; }
Here, 'a' and 'b' are global variables

Comparison Table Between Array and String


Parameters of
Array String
Comparison

Strings can hold items of


Data Type Arrays can hold items of any data type.
only the char data type.

Category The array is a data structure. The string is an object.

Mutability Arrays are mutable. Strings are immutable.

The length of an array is fixed, whether by the


The length of a string is not
Length programmer or the user when performing the
fixed.
operation.

Strings end with a null


End Character Usually, arrays do not end with a null character.
character.

A pointer is a variable that stores a memory address. Pointers are used to store the addresses
of other variables or memory items. Pointers are very useful for another type of parameter
passing, usually referred to as Pass By Address. Pointers are essential for dynamic memory
allocation. The Pointer in C, is a variable that stores address of another variable. A pointer can
also be used to refer to another pointer function. A pointer can be incremented/decremented,
i.e., to point to the next/ previous memory location. The purpose of pointer is to save memory
space and achieve faster execution time.

A null character is a character with all its bits set to zero. Therefore, it has a numeric value
of zero and can be used to represent the end of a string of characters, such as a word or
phrase. This helps programmers determine the length of strings.

Difference between Append and Write Mode


The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will
not happen. Append mode is used to append or add data to the existing data of file, if any.

You might also like