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.
Source Code: C Program To Delete Element of An Array at Specified Position
#include
#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.
i
pos
a[i]
a[i + 1]
a[i] = a[i + 1]
2
2
a[2] = 14
a[3] = 16
a[2] = 16
3
2
a[3] = 16
a[4] = 18
a[3] = 18
4
2
a[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.
ul
li Age: #{user.age}
li Email: #{user._id}
ul
li
a(href="/user/#{user._id}/delete") Delete
#{user.name}
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');
});
});
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');
});
});
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
#{user.name}
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
#{user.name}
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');
});
});
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');
});
});
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.
ul
each user in users
li
a(href='/user/#{user._id}') #{user.name}
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
Editing #{user.name}'s profile!
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")
Editing #{user.name}'s profile!
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
#{user.name}
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
#{user.name}
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
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'));
});
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 are one of the important components of web application. You need registration form, login form, edit form, status update form etc ..
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).
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")
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.
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
You can observe the nesting of elements and their relationship – child and parent.
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')));
var express = require('express');
var path = require('path');
var app = express(); 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 = [
"
I love Google..
",
"
Because they make awesome products",
" like my Nexus 7 Tablet",
"which is so amazing!"
].join("\n");
res.send(msg);
});
app.get('/', function(req, res){ var msg = [ "
I love Google..
", "
Because they make awesome products", " like my Nexus 7 Tablet", "which is so amazing!" ].join("\n"); res.send(msg);
});
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>
Enter your name
< !DOCTYPE html>
Enter your name
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);
});
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);
});
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!
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 ..');
};
/* * 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);
var routes = require('./routes');
app.get('/', routes.index);
This would output: Google Nexus 5 To Be Release Shortly ..
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 NPM – Node 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
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 | grep module_name
npm search followed by pipe symbol, which is followed by any module name.
For Windows users
1
npm search module_name
npm search module_name
it gives all the details of available methods, properties and their description.
Installation of Modules
init command
1
npm init
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
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
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
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
sudo npm update -g
This would solve the problem both for updating and deleting external modules.
remove/delete module command
1
npm prune
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
npm -g ls
This lists all the global modules, it’s path and file structure: as shown below: