Basics of C Simplified
Basics of C Simplified
Overview
C was initially used for system development work, particularly the
programs that make-up the operating system. C was adopted as a
system development language because it produces code that runs
nearly as fast as the code written in assembly language. Some
examples of the use of C might be
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
A C program can vary from 3 lines to millions of lines and it should be
written into one or more text files with extension ".c"; for example,
hello.c. You can use "vi", "vim" or any other text editor to write your C
program into a file.
structure
Lets begin by looking at the simple structure of C
A C program basically consists of the following parts −
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Lets consider the various past of the previous slide
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 the program execution
begins.
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.
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 the main() function and returns the value 0.
Compile and Execute C Program
Let us see how to save the source code in a file, and how to compile and run it.
Following are the simple steps
• Open a text editor and add the above-mentioned code.
• Save the file as hello.c
• Open a command prompt and go to the directory where you have saved the file.
• Type gcc hello.c and press enter to compile your code.
• If there are no errors in your code, the command prompt will take you to the next line and
would generate a.out executable file.
• Now, type a.out to execute your program.
• You will see the output "Hello World" printed on the screen.
Basic syntax
Since you have seen the basic structure of a C program, so it will be easy to
understand other basic building blocks of the C programming language.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an
identifier, a constant, a string literal, or a symbol. For example, the following
C statement consists of five tokens
printf
(
"Hello, World! \n"
)
;
Semicolons
In a C program, the semicolon is a statement terminator. That is, each
individual statement must be ended with a semicolon. It indicates the
end of one logical entity.
Comments
Comments are like helping text in your C program and they are ignored
by the compiler. They start with /* and terminate with the characters
*/ as shown below −
/* my first program in C */
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, 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. Thus,
Manpower and manpower are two different identifiers in C.
keywords
auto else long switch
double
Variables
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
String constants
String constants are the constants which are enclosed in a pair of
double-quote marks. For example:
"good" //string constant
"" //null string constant
" " //string constant of six white space
"x" //string constant having single character.
"Earth is round\n" //prints string with newline
Enumeration constants
Keyword enum is used to define enumeration types
enum color {yellow, green, black, white};
Here, color is a variable and yellow, green, black and white are the
enumeration constants having value 0, 1, 2 and 3 respectively.
Data types
Data types simply refers to the type and size of data associated with
variables and functions.
Data types in C
• Fundamental Data Types
• Integer types
• Floating type
• Character type
• Derived Data Types
• Arrays
• Pointers
• Structures
• Enumeration
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. Floating point
variables has a precision of 6 digits whereas the precision of double is
14 digits.
Character types
Keyword char is used for declaring character type variables. For
example: char test = 'h';
Sign qualifiers
Integers and floating point variables can hold both negative and
positive values. However, if a variable needs to hold positive value only,
unsigned data types are used.
// unsigned variables cannot hold negative value
unsigned int positiveInteger;
Signed variables hold both positive and negative. However it is not
necessary to declare a variable signed since its by default.
Constant qualifiers
An identifier can be declared as a constant. To do so const keyword is
used. Example const int cost = 20;
The value of cost cannot be changed in the program.
Operators
An operator is a symbol which operates on a value or a variable.
C programming has wide range of operators to perform various
operations. For better understanding of operators, these operators can
be classified as:
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators
An arithmetic operator performs mathematical operations such as
addition, subtraction and multiplication on numerical values (constants
and variables).
Operator Meaning of Operator
* multiplication
/ division
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
example
// C Program to demonstrate the working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a;
printf("c = %d \n", c);
c += a; // c = c+a
printf("c = %d \n", c);
c -= a; // c = c-a
printf("c = %d \n", c);
c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
Relational Operators
A relational operator checks the relationship between two operands. If
the relation is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
== Equal to 5 == 3 returns 0
Logial AND. True only if all operands If c = 5 and d = 2 then, expression ((c
&&
are true == 5) && (d > 5)) equals to 0.
Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c
||
operand is true == 5) || (d > 5)) equals to 1.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Nested If…Else
The if...else statement executes two different codes depending upon
whether the test expression is true or false. Sometimes, a choice has to
be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test
expressions and execute different codes for more than two conditions.
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
example
// Program to relate two integers using =, > or <
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Looping construct
Loops are used in programming to repeat a specific block until some
end condition is met. There are three loops in C programming:
• for loop
• while loop
• do...while loop
for Loop
The syntax of for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// codes
}
How for loop works
The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is false (0), for
loop is terminated. But if the test expression is true (nonzero), codes inside
the body of for loop is executed and the update expression is updated.
The for loop is commonly used when the number of iterations is known.
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
while loop
The syntax of a while loop is:
while (testExpression)
{
//codes
}
where, testExpression checks the condition is true or false before each
loop.
How while loop works
The while loop evaluates the test expression.
If the test expression is true (nonzero), codes inside the body of while
loop are executed. The test expression is evaluated again. The process
goes on until the test expression is false.
When the test expression is false, the while loop is terminated.
example
// Program to find factorial of a number
// For a positive integer n, factorial = 1*2*3...n
#include <stdio.h>
int main()
{
int number;
long long factorial;
printf("Enter an integer: ");
scanf("%d",&number);
factorial = 1;
// loop terminates when number is less than or equal to 0
while (number > 0)
{
factorial *= number; // factorial = factorial*number;
--number;
}
printf("Factorial= %lld", factorial);
return 0;
}
do...while loop
The do..while loop is similar to the while loop with one important
difference. The body of do...while loop is executed once, before
checking the test expression. Hence, the do...while loop is executed at
least once.
do
{
// codes
}
while (testExpression);
How do...while loop works
The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the
loop body is executed again. This process goes on until the test
expression is evaluated to 0 (false).
#include <stdio.h>
int main()
{
double number, sum = 0;
// loop body is executed at least once
do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
Break and continue
It is sometimes desirable to skip some statements inside the loop or
terminate the loop immediately without checking the test expression.
In such cases, break and continue statements are used.
break Statement
The break statement terminates the loop (for, while and do...while
loop) immediately when it is encountered. The break statement is used
with decision making statement such as if...else.
Syntax is: break;
How the break works
How break statement works?
example
// Program to calculate the sum of maximum of 10 numbers
// Calculates sum until user enters positive number
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If user enters negative number, loop is terminated
if(number < 0.0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
continue Statement
The continue statement skips some statements inside the loop. The
continue statement is used with decision making statement such as
if...else.
How the continue works
// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from calculation
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If user enters negative number, loop is terminated
if(number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
Switch case
The if..else..if ladder allows you to execute a block code among many
alternatives. If you are checking on the value of a single variable in
if...else...if, it is better to use switch statement.
The switch statement is often faster than nested if...else (not always).
Also, the syntax of switch statement is cleaner and easy to understand.
syntax
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
When a case constant is found that matches the switch expression,
control of the program passes to the block of code associated with that
case.
In the above pseudocode, suppose the value of n is equal to constant2.
The compiler will execute the block of code associate with the case
statement until the end of switch block, or until the break statement is
encountered.
The break statement is used to prevent the code running into the next
case.
example
// Program to create a simple calculator
// Performs addition, subtraction, multiplication or division depending the input from user
# include <stdio.h>
int main() {
char operator;
double firstNumber,secondNumber;
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber+secondNumber);
break;
Cont…….
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);
break;
# include <stdio.h>
int main()
{
jump:
average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
Functions
A function is a block of code that performs a specific task. Every C program has at
least one function, which is main(), and all the most trivial programs can define
additional functions.
return_type function_name( parameter list ) {
//body of the function
}
• Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
• Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
• Function Body − The function body contains a collection of statements that
define what the function does.
Types of functions
There are two types of functions in C programming:
• Standard library functions
• User defined functions
The standard library functions are built-in functions in C programming
to handle tasks such as mathematical computations, I/O processing,
string handling etc.
These functions are defined in the header file. When you include the
header file, these functions are available for use. Example
The printf() is a standard library function to send formatted output to
the screen (display output on the screen). This function is defined in
"stdio.h" header file.
There are other numerous library functions defined under "stdio.h",
such as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in
your program, all these functions are available for use.
User-defined functions
As mentioned earlier, C allow programmers to define functions. Such
functions created by the user are called user-defined functions.
Depending upon the complexity and requirement of the program, you
can create as many user-defined functions as you want.
How user define function works
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
Example
/* function returning the max between two numbers */
int max(int num1, int num2) {
return result;
}
Calling a Function
While creating a C function, you give a definition of what the function
has to do. To use a function, you will have to call that function to
perform the defined task.
When a program calls a function, the program control is transferred to
the called function. A called function performs a defined task and when
its return statement is executed or when its function-ending closing
brace is reached, it returns the program control back to the main
program.
To call a function, you simply need to pass the required parameters
along with the function name, and if the function returns a value, then
you can store the returned value
example
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2) {
return result;
}
Function Arguments
If a function is to use arguments, it must declare variables that accept
the values of the arguments. These variables are called the formal
parameters of the function.
Formal parameters behave like other local variables inside the function
and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be
passed to a function
Sr.No. Call Type & Description
Call by value: This method copies the actual value of an argument into the formal
1 parameter of the function. In this case, changes made to the parameter inside the
function have no effect on the argument.
Call by reference: This method copies the address of an argument into the formal
2 parameter. Inside the function, the address is used to access the actual argument used
in the call. This means that changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means
the code within a function cannot alter the arguments used to call the
function
A to programs to check whether an integer entered by the user is a prime number or
not.
#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// integer is returned from the function
int checkPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */
int i;
return 0;
}
Arrays
An array is a collection of data that holds fixed number of values of
same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same
type. The size and type of arrays cannot be changed after its
declaration.
Arrays are of two types:
• One-dimensional arrays
• Multidimensional arrays
Declaring and initializing an Array
To declare an array in C, a programmer specifies the type of the
elements and the number of elements required by an array
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an
integer constant greater than zero and type can be any valid C data
type.
You can initialize an array in C either one by one or using a single
statement. Example
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
example
// Program to find the average of n (n < 10) numbers using arrays
#include <stdio.h>
int main(){
return 0;
}
Two-dimensional Arrays
type name[size1][size2]...[sizeN];
The simplest form of multidimensional array is the two-dimensional
array. A two-dimensional array is, in essence, a list of one-dimensional
arrays. To declare a two-dimensional integer array of size [x][y], you
would write something as follows −
type arrayName [ x ][ y ];
example
#include <stdio.h>
int main () {
if(j==1)
printf("\n");
}
return 0;
}
Three dimensional array
#include <stdio.h>
int main()
{
// this array can store 12 elements
int i, j, k, test[2][3][2];
printf("Enter 12 values: \n");
return 0;
}
Passing arrays to a functions
C program to pass a single element of an array to function
#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main(){
int ageArray[] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element ageArray[2] only.
return 0;
}
Passing an entire one-dimensional array to a
function
While passing arrays as arguments to the function, only the name of
the array is passed (,i.e, starting address of memory area is passed as
argument).
Example:
A program to pass an array containing age of person to a function. This
function should find average age and display the average age in main
function.
#include <stdio.h>
float average(float age[]);
int main(){
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age); /* Only name of array is passed as argument. */
printf("Average age=%.2f", avg);
return 0;
}
float average(float age[])
{
int i; float avg, sum = 0.0;
for (i = 0; i < 6; ++i)
{
sum += age[i];
}
avg = (sum / 6);
return avg;
}
Pointers
A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location.
Arrays are closely related to pointers in C programming but the
important difference between them is that, a pointer variable takes
different addresses as value whereas, in case of array it is fixed.
Like any variable or constant, you must declare a pointer before using it
to store any variable address.
type *var-name;
return 0;
}
Pointers and Arrays
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
int main()
{
int num1 = 5, num2 = 10;
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
return 0;
}
Structures to Pointers
Structures can be created and accessed using pointers
struct name {
member1;
member2;
.
.
};
int main()
{
struct name *ptr;
}
Accessing structure's member through pointer
printf("Displaying: ");
printf("%d%f",(*personPtr).age,(*personPtr).weight);
return 0;
}