C Program To Delete Element of An Array at Specified Position

Write a C program to delete element of an array at user specified position. Show a confirmation message before deleting the element from specified position.

Related Read:
C Program To Shift Elements of An Array by n Position

Example: Expected Input/Output

Enter 5 integer numbers
10
12
14
16
18

Enter the position of the element to be deleted
2

You want to delete element 14 at position 2?
Yes: 1, No: 0
1

Array after deleting the specified element …
10
12
16
18

Visual Representation

delete element of an array at specified position

Video Tutorial: C Program To Delete Element of An Array at Specified Position


[youtube https://www.youtube.com/watch?v=VYGGJnQ1ArE]

YouTube Link: https://www.youtube.com/watch?v=VYGGJnQ1ArE [Watch the Video In Full Screen.]

Source Code: C Program To Delete Element of An Array at Specified Position

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, pos, flag = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    do
    {
        printf("\nEnter the position of the element to be deleted\n");
        scanf("%d", &pos);

        if(pos >= N)
            printf("\nPlease enter position within the range/size of the array\n");
        else
        {
            printf("\nYou want to delete element %d at position %d?\n", a[pos], pos);
            printf("Yes: 1, No: 0\n");
            scanf("%d", &flag);
        }
    }while(flag == 0);

    for(i = pos; i < (N - 1); i++)
        a[i] = a[i + 1];

    printf("\nArray after deleting the specified element ...\n");
    for(i = 0; i < (N - 1); i++)
        printf("%d\n", a[i]);

    printf("\n");

    return 0;
}

Output 1:
Enter 5 integer numbers
1
5
9
7
3

Enter the position of the element to be deleted
4

You want to delete element 3 at position 4?
Yes: 1, No: 0
0

Enter the position of the element to be deleted
2

You want to delete element 9 at position 2?
Yes: 1, No: 0
1

Array after deleting the specified element …
1
5
7
3

Output 2:
Enter 5 integer numbers
1
2
3
4
5

Enter the position of the element to be deleted
15

Please enter position within the range/size of the array

Enter the position of the element to be deleted
0

You want to delete element 1 at position 0?
Yes: 1, No: 0
1

Array after deleting the specified element …
2
3
4
5

Logic To Delete Element of An Array at Specified Position

We ask the user to enter N integer numbers and store it inside array variable a[N]. Next we ask the index position of the element which has to be deleted from the array. Once we’ve these inputs from the user, we show a confirmation message to the user before deleting the specified element. Here user can either choose “1” to delete the element or choose “0” to re-select the element to be deleted.

If user selects “1” and chooses to delete the selected element, then we initialize i to the position of the element to be deleted. We iterate the for loop until i is less than (N – 1), and for each iteration we increment the value of i by 1.

Note: Observe the condition i < (N – 1), which is similar to writing i <= (N – 2). That is because we don’t want to swap/insert the last element of the array with some garbage value present outside the array limit/size.

Inside the for loop
Inside the ‘for loop’ we assign the element present in the next index to the current index element selected by i. i.e,. a[i] is assigned the value present at a[i + 1]. This way the value or the element present at the user selected position is lost, and the index N – 1 and N – 2 will have same elements. While displaying the array elements we leave the last index element, indicating deletion of 1 element from the array – so the array size has been obviously reduced by 1.

Note: Here array variable size isn’t reduced, but we simply do not display the last element of the array and create the illusion of reducing the size of array by 1.

Explanation With Example

If a[5] = {10, 12, 14, 16, 18};
Delete element/number at position: 2
Element at user specified position: 14

    for(i = pos; i < (N - 1); i++)
        a[i] = a[i + 1];

We initialize i to user specified position, which is present in variable pos. Iterate this for loop until i in less than (N – 1), for each iteration increment the value of i by 1.

iposa[i]a[i + 1]a[i] = a[i + 1]
22a[2] = 14a[3] = 16a[2] = 16
32a[3] = 16a[4] = 18a[3] = 18
42a[4] = 18

Now that index i is 4 and the array size is N = 5. So 4 < (5 – 1) is 4 < 4 which returns false, so the control exits the for loop. Using another “for loop” we display the array elements from index 0 to N – 2. i.e., from index i to i < (N – 1) or i <= (N – 2).

So the array elements after execution of above logic:
a[4] = {10, 12, 16, 18};

That’s how we successfully delete a element/number from user specified position 2.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Remove / Delete Data From MongoDB: Node.js

Today lets learn how to delete documents from MongoDB collection via your node.js application.

remove-delete-data-mongoDB-nodejs

In this video tutorial, I’ll show you how to make use of normal app.get to delete data and also the use of app.delete to accomplish the same.

Related Read:
Connecting To MongoDB Using Mongoose: Node.js
Save data To MongoDB: Node.js
Fetch Data From MongoDB: Node.js
Fetch Individual User Data From MongoDB: Node.js
Update / Edit Data In MongoDB: Node.js
..please go through these tutorials before proceeding further. It’ll take less than 20 min

Adding Delete link
view/show.jade

1
2
3
4
5
6
7
8
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/delete") Delete

This adds Delete link below each individual user information.

Delete Routes: remove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.get('/user/:id/delete', function(req, res){
user.remove({_id: req.params.id}, 
   function(err){
if(err) res.json(err);
else    res.redirect('/view');
});
});

Here we simply make use of app.get and the route we are defining is /user/:id/delete Once the user clicks on the delete link with the user id in it, the route gets triggered and by using remove() method upon user object, we fetch the user data with the particular id that the user passed in from the URL and delete it from our mongoDB collection.

Delete Routes: findByIdAndRemove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.get('/user/:id/delete', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, 
   function(err, docs){
if(err) res.json(err);
else    res.redirect('/view');
});
});

Here we are using findByIdAndRemove() method of mongoose module to find the requested user and delete the user document. Syntax is same as remove() method, only change is, findByIdAndRemove() method also returns result object to the callback method along with error object.

app.delete
view/show.jade

1
2
3
4
5
6
7
8
9
10
11
12
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/edit") Edit
 li
  form(action="/user/#{user._id}", method="POST")
   input(type="hidden", name="_method", value="DELETE")
   button(type="submit") Delete

Here we replace the delete link with a delete button. Here the action field value is /user/#{user._id} and the method used is POST. But we are also passing a hidden input field which overrides the method from POST to DELETE inside our node application.

Delete Routes: app.delete() and findByIdAndRemove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, 
   function(err, docs){
if(err) res.json(err);
else    res.redirect('/view');
});
});

The findByIdAndRemove() method works the same way as explained above.

Delete Routes: app.delete() and remove()
app.js

1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
 
app.delete('/user/:id', function(req, res){
user.remove({_id: req.params.id}, 
   function(err){
if(err) res.json(err);
else    res.redirect('/view');
});
});

The remove() method works the same way as explained above.

Remove / Delete Data From MongoDB: Node.js


[youtube https://www.youtube.com/watch?v=WFIuVGdmbPo]

YouTube Link: https://www.youtube.com/watch?v=WFIuVGdmbPo [Watch the Video In Full Screen.]



Full Source Code

new user registration form
public/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< !DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
 <form action="/new" method="POST">
<label for="email">Email: </label>
  <input type="email" name="email" /><br />
<label for="name">Name: </label>
  <input type="text" name="name" /><br />
<label for="age">Age: </label>
  <input type="number" name="age" /><br />
 <input type="submit"/>
</form>
</body>
</html>

Link to all registered users
view/index.jade

1
2
3
4
ul
each user in users
 li
  a(href='/user/#{user._id}') #{user.name}

Edit form
view/edit-form.jade

1
2
3
4
5
6
7
8
9
<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}")
 input(type="hidden", name="_method", value="PUT")
 p Name:
  input(type="text", name="name", value="#{user.name}")
 p Age:
  input(type="number", name="age", value="#{user.age}")
 p
  input(type="submit")

Show Individual User Information
view/show.jade

1
2
3
4
5
6
7
8
9
10
11
12
<h1>#{user.name}</h1>
ul
 li Age: #{user.age}
 li Email: #{user._id}
 
ul
 li 
  a(href="/user/#{user._id}/edit") Edit
 li
  form(action="/user/#{user._id}", method="POST")
   input(type="hidden", name="_method", value="DELETE")
   button(type="submit") Delete

Main Node.js Application File, with Create, Read, Update and Delete Routes
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
 
var app = express();
 
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
 
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
 
mongoose.connect('mongodb://localhost/Company');
 
var Schema = new mongoose.Schema({
_id    : String,
name: String,
age   : Number
});
 
var user = mongoose.model('emp', Schema);
 
app.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, 
   function(err, docs){
if(err) res.json(err);
else    res.redirect('/view');
});
});
 
app.get('/user/:id/edit', function(req, res){
res.render('edit-form', {user: req.userId});
});
 
app.put('/user/:id', function(req, res){
user.findByIdAndUpdate({_id: req.params.id},
                   {
     name: req.body.name,
  age   : req.body.age
   }, function(err, docs){
 if(err) res.json(err);
else
{ 
   console.log(docs);
   res.redirect('/user/'+req.params.id);
 }
 });
});
 
app.param('id', function(req, res, next, id){
user.findById(id, function(err, docs){
if(err) res.json(err);
else
{
req.userId = docs;
next();
}
});
});
 
 
app.get('/user/:id', function(req, res){
res.render('show', {user: req.userId});
});
 
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else    res.render('index', {users: docs})
});
});
 
app.post('/new', function(req, res){
new user({
_id    : req.body.email,
name: req.body.name,
age   : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else    res.redirect('/view');
});
});
 
 
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Routes
/ for new entries
/view for viewing all the users
/user/:id to see individual user information
/user/:id/edit to edit individual user information

With these tutorials you can start building fully functional web application. But to make it more secure, incorporate sessions, validation and error handling.

Forms Using Jade: Node.js

Forms are one of the important components of web application. You need registration form, login form, edit form, status update form etc ..

forms-in-Jade-nodejs

In this video tutorial we shall see how to write the form in Jade, and how to use Twitter Bootstrap to design the form (we just show you how to add the id or class tags and not actual bootstrap implementation – but if you need any help, you can always ask us in the comment section below).

Related Read:
Basics of Jade – Template Engine: Node.js
Loops and Conditions In Jade: Node.js
Mixins in Jade: Node.js

Route To Render Form
app.js

1
2
3
app.get('/edit', function(req, res){
 res.render('edit-form');
});

We define a route /edit and once someone visits this route, we render our edit-form.jade template file.

Form tags in Jade
edit-form.jade

1
2
3
4
5
6
7
8
9
10
form(method="POST", action="/user")
 input(type="hidden", name="_method", value="PUT")
 p Name
  input(type="text", name="name")
 p Email
  input(type="email", name="email")
 p Age
  input(type="number", name="age")
 p
  input(type="submit")

Here we indent input tags inside paragraph tags, which is a child of form. We separate form attributes using comma.

Forms Using Jade: Node.js


[youtube https://www.youtube.com/watch?v=1RC9re_llx0]

YouTube Link: https://www.youtube.com/watch?v=1RC9re_llx0 [Watch the Video In Full Screen.]



Form tags with Jade and Bootstrap
edit-form.jade

1
  input#btn(type="submit")

If you want to use bootstrap along with your jade template files, make sure to include bootstrap.min.css and bootstrap.min.js and jquery.min.js into your file, by opening layout.jade present inside your view folder. Now add the id or class names along with the html tags, this should render you bootstrap enabled functionality and styling.

Form output source code
view-source:localhost:3000/edit

1
2
3
4
5
6
7
<form method="POST" action="/user">
 <input type="hidden" name="_method" value="PUT"/>
 <p>Name<input type="text" name="name"/></p>
 <p>Email<input type="email" name="email"/></p>
 <p>Age<input type="number" name="age"/></p>
 <p><input type="submit"/></p>
</form>

You can observe the nesting of elements and their relationship – child and parent.

Basic Routing Using Express: Node.js

Today let us learn a very important lesson in any web application development i.e., setting up the routes.

basic route using Express Node.js

Express is an excellent web framework for Node.js

Basic Routing with Express
app.js

1
2
3
app.get('/', function(req, res){
    res.send("Hello World!"); 
});

This would output Hello World when users access the index or home page.

Basic Routing with Express
app.js

1
2
3
app.get('/myPhone', function(req, res){
    res.send("Sony Xperia!"); 
});

This would output Sony Xperia! when users access the /myPhone route.

Dynamic Routing with Express
app.js

1
2
3
app.get('/user/:username', function(req, res){
    res.send(" "+req.params.username+"'s profile!"); 
});

When we request information of particular user by using his username in the URL, it fetches the username using request object and displays appropriate message.
Example: If the user requests /user/Satish it’ll output Satish’s profile!

Public Folder

If we put some files inside our public directory, it would be convenient if some middlewares fetch the files directly upon user request, instead of writing routes for all those files. Connect module which is a dependency of Express web framework takes care of this.

Middleware for public folder files
app.js

1
2
3
4
5
6
var express = require('express');
var path = require('path');
 
var app = express();
 
 app.use(express.static(path.join(__dirname, 'public')));

This would set the public directory.

Middleware for public folder files
app.js

1
2
 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'public')));

If you want your custom routes to be checked before the public folder, then you could specify it using another middleware, i.e., app.router

Note that, the ordering of Middleware is significant.

Sending HTML in Routs: Express
app.js

1
2
3
4
5
6
7
8
9
10
app.get('/', function(req, res){
    var msg = [
               "<h1>I love Google..</h1>",
               "<p>Because they make awesome products",
               "<br />like my Nexus 7 Tablet",
               "which is so amazing!"
    ].join("\n");
    res.send(msg); 
});
</p>

This would out put with all HTML semantics on the browser.

Get, Post, Put, Delete Requests
Web browsers by default support only get and post requests. But we can override methods and make sure our Node.js application supports even the Put and Delete requests.

Post Request
HTML Form
index.html present in public directory

1
2
3
4
5
6
7
8
9
10
11
12
13
< !DOCTYPE html>
<html>
<head>
<title>Enter your name</title>
</head>
<body>
<form action="/user" method="POST">
<label for="name">Name: </label>
 <input type="text" name="name"/>
 <input type="submit"/>
</form>
</body>
</html>

Here we have a form with post method and also take note of action field value.

POST Route
app.js

1
2
3
4
5
app.use(express.bodyParser());
 
app.post('/user', function(req, res){
    res.send("Submitted user's name is: "+req.body.name);  
});

Inorder to parse the HTML page, you’ll need bodyParser middleware. Once you have it in place you can get form field entries and use it to insert the data into database or simply display as in our case with this example.

We could similarly write code for PUT and DELETE requests.
PUT & DELETE Routes
app.js

1
2
3
4
5
6
7
8
9
10
app.use(express.bodyParser());
app.use(express.methodOverride());
 
app.put('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});
 
app.delete('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});

By getting the unique userId of the user, you could fetch the data from database and make changes and update the information using Put request. Similarly, using the unique userId of the user, you could select and delete the information about the user!

Basic Routing Using Express: Node.js


[youtube https://www.youtube.com/watch?v=zHykHw9JlhE]

YouTube Link: https://www.youtube.com/watch?v=zHykHw9JlhE [Watch the Video In Full Screen.]



Separating Route Files
As your application grows, its hard to keep the code cleaner and maintainable, so it’s always a good idea to separate these kind of information from the main application file. So we create a file called routes and include it as a local module in our main application file.

External Route File
/routes/index.js

1
2
3
4
5
6
7
/*
 * GET home page.
 */ 
exports.index = function(req, res){
  res.send('Google Nexus 5 To Be Release Shortly ..');
};

exports is a global provided by node.js
index is a name given by us; it’s a property name and we assign a function to it.

Accessing External Route File
app.js

1
2
3
var routes = require('./routes');
 
app.get('/', routes.index);

This would output: Google Nexus 5 To Be Release Shortly ..

External Module( NPM ) Install, Update, Remove: Node.js

This video tutorial illustrates searching, installing, updating and removing the external, free modules.

External Free Node Modules are listed at npmjs.org and is managed by NPMNode Package Manager.

There are so many amazing modules already written to handle so many sophisticated functionalities, that it becomes easy to use them in our application and build a robust, scalable application quickly.

Command to look at all the external module names and their respective description

1
npm search

It gives a long list of names and descriptions.

To make is look better, you can use GREP(if you’re on Linux or Unix based System)
Search with GREP

1
npm search | grep module_name

npm search followed by pipe symbol, which is followed by any module name.

For Windows users

1
npm search module_name

it gives all the details of available methods, properties and their description.

Installation of Modules

init command

1
npm init

Once you run this command, it prompts you with some optional things, like, name of the project, version, author, licensing etc. Once you’re done with that, it creates package.json file with all the details you provided.

The ‘init’ command in NPM allows us to identify our project and list out any Node Modules it requires.

Now open that package.json file: it looks somewhat like this
package.json file

1
2
3
4
5
6
7
8
9
10
11
12
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

You need to open this package.json file using a plain text editor and add your project dependencies i.e., some of the modules you need to install for your project.

In this video tutorial we’re installing 3 external modules:
express
jade
mongoose

package.json file, after editing

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
 "dependencies": { "express": "2.5.8", "jade": "0.26.1", "mongoose": "2.6.5" },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

Now you’ve specified all the external modules your project depends on.

Now using install command, we need to install these modules.
installation command

1
npm install

Once this command is executed, it looks through the package.json file and installs all the dependency modules one by one.

External Module Install, Update, Remove via NPM: Node.js


[youtube https://www.youtube.com/watch?v=HRISSD0ic2s]

YouTube Link: https://www.youtube.com/watch?v=HRISSD0ic2s [Watch the Video In Full Screen.]



What is a module?
A module is a self-contained series of one or more javascript files represented by an object.

Update Command

1
npm update

once you run this command, package.json file is parsed and the dependency modules are checked for any updates, if any, it’ll be updated.
If any module is installed with -g (global scope), i.e., the root installation, then while updating or removing them, it may throw some errors, in such case, use sudo keyword:

Update Command

1
sudo npm update -g

This would solve the problem both for updating and deleting external modules.

remove/delete module command

1
npm prune

To remove the unused modules: open package.json file and remove the module names which you want to remove. Save the package.json file and then run above(npm prune) command. This would safely remove the modules you no more intend to use in your project.

List Global module: using command

1
npm -g ls

This lists all the global modules, it’s path and file structure: as shown below:

Example output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
C:\node\express_example>npm  -g ls
C:\Users\Satish\AppData\Roaming\npm
└─┬ [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  ├─┬ [email protected]
  │ ├── [email protected]
  │ ├─┬ [email protected]
  │ │ ├── [email protected]
  │ │ └── [email protected]
  │ ├── [email protected]
  │ ├── [email protected]
  │ └── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  └─┬ [email protected]
    └── [email protected]

Removing/Uninstalling Global modules: using command

1
npm -g rm

This removes all the global modules installed.

Clear cache

1
npm cache clear

After modifiying things from command prompt, if it’s still not working, try clearing the cache.

Note:
To install latest version of the module: you’ll need to write * (asterisk or star) in the place of version number inside package.json file.