Quantcast
Viewing all 761 articles
Browse latest View live

Bresenham’s Midpoint Circle Algorithm in C and C++

Here you will get program for bresenham’s midpoint circle algorithm in C and C++. It is an algorithm used in computer graphics for drawing circle.

This program will work in Turbo C or Turbo C++ compiler as it uses graphics.h header file.

Change the path of BGI file inside initgraph() function according to your system to make this program run.

Program for Bresenham’s Midpoint Circle Algorithm in C

#include<stdio.h>
#include<graphics.h>

void drawcircle(int x0, int y0, int radius)
{
    int x = radius;
    int y = 0;
    int err = 0;

    while (x >= y)
    {
	putpixel(x0 + x, y0 + y, 7);
	putpixel(x0 + y, y0 + x, 7);
	putpixel(x0 - y, y0 + x, 7);
	putpixel(x0 - x, y0 + y, 7);
	putpixel(x0 - x, y0 - y, 7);
	putpixel(x0 - y, y0 - x, 7);
	putpixel(x0 + y, y0 - x, 7);
	putpixel(x0 + x, y0 - y, 7);

	if (err <= 0)
	{
	    y += 1;
	    err += 2*y + 1;
	}

	if (err > 0)
	{
	    x -= 1;
	    err -= 2*x + 1;
	}
    }
}

int main()
{
	int gdriver=DETECT, gmode, error, x, y, r;
	initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");

	printf("Enter radius of circle: ");
	scanf("%d", &r);

	printf("Enter co-ordinates of center(x and y): ");
	scanf("%d%d", &x, &y);
	drawcircle(x, y, r);

	return 0;
}

Program for Bresenham’s Midpoint Circle Algorithm in C++

#include<iostream.h>
#include<graphics.h>

void drawcircle(int x0, int y0, int radius)
{
    int x = radius;
    int y = 0;
    int err = 0;

    while (x >= y)
    {
	putpixel(x0 + x, y0 + y, 7);
	putpixel(x0 + y, y0 + x, 7);
	putpixel(x0 - y, y0 + x, 7);
	putpixel(x0 - x, y0 + y, 7);
	putpixel(x0 - x, y0 - y, 7);
	putpixel(x0 - y, y0 - x, 7);
	putpixel(x0 + y, y0 - x, 7);
	putpixel(x0 + x, y0 - y, 7);

	if (err <= 0)
	{
	    y += 1;
	    err += 2*y + 1;
	}

	if (err > 0)
	{
	    x -= 1;
	    err -= 2*x + 1;
	}
    }
}

int main()
{
	int gdriver=DETECT, gmode, error, x, y, r;
	initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");

	cout<<"Enter radius of circle: ";
	cin>>r;

	cout<<"Enter co-ordinates of center(x and y): ";
	cin>>x>>y;
	drawcircle(x, y, r);

	return 0;
}

Output

Image may be NSFW.
Clik here to view.
Bresenham's Midpoint Circle Algorithm in C and C++

The post Bresenham’s Midpoint Circle Algorithm in C and C++ appeared first on The Crazy Programmer.


Bresenham’s Line Drawing Algorithm in C and C++

Here you will get program for bresenham’s line drawing algorithm in C and C++.

This algorithm is used in computer graphics for drawing line.

The program will work in Turbo C or Turbo C++ compiler as it uses graphics.h header file.

Make sure to change the path of BGI folder inside initgraph() function according to your system. Otherwise the program will not work.

Also Read: Bresenham’s Midpoint Circle Algorithm in C and C++

Program for Bresenham’s Line Drawing Algorithm in C

#include<stdio.h>
#include<graphics.h>

void drawline(int x0, int y0, int x1, int y1)
{
    int dx, dy, p, x, y;

	dx=x1-x0;
	dy=y1-y0;

	x=x0;
	y=y0;

	p=2*dy-dx;

	while(x<x1)
	{
		if(p>=0)
		{
			putpixel(x,y,7);
			y=y+1;
			p=p+2*dy-2*dx;
		}
		else
		{
			putpixel(x,y,7);
			p=p+2*dy;
		}
		x=x+1;
	}
}

int main()
{
	int gdriver=DETECT, gmode, error, x0, y0, x1, y1;
	initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");

	printf("Enter co-ordinates of first point: ");
	scanf("%d%d", &x0, &y0);

	printf("Enter co-ordinates of second point: ");
	scanf("%d%d", &x1, &y1);
	drawline(x0, y0, x1, y1);

	return 0;
}

Program for Bresenham’s Line Drawing Algorithm in C++

#include<iostream.h>
#include<graphics.h>

void drawline(int x0, int y0, int x1, int y1)
{
    int dx, dy, p, x, y;

	dx=x1-x0;
	dy=y1-y0;

	x=x0;
	y=y0;

	p=2*dy-dx;

	while(x<x1)
	{
		if(p>=0)
		{
			putpixel(x,y,7);
			y=y+1;
			p=p+2*dy-2*dx;
		}
		else
		{
			putpixel(x,y,7);
			p=p+2*dy;
		}
		x=x+1;
	}
}

int main()
{
	int gdriver=DETECT, gmode, error, x0, y0, x1, y1;
	initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");

	cout<<"Enter co-ordinates of first point: ";
	cin>>x0>>y0;

	cout<<"Enter co-ordinates of second point: ";
	cin>>x1>>y1;
	drawline(x0, y0, x1, y1);

	return 0;
}

Output

Image may be NSFW.
Clik here to view.
Bresenham's Line Drawing Algorithm in C and C++

The post Bresenham’s Line Drawing Algorithm in C and C++ appeared first on The Crazy Programmer.

Android XML Parsing Using XMLPullParser

In this tutorial you will learn about android xml parsing using XMLPullParser.

XML is a popular and very commonly used format for sharing data on internet. In android there are several ways to parse xml data like DOM, SAX and XMLPullParser. But in this article I will teach you how to parse xml using XMLPullParser.

Android XML Parsing Using XMLPullParser

Steps for XML Parsing

XML parsing includes following steps.

1. First we have to read the xml file or data inside InputStream.

InputStream stream = this.getResources().openRawResource(R.raw.student);

Here I have assumed that student.xml file is present in res/raw folder of project. You can also fetch the xml data from internet using url. The xml file contains data of students as shown below.

<?xml version="1.0"?>
<class>
	<student>
		<name>Neeraj Mishra</name>
		<rollno>10</rollno>
		<age>22</age>
	</student>
	
	<student>
		<name>Mayank Khandiwal</name>
		<rollno>11</rollno>
		<age>22</age>
	</student>
	
	<student>
		<name>Sumit Gendar</name>
		<rollno>12</rollno>
		<age>22</age>
	</student>
	
	<student>
		<name>Vivek Pathak</name>
		<rollno>13</rollno>
		<age>22</age>
	</student>
</class>

2. Create an instance of XMLPullParserFactory and using it call newPullParser() method to get instance of XMLPullParser.

XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = xmlPullParserFactory.newPullParser();

3. Now provide InputStream object to XMLPullParser as an input using setInput() method.

parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(stream, null);

4. Finally the data is read form XMLPullParser in following way.

String tag_name = "", text = "";
int event = parser.getEventType();

while (event != XmlPullParser.END_DOCUMENT) {
	tag_name = parser.getName();

	switch (event) {
		case XmlPullParser.START_TAG:
                        break;

		case XmlPullParser.TEXT:
                        text = parser.getText();
                        break;
						
		case XmlPullParser.END_TAG:
						switch(tag_name) {
                            case "name": textView.append("Name: " + text + "\n");
                                        break;
                            case "rollno": textView.append("Roll No: " + text + "\n");
                                        break;
                            case "age": textView.append("Age: " + text + "\n\n");
                                        break;
                        }
                        break;
	}
	
	event = parser.next();
}

The above code should be placed inside try-catch block.

The getEventType() method gives the type of event. It can be END_DOCUMENT, START_TAG, END_TAG, etc. On the basis of these events we filter and read the xml data.

The getName() method gives tag name while getText() method gives text information present inside that tag.

Android XMLPullParser Example

Below is a simple example that parses student data present in xml format using XMLPullParser.

1. Create a new android project with package name com.androidxmlparser.

2. Create a folder raw under res. Add a file student.xml inside res/raw with following xml data.

student.xml

<?xml version="1.0"?>
<class>
	<student>
		<name>Neeraj Mishra</name>
		<rollno>10</rollno>
		<age>22</age>
	</student>
	
	<student>
		<name>Mayank Khandiwal</name>
		<rollno>11</rollno>
		<age>22</age>
	</student>
	
	<student>
		<name>Sumit Gendar</name>
		<rollno>12</rollno>
		<age>22</age>
	</student>
	
	<student>
		<name>Vivek Pathak</name>
		<rollno>13</rollno>
		<age>22</age>
	</student>
</class>

3. By default you would get an activity MainActivity when you have created the project. This activity is used to display the parsed xml data. Just add following code inside its xml layout and java source file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.androidxmlparser.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:text=""/>
</RelativeLayout>

MainActivity.java

package com.androidxmlparser;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.textView);

        InputStream stream = this.getResources().openRawResource(R.raw.student);

        try {
            XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = xmlPullParserFactory.newPullParser();

            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(stream, null);

            String tag_name = "", text = "";
            int event = parser.getEventType();

            while (event != XmlPullParser.END_DOCUMENT) {
                tag_name = parser.getName();

                switch (event) {
                    case XmlPullParser.START_TAG:
                        break;

                    case XmlPullParser.TEXT:
                        text = parser.getText();
                        break;

                    case XmlPullParser.END_TAG:
                        switch(tag_name) {
                            case "name": textView.append("Name: " + text + "\n");
                                        break;
                            case "rollno": textView.append("Roll No: " + text + "\n");
                                        break;
                            case "age": textView.append("Age: " + text + "\n\n");
                                        break;
                        }
                        break;
                }

                event = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4. Now save and run the project. If everything was done correctly then you will see an output as shown in below image.

Screenshot

Image may be NSFW.
Clik here to view.
Android XML Parsing Using XMLPullParser

Comment below if you have doubts or found anything incorrect in above android xml parsing tutorial.

The post Android XML Parsing Using XMLPullParser appeared first on The Crazy Programmer.

How to Get Current Location in Android Using Location Manager

In this GPS tutorial you will learn how to get current location in android.

LocationManager class provides the facility to get latitude and longitude coordinates of current location. The class in which you want to get location should implement LocationListener and override all its abstract methods.

How to Get Current Location in Android Using Location Manager

Add following permissions to AndroidManifest.xml file.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Following lines of code helps in getting current location.

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);

In requestLocationUpdates() method the 2nd argument is time in milliseconds and 3rd argument is distance in meters. Here I have used 5000 and 5 that means after every 5 seconds and 5 meter the current location is fetched.

To get coordinates use getLatitude() and getLongitude() method on variable of Location class.

Whenever location is changed it can be fetched inside onLocationChanged() method.

Below is simple application that fetches current location on button click and displays it in textview.

Full Source Code

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.currentlocation.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Current Location"
        android:id="@+id/getLocationBtn"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/locationText"
        android:layout_below="@id/getLocationBtn"/>
</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.currentlocation">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.currentlocation;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LocationListener {
    Button getLocationBtn;
    TextView locationText;

    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getLocationBtn = (Button)findViewById(R.id.getLocationBtn);
        locationText = (TextView)findViewById(R.id.locationText);

        getLocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocation();
            }
        });
    }

    void getLocation() {
        try {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
        }
        catch(SecurityException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        locationText.setText("Current Location: " + location.getLatitude() + ", " + location.getLongitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(MainActivity.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }
}

Screenshot

Image may be NSFW.
Clik here to view.
How to Get Current Location in Android Using Location Manager

Comment below if found anything incorrect or have doubts related to above android gps tutorial to get current location.

 

The post How to Get Current Location in Android Using Location Manager appeared first on The Crazy Programmer.

Android Google Maps API Tutorial – Getting Started

This is android google maps api tutorial.

In this tutorial I will teach you to integrate google maps in your android app using google maps api v2.

This API provides us various functionality like showing locations in map, showing routes, add marker, etc.

Android Google Maps API Tutorial

Android Project

1. Open Android Studio and go to New Project option. Now give a name to your project and press Next.

Image may be NSFW.
Clik here to view.
Android Google Maps API Tutorial

2. Choose Google Maps Activity, choosing this activity makes easier to integrate google maps.

Image may be NSFW.
Clik here to view.
Android Google Maps API Tutorial

3. Click Next and finally click on Finish to create the project.

Getting API Key

For using google maps in our project we need API key. It can be obtained in following way.

1. After creating the project you will see a file google_maps_api.xml as shown in below image. Copy the URL given in it and open it in browser.

Image may be NSFW.
Clik here to view.
Android Google Maps API Tutorial

2. You will see a page as shown below. There agree with the terms and click Agree and continue. Make sure you are logged in to google account.

Image may be NSFW.
Clik here to view.
Android Google Maps API Tutorial

3. Then click Create API key button.

Image may be NSFW.
Clik here to view.
Android Google Maps API Tutorial

4. On the next page you will get API key, just copy it.

Image may be NSFW.
Clik here to view.
Android Google Maps API Tutorial

5. Finally paste the API key in google_maps_api.xml file under string tag.

Image may be NSFW.
Clik here to view.
Android Google Maps API Tutorial

6. Save and run the project.

When we created the project by default we got the code to display a simple google map with a marker at some location. Make sure google play services is installed and internet is enabled in the device on which you are running this app.

Image may be NSFW.
Clik here to view.
Android Google Maps API Tutorial

Comment below if you have any doubts related to above tutorial.

The post Android Google Maps API Tutorial – Getting Started appeared first on The Crazy Programmer.

Android JSON Parsing From URL Example

Here you will get android json parsing from url example.

What I will do here?

  • First fetch json string from url.
  • Parse the json data and display in listview.

The data contains a json array with some fruits name as shown below.

{
"fruits":[
	"Apple",
	"Apricot",
	"Avocado",
	"Banana",
	"Bilberry",
	"Blackberry",
	"Blackcurrant",
	"Blueberry",
	"Boysenberry",
	"Currant",
	"Cherry",
	"Cherimoya",
	"Cloudberry",
	"Coconut",
	"Cranberry",
	"Custard apple",
	"Damson",
	"Date",
	"Dragonfruit",
	"Durian",
	"Elderberry",
	"Feijoa",
	"Fig",
	"Goji berry",
	"Gooseberry",
	"Grape",
	"Raisin",
	"Grapefruit",
	"Guava"
	]
}

Also Read: Picasso Android Tutorial – Load Image from URL

Android JSON Parsing From URL Example

Create a new android studio project with package name com.jsonparsing.

As we are fetching data from internet so we have to add internet access permission. Add following line of code in AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />

I am using volley library in this example. It is a network library that is used to fetch data from server or internet. So add it to your project by adding following line of code in app level build.gradle file under dependencies section. After that sync the project.

compile 'com.android.volley:volley:1.0.0'

The following code is responsible for fetching json data from url in the form of json string using volley library.

StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String string) {
                parseJsonData(string);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });

  • When data is fetched successfully then onResponse() method is called.
  • If there is any error while fetching data then onErrorResponse() is called and an error message is displayed in toast.

After creating the volley request we have to add it to request queue.

RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);

Now comes the parsing part. The parseJsonData() method contains the code to parse the json string.

void parseJsonData(String jsonString) {
        try {
            JSONObject object = new JSONObject(jsonString);
            JSONArray fruitsArray = object.getJSONArray("fruits");
            ArrayList al = new ArrayList();

            for(int i = 0; i < fruitsArray.length(); ++i) {
                al.add(fruitsArray.getString(i));
            }

            ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, al);
            fruitsList.setAdapter(adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        dialog.dismiss();
    }

  • First json string is parsed to json object. From this object a json array with name fruits is fetched.
  • Now each fruit is fetched from json array one by one inside loop and added to an arraylist.
  • Finally this list of fruits is assigned to listview using an adapter.

Below I have shared the full source code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.jsonparsing.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/fruitsList"/>
</RelativeLayout>

MainActivity.java

package com.jsonparsing;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ListView fruitsList;
    String url = "http://www.thecrazyprogrammer.com/example_data/fruits_array.json";
    ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fruitsList = (ListView)findViewById(R.id.fruitsList);

        dialog = new ProgressDialog(this);
        dialog.setMessage("Loading....");
        dialog.show();

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String string) {
                parseJsonData(string);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });

        RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
        rQueue.add(request);
    }

    void parseJsonData(String jsonString) {
        try {
            JSONObject object = new JSONObject(jsonString);
            JSONArray fruitsArray = object.getJSONArray("fruits");
            ArrayList al = new ArrayList();

            for(int i = 0; i < fruitsArray.length(); ++i) {
                al.add(fruitsArray.getString(i));
            }

            ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, al);
            fruitsList.setAdapter(adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        dialog.dismiss();
    }
}

Screenshots

Image may be NSFW.
Clik here to view.
Android JSON Parsing From URL Example

Image may be NSFW.
Clik here to view.
Android JSON Parsing From URL Example

You can ask your queries related to above android json paring from url example.

The post Android JSON Parsing From URL Example appeared first on The Crazy Programmer.

DDA Line Drawing Algorithm in C and C++

Here you will learn about dda line drawing algorithm in C and C++.

In Computer Graphics the first basic line drawing algorithm is Digital Differential Analyzer (DDA) Algorithm.

A line connects two points. It is a basic element in graphics. To draw a line, you need two points between which you can draw a line.

Also Read: Bresenham’s Line Drawing Algorithm in C and C++

Digital Differential Analyzer (DDA) Algorithm

Step 1: Read the input of the 2 end points of the line as (x1, y1) & (x2, y2) such that x1 != x2 and y1 != y2

Step 2: Calculate dx = x2 – x1 and dy = y2 – y1

Step 3:

if(dx>=dy)

step=dx

else

step=dy

Step 4: xin = dx / step & yin = dy / step

Step 5: x = x1 + 0.5 & y = y1 + 0.5

Step 6: 

for(k = 0; k < step; k++)

{

x = x + xin

y = y + yin

putpixel(x, y)

}

Program for DDA Line Drawing Algorithm in C

#include <graphics.h>
#include <stdio.h>
#include <math.h>
#include <dos.h>

void main( )
{
	float x,y,x1,y1,x2,y2,dx,dy,step;
	int i,gd=DETECT,gm;

	initgraph(&gd,&gm,"c:\\turboc3\\bgi");

	printf("Enter the value of x1 and y1 : ");
	scanf("%f%f",&x1,&y1);
	printf("Enter the value of x2 and y2: ");
	scanf("%f%f",&x2,&y2);

	dx=abs(x2-x1);
	dy=abs(y2-y1);

	if(dx>=dy)
		step=dx;
	else
		step=dy;

	dx=dx/step;
	dy=dy/step;

	x=x1;
	y=y1;

	i=1;
	while(i<=step)
	{
		putpixel(x,y,5);
		x=x+dx;
		y=y+dy;
		i=i+1;
		delay(100);
	}

	closegraph();
}

Outptut

Image may be NSFW.
Clik here to view.
DDA Line Drawing Algorithm in C and C++

Program for DDA Line Drawing Algorithm in C++

#include <graphics.h>
#include <iostream.h>
#include <math.h>
#include <dos.h>

void main( )
{
	float x,y,x1,y1,x2,y2,dx,dy,step;
	int i,gd=DETECT,gm;

	initgraph(&gd,&gm,"c:\\turboc3\\bgi");

	cout<<"Enter the value of x1 and y1 : ";
	cin>>x1>>y1;
	cout<<"Enter the value of x2 and y2: ";
	cin>>x2>>y2;

	dx=abs(x2-x1);
	dy=abs(y2-y1);

	if(dx>=dy)
		step=dx;
	else
		step=dy;

	dx=dx/step;
	dy=dy/step;

	x=x1;
	y=y1;

	i=1;
	while(i<=step)
	{
		putpixel(x,y,5);
		x=x+dx;
		y=y+dy;
		i=i+1;
		delay(100);
	}

	closegraph();
}

Comment below if you have any doubts related above algorithm.

The post DDA Line Drawing Algorithm in C and C++ appeared first on The Crazy Programmer.

Best Fit Algorithm in C and C++

Here you will learn about best fit algorithm in C and C++ with program example.

Memory Management is one of the services provided by OS which is needed for Optimized memory usage of the available memory in a Computer System.

For this purpose OS uses 3 methods:-

  1. First Fit
  2. Best Fit
  3. Worst Fit

In this section we will talk about Best Fit Memory Management Scheme.

What is Best Fit Memory Management Scheme?

Best fit uses the best memory block based on the Process memory request. In best fit implementation the algorithm first selects the smallest block which can adequately fulfill the memory request by the respective process.
Because of this memory is utilized optimally but as it compares the blocks with the requested memory size it increases the time requirement and hence slower than other methods. It suffers from Internal Fragmentation which simply means that the memory block size is greater than the memory requested by the process, then the free space gets wasted.

Once we encounter a process that requests a memory which is higher than block size we stop the algorithm.

Best Fit Algorithm

  1. Get no. of Processes and no. of blocks.
  2. After that get the size of each block and process requests.
  3. Then select the best memory block that can be allocated using the above definition.
  4. Display the processes with the blocks that are allocated to a respective process.
  5. Value of Fragmentation is optional to display to keep track of wasted memory.
  6. Stop.

Program for Best Fit Algorithm in C

#include<stdio.h>

void main()
{
	int fragment[20],b[20],p[20],i,j,nb,np,temp,lowest=9999;
	static int barray[20],parray[20];
	
	printf("\n\t\t\tMemory Management Scheme - Best Fit");
	printf("\nEnter the number of blocks:");
	scanf("%d",&nb);
	printf("Enter the number of processes:");
	scanf("%d",&np);
	
	printf("\nEnter the size of the blocks:-\n");
	for(i=1;i<=nb;i++)
    {
		printf("Block no.%d:",i);
        scanf("%d",&b[i]);
    }
	
	printf("\nEnter the size of the processes :-\n");
	for(i=1;i<=np;i++)
    {
        printf("Process no.%d:",i);
        scanf("%d",&p[i]);
    }
	
	for(i=1;i<=np;i++)
	{
		for(j=1;j<=nb;j++)
		{
			if(barray[j]!=1)
			{
				temp=b[j]-p[i];
				if(temp>=0)
					if(lowest>temp)
					{
						parray[i]=j;
						lowest=temp;
					}
			}
		}
		
		fragment[i]=lowest;
		barray[parray[i]]=1;
		lowest=10000;
	}
	
	printf("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment");
	for(i=1;i<=np && parray[i]!=0;i++)
		printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,p[i],parray[i],b[parray[i]],fragment[i]);
}

Program for Best Fit Algorithm in C++

#include<iostream>

using namespace std;

int main()
{
	int fragment[20],b[20],p[20],i,j,nb,np,temp,lowest=9999;
	static int barray[20],parray[20];
	cout<<"\n\t\t\tMemory Management Scheme - Best Fit";
	cout<<"\nEnter the number of blocks:";
	cin>>nb;
	cout<<"Enter the number of processes:";
	cin>>np;
	
	cout<<"\nEnter the size of the blocks:-\n";
	for(i=1;i<=nb;i++)
    {
        cout<<"Block no."<<i<<":";
        cin>>b[i];
    }
	
	cout<<"\nEnter the size of the processes :-\n";
	for(i=1;i<=np;i++)
    {
        cout<<"Process no. "<<i<<":";
        cin>>p[i];
    }
	
	for(i=1;i<=np;i++)
	{
		for(j=1;j<=nb;j++)
		{
			if(barray[j]!=1)
			{
				temp=b[j]-p[i];
				if(temp>=0)
					if(lowest>temp)
					{
						parray[i]=j;
						lowest=temp;
					}
			}
		}
		
		fragment[i]=lowest;
		barray[parray[i]]=1;
		lowest=10000;
	}
	
	cout<<"\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment";
	for(i=1;i<=np && parray[i]!=0;i++)
		cout<<"\n"<<i<<"\t\t"<<p[i]<<"\t\t"<<parray[i]<<"\t\t"<<b[parray[i]]<<"\t\t"<<fragment[i];
	
	return 0;
}

Output

Image may be NSFW.
Clik here to view.
Best Fit Algorithm in C and C++

Comment below if you have any doubts related to above best fit algorithm in C and C++.

The post Best Fit Algorithm in C and C++ appeared first on The Crazy Programmer.


First Fit Algorithm in C and C++

Here you will learn about first fit algorithm in C and C++ with program examples.

There are various memory management schemes in operating system like first fit, best fit and worst fit. In this section we will talk about first fit scheme.

What is First Fit Memory Management Scheme?

In this scheme we check the blocks in a sequential manner which means we pick the first process then compare it’s size with first block size if it is less than size of block it is allocated otherwise we move to second block and so on.

When first process is allocated we move on to the next process until all processes are allocated.

Also Read: Best Fit Algorithm in C and C++

First Fit Algorithm

  1. Get no. of Processes and no. of blocks.
  2. After that get the size of each block and process requests.
  3. Now allocate processes
    if(block size >= process size)
    //allocate the process
    else
    //move on to next block
  4. Display the processes with the blocks that are allocated to a respective process.
  5. Stop.

Program for First Fit Algorithm in C

#include<stdio.h>

void main()
{
	int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;

	for(i = 0; i < 10; i++)
	{
		flags[i] = 0;
		allocation[i] = -1;
	}
	
	printf("Enter no. of blocks: ");
	scanf("%d", &bno);
	
	printf("\nEnter size of each block: ");
	for(i = 0; i < bno; i++)
		scanf("%d", &bsize[i]);

	printf("\nEnter no. of processes: ");
	scanf("%d", &pno);
	
	printf("\nEnter size of each process: ");
	for(i = 0; i < pno; i++)
		scanf("%d", &psize[i]);
	for(i = 0; i < pno; i++)         //allocation as per first fit
		for(j = 0; j < bno; j++)
			if(flags[j] == 0 && bsize[j] >= psize[i])
			{
				allocation[j] = i;
				flags[j] = 1;
				break;
			}
	
	//display allocation details
	printf("\nBlock no.\tsize\t\tprocess no.\t\tsize");
	for(i = 0; i < bno; i++)
	{
		printf("\n%d\t\t%d\t\t", i+1, bsize[i]);
		if(flags[i] == 1)
			printf("%d\t\t\t%d",allocation[i]+1,psize[allocation[i]]);
		else
			printf("Not allocated");
	}
}

Program for First Fit Algorithm in C++

#include<iostream>

using namespace std;

int main()
{
	int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;

	for(i = 0; i < 10; i++)
	{
		flags[i] = 0;
		allocation[i] = -1;
	}
	
	cout<<"Enter no. of blocks: ";
	cin>>bno;
	
	cout<<"\nEnter size of each block: ";
	for(i = 0; i < bno; i++)
		cin>>bsize[i];

	cout<<"\nEnter no. of processes: ";
	cin>>pno;
	
	cout<<"\nEnter size of each process: ";
	for(i = 0; i < pno; i++)
		cin>>psize[i];
	for(i = 0; i < pno; i++)         //allocation as per first fit
		for(j = 0; j < bno; j++)
			if(flags[j] == 0 && bsize[j] >= psize[i])
			{
				allocation[j] = i;
				flags[j] = 1;
				break;
			}
	
	//display allocation details
	cout<<"\nBlock no.\tsize\t\tprocess no.\t\tsize";
	for(i = 0; i < bno; i++)
	{
		cout<<"\n"<< i+1<<"\t\t"<<bsize[i]<<"\t\t";
		if(flags[i] == 1)
			cout<<allocation[i]+1<<"\t\t\t"<<psize[allocation[i]];
		else
			cout<<"Not allocated";
	}
	
	return 0;
}

Output

Image may be NSFW.
Clik here to view.
First Fit Algorithm in C and C++

Comment below if have any queries or found any information incorrect in above first fit algorithm in C and C++.

The post First Fit Algorithm in C and C++ appeared first on The Crazy Programmer.

Android Signature Capture Example Using Signature Pad Library

Here you will get android signature capture example.

You may have seen many eCommerce companies like Amazon provides a facility for digital signature. You can implement that feature in your app easily by using a library called Signature Pad.

Video Demo

Below tutorial shows you how to do this.

Android Signature Capture Example

Add to Layout

You can simply add a signature drawing view to your xml layout by using following tag.

<com.github.gcacace.signaturepad.views.SignaturePad
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/signaturePad"/>

Apply Listener

You can simply apply a listener to Signature Pad widget in following way.

signaturePad = (SignaturePad) findViewById(R.id.signaturePad);
signaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {

    @Override
    public void onStartSigning() {
        //Event triggered when the pad is touched
    }

   @Override
   public void onSigned() {
       //Event triggered when the pad is signed
   }

   @Override
   public void onClear() {
       //Event triggered when the pad is cleared
   }
});

Get Data

You can get signature data by following methods.

  • getSignatureBitmap() – Gets signature bitmap with a white background.
  • getTransparentSignatureBitmap() – Gets signature bitmap with a transparent background.
  • getSignatureSvg() – Gets signature Scalable Vector Graphics document.

For clearing the signature pad area use clear() method.

In below example I have just captured the signature and not saved it anywhere. You can get signature data using above methods and then save anywhere like in database or server.

Android Project

First create an android project with package name com.signaturecapture or you can use your existing project.

Now we have to add the Signature Pad library to our project. Add following line in your app level build.gradle file under dependencies section and then sync the project.

compile 'com.github.gcacace:signature-pad:1.2.1'

Add following code in respective files.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.signaturecapture.MainActivity"
    android:orientation="vertical">

    <com.github.gcacace.signaturepad.views.SignaturePad
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/signaturePad"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/saveButton"
            android:text="Save"
            android:layout_weight="1"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/clearButton"
            android:text="Clear"
            android:layout_weight="1"/>
    </LinearLayout>

</LinearLayout>

MainActivity.java

package com.signaturecapture;

import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.github.gcacace.signaturepad.views.SignaturePad;

public class MainActivity extends AppCompatActivity {
    SignaturePad signaturePad;
    Button saveButton, clearButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        signaturePad = (SignaturePad)findViewById(R.id.signaturePad);
        saveButton = (Button)findViewById(R.id.saveButton);
        clearButton = (Button)findViewById(R.id.clearButton);

        //disable both buttons at start
        saveButton.setEnabled(false);
        clearButton.setEnabled(false);

        //change screen orientation to landscape mode
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        signaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
            @Override
            public void onStartSigning() {

            }

            @Override
            public void onSigned() {
                saveButton.setEnabled(true);
                clearButton.setEnabled(true);
            }

            @Override
            public void onClear() {
                saveButton.setEnabled(false);
                clearButton.setEnabled(false);
            }
        });

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //write code for saving the signature here
                Toast.makeText(MainActivity.this, "Signature Saved", Toast.LENGTH_SHORT).show();
            }
        });

        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signaturePad.clear();
            }
        });
    }
}

Save and run your project.

Screenshot

Image may be NSFW.
Clik here to view.
Android Signature Capture Example Using Signature Pad Library

Comment below if you have any queries related to above android signature capture example.

The post Android Signature Capture Example Using Signature Pad Library appeared first on The Crazy Programmer.

Flood Fill Algorithm in C and C++

Here you will learn about flood fill algorithm in C and C++.

Flood Fill is a seed fill algorithm similar to Boundary Fill algorithm but sometimes when it is required to fill in an area that is not defined within a single color boundary we use flood fill instead of boundary fill.

For this purpose we can create a function or we can use a predefined function in the graphics.h header file which takes 3 arguments:-

floodfill(x,y,color)

Image may be NSFW.
Clik here to view.
Flood Fill Algorithm in C and C++

4 Connected Region (Image Source)

In Flood Fill algorithm we start with some seed and examine the neighboring pixels, however pixels are checked for a specified interior color instead of boundary color and is replaced by a new color. It can be done using 4 connected or 8 connected region method.

Below we use 4 connected region recursive algorithm to implement this algorithm.

Algorithm

1. Create a function called as floodFill (x,y,oldcolor,newcolor)

void floodFill(int x,int y,int oldcolor,int newcolor)
{
	if(getpixel(x,y) == oldcolor)
	{
		putpixel(x,y,newcolor);
		floodFill(x+1,y,oldcolor,newcolor);
		floodFill(x,y+1,oldcolor,newcolor);
		floodFill(x-1,y,oldcolor,newcolor);
		floodFill(x,y-1,oldcolor,newcolor);
	}
}
//getpixel(x,y) gives the color of specified pixel

2. Repeat until the polygon is completely filled.

3. Stop.

Program for Flood Fill Algorithm in C and C++

C Program

#include<stdio.h>
#include<graphics.h>
#include<dos.h>

void floodFill(int x,int y,int oldcolor,int newcolor)
{
	if(getpixel(x,y) == oldcolor)
	{
		putpixel(x,y,newcolor);
		floodFill(x+1,y,oldcolor,newcolor);
		floodFill(x,y+1,oldcolor,newcolor);
		floodFill(x-1,y,oldcolor,newcolor);
		floodFill(x,y-1,oldcolor,newcolor);
	}
}
//getpixel(x,y) gives the color of specified pixel 

int main()
{
	int gm,gd=DETECT,radius;
	int x,y;
	
	printf("Enter x and y positions for circle\n");
	scanf("%d%d",&x,&y);
	printf("Enter radius of circle\n");
	scanf("%d",&radius);
	
	initgraph(&gd,&gm,"c:\\turboc3\\bgi");
	circle(x,y,radius);
	floodFill(x,y,0,15);
	delay(5000);
	closegraph();
	
	return 0;
}

C++ Program

#include<iostream.h>
#include<graphics.h>
#include<dos.h>

void floodFill(int x,int y,int oldcolor,int newcolor)
{
	if(getpixel(x,y) == oldcolor)
	{
		putpixel(x,y,newcolor);
		floodFill(x+1,y,oldcolor,newcolor);
		floodFill(x,y+1,oldcolor,newcolor);
		floodFill(x-1,y,oldcolor,newcolor);
		floodFill(x,y-1,oldcolor,newcolor);
	}
}
//getpixel(x,y) gives the color of specified pixel 

int main()
{
	int gm,gd=DETECT,radius;
	int x,y;
	
	cout<<"Enter x and y positions for circle\n";
	cin>>x>>y;
	cout<<"Enter radius of circle\n";
	cin>>radius;
	
	initgraph(&gd,&gm,"c:\\turboc3\\bgi");
	circle(x,y,radius);
	floodFill(x,y,0,15);
	delay(5000);
	closegraph();
	
	return 0;
}

Author Bio:

I am Rahul Maheshwari from India currently pursuing engineering degree in Computer Science. I am passionate about programming and loves to code as much as I can and likes to help people to become better in programming.

Connect with him: Facebook | Linkedin

Comment below if you have queries or found anything incorrect in above flood fill algorithm in C and C++.

The post Flood Fill Algorithm in C and C++ appeared first on The Crazy Programmer.

Boundary Fill Algorithm in C and C++

Here you will learn about boundary fill algorithm in C and C++.

Boundary Fill is another seed fill algorithm in which edges of the polygon are drawn. Then starting with some seed any point inside the polygon we examine the neighboring pixels to check whether the boundary pixel is reached. If boundary pixels are not reached, pixels are highlighted and process is continued until boundary pixels are reached.

Also Read: Flood Fill Algorithm in C and C++

Image may be NSFW.
Clik here to view.
Flood Fill Algorithm in C and C++

4 Connected Region (Image Source)

Following is the algorithm for filling a region in a recursive manner with color specified fill color (f_color) up to a boundary color specified boundary color (b_color)

Algorithm

1. Create a function named as boundaryfill with 4 parameters (x,y,f_color,b_color).

void boundaryfill(int x,int y,int f_color,int b_color)
{
	if(getpixel(x,y)!=b_color && getpixel(x,y)!=f_color)
	{
		putpixel(x,y,f_color);
		boundaryfill(x+1,y,f_color,b_color);
		boundaryfill(x,y+1,f_color,b_color);
		boundaryfill(x-1,y,f_color,b_color);
		boundaryfill(x,y-1,f_color,b_color);
	}
}
//getpixel(x,y) gives the color of specified pixel

2. Call it recursively until the boundary pixels are reached.

3. Stop.

Program for Boundary Fill Algorithm in C and C++

C Program

#include<stdio.h>
#include<graphics.h>
#include<dos.h>

void boundaryfill(int x,int y,int f_color,int b_color)
{
	if(getpixel(x,y)!=b_color && getpixel(x,y)!=f_color)
	{
		putpixel(x,y,f_color);
		boundaryfill(x+1,y,f_color,b_color);
		boundaryfill(x,y+1,f_color,b_color);
		boundaryfill(x-1,y,f_color,b_color);
		boundaryfill(x,y-1,f_color,b_color);
	}
}
//getpixel(x,y) gives the color of specified pixel 

int main()
{
	int gm,gd=DETECT,radius;
	int x,y;
	
	printf("Enter x and y positions for circle\n");
	scanf("%d%d",&x,&y);
	printf("Enter radius of circle\n");
	scanf("%d",&radius);
	
	initgraph(&gd,&gm,"c:\\turboc3\\bgi");
	circle(x,y,radius);
	boundaryfill(x,y,4,15);
	delay(5000);
	closegraph();
	
	return 0;
}

C++ Program

#include<iostream.h>
#include<graphics.h>
#include<dos.h>

void boundaryfill(int x,int y,int f_color,int b_color)
{
	if(getpixel(x,y)!=b_color && getpixel(x,y)!=f_color)
	{
		putpixel(x,y,f_color);
		boundaryfill(x+1,y,f_color,b_color);
		boundaryfill(x,y+1,f_color,b_color);
		boundaryfill(x-1,y,f_color,b_color);
		boundaryfill(x,y-1,f_color,b_color);
	}
}
//getpixel(x,y) gives the color of specified pixel 

int main()
{
	int gm,gd=DETECT,radius;
	int x,y;
	cout<<"Enter x and y positions for circle\n";
	cin>>x>>y;
	cout<<"Enter radius of circle\n";
	cin>>radius;
	
	initgraph(&gd,&gm,"c:\\turboc3\\bgi");
	circle(x,y,radius);
	boundaryfill(x,y,4,15);
	delay(5000);
	closegraph();
	
	return 0;
}

Author Bio:

I am Rahul Maheshwari from India currently pursuing engineering degree in Computer Science. I am passionate about programming and loves to code as much as I can and likes to help people to become better in programming.

Connect with him: Facebook | Linkedin

Comment below if you have doubts or found anything incorrect in above boundary fill algorithm in C and C++.

The post Boundary Fill Algorithm in C and C++ appeared first on The Crazy Programmer.

Liang Barsky Line Clipping Algorithm in C and C++

Here you will learn about liang barsky line clipping algorithm in C and C++.

This Algorithm was developed by Liang and Barsky. It is used for line clipping as it is more efficient than Cyrus Beck algorithm and Cohen Sutherland algorithm because it uses more efficient parametric equations to clip the given line.

These parametric equations are given as:

x = x1 + tdx

y = y1 + tdy, 0 <= t <= 1

Where dx = x2 – x1 & dy = y2 – y1

Liang Barsky line clipping algorithm uses 4 inequalities with 2 parameters p & q which are defined in the algorithm below.

Algorithm

1. Read 2 endpoints of line as p1 (x1, y1) & p2 (x2, y2).

2. Read 2 corners (left-top & right-bottom) of the clipping window as (xwmin, ywmin, xwmax, ywmax).

3. Calculate values of parameters pi and qi for i = 1, 2, 3, 4 such that

p1 = -dx, q1 = x1 – xwmin

p2 = dx, q2 = xwmax – x1

p3 = -dy, q3 = y1 – ywmin

p4 = dy, q4 = ywmax – y1

4. if pi = 0 then line is parallel to ith boundary

if qi < 0 then line is completely outside boundary so discard line

else, check whether line is horizontal or vertical and then check the line endpoints with the corresponding boundaries.

5. Initialize t1 & t2 as

t1 = 0 & t2 = 1

6. Calculate values for qi/pi for i = 1, 2, 3, 4.

7. Select values of qi/pi where pi < 0 and assign maximum out of them as t1.

8. Select values of qi/pi where pi > 0 and assign minimum out of them as t2.

9. if (t1 < t2)
{
xx1 = x1 + t1dx

xx2 = x1 + t2dx

yy1 = y1 + t1dy

yy2 = y1 + t2dy

line (xx1, yy1, xx2, yy2)
}

10. Stop.

Advantages

1. More efficient than other algorithms as line intersection with boundaries calculations are reduced.

2. Intersections of line are computed only once.

Program for Liang Barsky Line Clipping Algorithm in C and C++

C Program

#include<stdio.h>
#include<graphics.h>
#include<math.h>
#include<dos.h>

void main()
{
	int i,gd=DETECT,gm;
	int x1,y1,x2,y2,xmin,xmax,ymin,ymax,xx1,xx2,yy1,yy2,dx,dy;
	float t1,t2,p[4],q[4],temp;
	
	x1=120;
	y1=120;
	x2=300;
	y2=300;
	
	xmin=100;
	ymin=100;
	xmax=250;
	ymax=250;
	
	initgraph(&gd,&gm,"c:\\turboc3\\bgi");
	rectangle(xmin,ymin,xmax,ymax);
	dx=x2-x1;
	dy=y2-y1;
	
	p[0]=-dx;
	p[1]=dx;
	p[2]=-dy;
	p[3]=dy;
	
	q[0]=x1-xmin;
	q[1]=xmax-x1;
	q[2]=y1-ymin;
	q[3]=ymax-y1;
	
	for(i=0;i<4;i++)
	{
		if(p[i]==0)
		{
			printf("line is parallel to one of the clipping boundary");
			if(q[i]>=0)
			{
				if(i<2)
				{
					if(y1<ymin)
					{
						y1=ymin;
					}
				
					if(y2>ymax)
					{
						y2=ymax;
					}
				
					line(x1,y1,x2,y2);
				}
				
				if(i>1)
				{
					if(x1<xmin)
					{
						x1=xmin;
					}
					
					if(x2>xmax)
					{
						x2=xmax;
					}
					
					line(x1,y1,x2,y2);
				}
			}
		}
	}
	
	t1=0;
	t2=1;
	
	for(i=0;i<4;i++)
	{
		temp=q[i]/p[i];
		
		if(p[i]<0)
		{
			if(t1<=temp)
				t1=temp;
		}
		else
		{
			if(t2>temp)
				t2=temp;
		}
	}
	
	if(t1<t2)
	{
		xx1 = x1 + t1 * p[1];
		xx2 = x1 + t2 * p[1];
		yy1 = y1 + t1 * p[3];
		yy2 = y1 + t2 * p[3];
		line(xx1,yy1,xx2,yy2);
	}
	
	delay(5000);
	closegraph();
}

C++ Program

#include<iostream.h>
#include<graphics.h>
#include<math.h>
#include<dos.h>

void main()
{
	int i,gd=DETECT,gm;
	int x1,y1,x2,y2,xmin,xmax,ymin,ymax,xx1,xx2,yy1,yy2,dx,dy;
	float t1,t2,p[4],q[4],temp;
	
	x1=120;
	y1=120;
	x2=300;
	y2=300;
	
	xmin=100;
	ymin=100;
	xmax=250;
	ymax=250;
	
	initgraph(&gd,&gm,"c:\\turboc3\\bgi");
	rectangle(xmin,ymin,xmax,ymax);
	dx=x2-x1;
	dy=y2-y1;
	
	p[0]=-dx;
	p[1]=dx;
	p[2]=-dy;
	p[3]=dy;
	
	q[0]=x1-xmin;
	q[1]=xmax-x1;
	q[2]=y1-ymin;
	q[3]=ymax-y1;
	
	for(i=0;i<4;i++)
	{
		if(p[i]==0)
		{
			cout<<"line is parallel to one of the clipping boundary";
			if(q[i]>=0)
			{
				if(i<2)
				{
					if(y1<ymin)
					{
						y1=ymin;
					}
				
					if(y2>ymax)
					{
						y2=ymax;
					}
				
					line(x1,y1,x2,y2);
				}
				
				if(i>1)
				{
					if(x1<xmin)
					{
						x1=xmin;
					}
					
					if(x2>xmax)
					{
						x2=xmax;
					}
					
					line(x1,y1,x2,y2);
				}
			}
		}
	}
	
	t1=0;
	t2=1;
	
	for(i=0;i<4;i++)
	{
		temp=q[i]/p[i];
		
		if(p[i]<0)
		{
			if(t1<=temp)
				t1=temp;
		}
		else
		{
			if(t2>temp)
				t2=temp;
		}
	}
	
	if(t1<t2)
	{
		xx1 = x1 + t1 * p[1];
		xx2 = x1 + t2 * p[1];
		yy1 = y1 + t1 * p[3];
		yy2 = y1 + t2 * p[3];
		line(xx1,yy1,xx2,yy2);
	}
	
	delay(5000);
	closegraph();
}

Output

Image may be NSFW.
Clik here to view.
Liang-Barsky Line Clipping Algorithm in C and C++

Author Bio:

I am Rahul Maheshwari from India currently pursuing engineering degree in Computer Science. I am passionate about programming and loves to code as much as I can and likes to help people to become better in programming.

Connect with him: Facebook | Linkedin

Comment below if you have doubts or found anything incorrect in above liang barsky line clipping algorithm in C and C++.

The post Liang Barsky Line Clipping Algorithm in C and C++ appeared first on The Crazy Programmer.

Cohen Sutherland Line Clipping Algorithm in C and C++

Here you will learn about cohen sutherland line clipping algorithm in C and C++.

This is one of the oldest and most popular line clipping algorithm. To speed up the process this algorithm performs initial tests that reduce number of intersections that must be calculated. It does so by using a 4 bit code called as region code or outcodes. These codes identify location of the end point of line.

Each bit position indicates a direction, starting from the rightmost position of each bit indicates left, right, bottom, top respectively.

Once we establish region codes for both the endpoints of a line we determine whether the endpoint is visible, partially visible or invisible with the help of ANDing of the region codes.

There arises 3 cases which are explained in the algorithm below in step 4.

Also Read: Liang Barsky Line Clipping Algorithm in C and C++

Algorithm

1. Read 2 end points of line as p1(x1,y1) and p2(x2,y2)

2. Read 2 corner points of the clipping window (left-top and right-bottom) as (wx1,wy1) and (wx2,wy2)

3. Assign the region codes for 2 endpoints p1 and p2 using following steps:-

initialize code with 0000

Set bit 1 if x<wx1

Set bit 2 if x>wx2

Set bit 3 if y<wy2

Set bit 4 if y>wy1

4. Check for visibility of line

  1. If region codes for both endpoints are zero then line is completely visible. Draw the line go to step 9.
  2. If region codes for endpoints are not zero and logical ANDing of them is also nonzero then line is invisible. Discard the line and move to step 9.
  3. If it does not satisfy 4.a and 4.b then line is partially visible.

5. Determine the intersecting edge of clipping window as follows:-

  1. If region codes for both endpoints are nonzero find intersection points p1’ and p2’ with boundary edges.
  2. If region codes for any one end point is non zero then find intersection point p1’ or p2’.

6. Divide the line segments considering intersection points.

7. Reject line segment if any end point of line appears outside of any boundary.

8. Draw the clipped line segment.

9. Stop.

Program for Cohen Sutherland Line Clipping Algorithm in C and C++

C Program

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<graphics.h>
#include<dos.h>

typedef struct coordinate
{
	int x,y;
	char code[4];
}PT;

void drawwindow();
void drawline(PT p1,PT p2);
PT setcode(PT p);
int visibility(PT p1,PT p2);
PT resetendpt(PT p1,PT p2);

void main()
{
	int gd=DETECT,v,gm;
	PT p1,p2,p3,p4,ptemp;
	
	printf("\nEnter x1 and y1\n");
	scanf("%d %d",&p1.x,&p1.y);
	printf("\nEnter x2 and y2\n");
	scanf("%d %d",&p2.x,&p2.y);
	
	initgraph(&gd,&gm,"c:\\turboc3\\bgi");
	drawwindow();
	delay(500);
	
	drawline(p1,p2);
	delay(500);
	cleardevice();
	
	delay(500);
	p1=setcode(p1);
	p2=setcode(p2);
	v=visibility(p1,p2);
	delay(500);
	
	switch(v)
	{
	case 0: drawwindow();
			delay(500);
			drawline(p1,p2);
			break;
	case 1:	drawwindow();
			delay(500);
			break;
	case 2:	p3=resetendpt(p1,p2);
			p4=resetendpt(p2,p1);
			drawwindow();
			delay(500);
			drawline(p3,p4);
			break;
	}
	
	delay(5000);
	closegraph();
}

void drawwindow()
{
	line(150,100,450,100);
	line(450,100,450,350);
	line(450,350,150,350);
	line(150,350,150,100);
}

void drawline(PT p1,PT p2)
{
	line(p1.x,p1.y,p2.x,p2.y);
}

PT setcode(PT p)	//for setting the 4 bit code
{
	PT ptemp;
	
	if(p.y<100)
		ptemp.code[0]='1';	//Top
	else
		ptemp.code[0]='0';
	
	if(p.y>350)
		ptemp.code[1]='1';	//Bottom
	else
		ptemp.code[1]='0';
		
	if(p.x>450)
		ptemp.code[2]='1';	//Right
	else
		ptemp.code[2]='0';
		
	if(p.x<150)
		ptemp.code[3]='1';	//Left
	else
		ptemp.code[3]='0';
	
	ptemp.x=p.x;
	ptemp.y=p.y;
	
	return(ptemp);
}

int visibility(PT p1,PT p2)
{
	int i,flag=0;
	
	for(i=0;i<4;i++)
	{
		if((p1.code[i]!='0') || (p2.code[i]!='0'))
			flag=1;
	}
	
	if(flag==0)
		return(0);
	
	for(i=0;i<4;i++)
	{
		if((p1.code[i]==p2.code[i]) && (p1.code[i]=='1'))
			flag='0';
	}
	
	if(flag==0)
		return(1);
	
	return(2);
}

PT resetendpt(PT p1,PT p2)
{
	PT temp;
	int x,y,i;
	float m,k;
	
	if(p1.code[3]=='1')
		x=150;
	
	if(p1.code[2]=='1')
		x=450;
	
	if((p1.code[3]=='1') || (p1.code[2]=='1'))
	{
		m=(float)(p2.y-p1.y)/(p2.x-p1.x);
		k=(p1.y+(m*(x-p1.x)));
		temp.y=k;
		temp.x=x;
		
		for(i=0;i<4;i++)
			temp.code[i]=p1.code[i];
		
		if(temp.y<=350 && temp.y>=100)
			return (temp);
	}
	
	if(p1.code[0]=='1')
		y=100;
	
	if(p1.code[1]=='1')
		y=350;
		
	if((p1.code[0]=='1') || (p1.code[1]=='1'))
	{
		m=(float)(p2.y-p1.y)/(p2.x-p1.x);
		k=(float)p1.x+(float)(y-p1.y)/m;
		temp.x=k;
		temp.y=y;
		
		for(i=0;i<4;i++)
			temp.code[i]=p1.code[i];
		
		return(temp);
	}
	else
		return(p1);
}

C++ Program

#include<iostream.h>
#include<stdlib.h>
#include<math.h>
#include<graphics.h>
#include<dos.h>

typedef struct coordinate
{
	int x,y;
	char code[4];
}PT;

void drawwindow();
void drawline(PT p1,PT p2);
PT setcode(PT p);
int visibility(PT p1,PT p2);
PT resetendpt(PT p1,PT p2);

void main()
{
	int gd=DETECT,v,gm;
	PT p1,p2,p3,p4,ptemp;
	
	cout<<"\nEnter x1 and y1\n";
	cin>>p1.x>>p1.y;
	cout<<"\nEnter x2 and y2\n";
	cin>>p2.x>>p2.y;
	
	initgraph(&gd,&gm,"c:\\turboc3\\bgi");
	drawwindow();
	delay(500);
	
	drawline(p1,p2);
	delay(500);
	cleardevice();
	
	delay(500);
	p1=setcode(p1);
	p2=setcode(p2);
	v=visibility(p1,p2);
	delay(500);
	
	switch(v)
	{
	case 0: drawwindow();
			delay(500);
			drawline(p1,p2);
			break;
	case 1:	drawwindow();
			delay(500);
			break;
	case 2:	p3=resetendpt(p1,p2);
			p4=resetendpt(p2,p1);
			drawwindow();
			delay(500);
			drawline(p3,p4);
			break;
	}
	
	delay(5000);
	closegraph();
}

void drawwindow()
{
	line(150,100,450,100);
	line(450,100,450,350);
	line(450,350,150,350);
	line(150,350,150,100);
}

void drawline(PT p1,PT p2)
{
	line(p1.x,p1.y,p2.x,p2.y);
}

PT setcode(PT p)	//for setting the 4 bit code
{
	PT ptemp;
	
	if(p.y<100)
		ptemp.code[0]='1';	//Top
	else
		ptemp.code[0]='0';
	
	if(p.y>350)
		ptemp.code[1]='1';	//Bottom
	else
		ptemp.code[1]='0';
		
	if(p.x>450)
		ptemp.code[2]='1';	//Right
	else
		ptemp.code[2]='0';
		
	if(p.x<150)
		ptemp.code[3]='1';	//Left
	else
		ptemp.code[3]='0';
	
	ptemp.x=p.x;
	ptemp.y=p.y;
	
	return(ptemp);
}

int visibility(PT p1,PT p2)
{
	int i,flag=0;
	
	for(i=0;i<4;i++)
	{
		if((p1.code[i]!='0') || (p2.code[i]!='0'))
			flag=1;
	}
	
	if(flag==0)
		return(0);
	
	for(i=0;i<4;i++)
	{
		if((p1.code[i]==p2.code[i]) && (p1.code[i]=='1'))
			flag='0';
	}
	
	if(flag==0)
		return(1);
	
	return(2);
}

PT resetendpt(PT p1,PT p2)
{
	PT temp;
	int x,y,i;
	float m,k;
	
	if(p1.code[3]=='1')
		x=150;
	
	if(p1.code[2]=='1')
		x=450;
	
	if((p1.code[3]=='1') || (p1.code[2]=='1'))
	{
		m=(float)(p2.y-p1.y)/(p2.x-p1.x);
		k=(p1.y+(m*(x-p1.x)));
		temp.y=k;
		temp.x=x;
		
		for(i=0;i<4;i++)
			temp.code[i]=p1.code[i];
		
		if(temp.y<=350 && temp.y>=100)
			return (temp);
	}
	
	if(p1.code[0]=='1')
		y=100;
	
	if(p1.code[1]=='1')
		y=350;
		
	if((p1.code[0]=='1') || (p1.code[1]=='1'))
	{
		m=(float)(p2.y-p1.y)/(p2.x-p1.x);
		k=(float)p1.x+(float)(y-p1.y)/m;
		temp.x=k;
		temp.y=y;
		
		for(i=0;i<4;i++)
			temp.code[i]=p1.code[i];
		
		return(temp);
	}
	else
		return(p1);
}

Output

Image may be NSFW.
Clik here to view.
Cohen Sutherland Line Clipping Algorithm in C and C++

Before Clipping

Image may be NSFW.
Clik here to view.
Cohen Sutherland Line Clipping Algorithm in C and C++

After Clipping

Image may be NSFW.
Clik here to view.
Cohen Sutherland Line Clipping Algorithm in C and C++

Comment below if you have doubts or found any information incorrect in above cohen sutherland line clipping algorithm in C and C++.

The post Cohen Sutherland Line Clipping Algorithm in C and C++ appeared first on The Crazy Programmer.

Android Upload Image to Firebase Storage Tutorial

In this tutorial you will learn to upload image to firebase storage in android.

Firebase storage provides facility to upload any file like image, video, audio, etc without using server side code.

Lets quickly learn how we can implement this in android.

Also Read: Android Push Notification Using Firebase Cloud Messaging (FCM)

Android Upload Image to Firebase Storage

Adding Firebase to Project

First of all we have to connect our project to firebase and then add the required dependencies. For doing this just follow below steps.

Note: Below method of adding firebase will work only in android studio 2.2 and higher versions. If you are using any older version then follow this link to learn how to add firebase.

1. In android studio go to Tools > Firebase. It will open firebase assistant that allows us to add firebase to android studio within few clicks.

Image may be NSFW.
Clik here to view.
Android Upload Image to Firebase Storage Tutorial 1

2. Now you will see a window as shown below. Just click on Storage section and then click Upload and download a file with Firebase Storage.

Image may be NSFW.
Clik here to view.
Android Upload Image to Firebase Storage Tutorial 2

3. Click on Connect to Firebase, this will open a browser where you have to login to firebase using google account.

Image may be NSFW.
Clik here to view.
Android Upload Image to Firebase Storage Tutorial 3

4. After that you will see a window as shown below. Here you can create a new firebase project or use an existing one. In my case I am using an existing project. Finally click on Connect to Firebase.

Image may be NSFW.
Clik here to view.
Android Upload Image to Firebase Storage Tutorial 4

5. Now click on Add Firebase Storage to your app. In the next window click on Accept Changes to add all firebase storage related dependencies to android studio project.

Image may be NSFW.
Clik here to view.
Android Upload Image to Firebase Storage Tutorial 3

Image may be NSFW.
Clik here to view.
Android Upload Image to Firebase Storage Tutorial 5

Change Rules

By default we are not allowed to access firebase storage without authentication. To change it go to firebase console using any web browser. Open the firebase project that you have used in above steps and go to Storage and then Rules tab. Now change read and write rules to true as shown in below image.

Image may be NSFW.
Clik here to view.
Android Upload Image to Firebase Storage Tutorial 6

Android Project

Now comes the actual coding part. In this simple example I have given two button, one to choose the image from gallery and another to upload it.

1. Firstly image is selected from gallery using file chooser and displayed in ImageView.

2. Before using firebase we have to get its instance and then using the instance create reference to firebase storage app. It can be done by following code.

//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com");    //change the url according to your firebase app

3. Now a child reference is created and using it we call putFile() method to upload image to firebase storage.

4. If image is uploaded successfully then success message is shown otherwise error is shown in toast.

Below I have shared the full code for this.

Full Source Code

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.firebaseimageupload.MainActivity"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choose Image"
        android:id="@+id/chooseImg"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Upload Image"
        android:id="@+id/uploadImg"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:id="@+id/imgView"/>
</LinearLayout>

MainActivity.java

package com.firebaseimageupload;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

public class MainActivity extends AppCompatActivity {
    Button chooseImg, uploadImg;
    ImageView imgView;
    int PICK_IMAGE_REQUEST = 111;
    Uri filePath;
    ProgressDialog pd;

    //creating reference to firebase storage
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com");    //change the url according to your firebase app


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        chooseImg = (Button)findViewById(R.id.chooseImg);
        uploadImg = (Button)findViewById(R.id.uploadImg);
        imgView = (ImageView)findViewById(R.id.imgView);

        pd = new ProgressDialog(this);
        pd.setMessage("Uploading....");


        chooseImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
            }
        });

        uploadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(filePath != null) {
                    pd.show();

                    StorageReference childRef = storageRef.child("image.jpg");

                    //uploading the image
                    UploadTask uploadTask = childRef.putFile(filePath);

                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            pd.dismiss();
                            Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            pd.dismiss();
                            Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                else {
                    Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();

            try {
                //getting image from gallery
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);

                //Setting image to ImageView
                imgView.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Now run and test your app.

Screenshots

Image may be NSFW.
Clik here to view.
Android Upload Image to Firebase Storage Tutorial

When you will login to firebase console the uploaded image will be shown something as given below.

Image may be NSFW.
Clik here to view.
Android Upload Image to Firebase Storage Tutorial 7

 

Comment below if you have any queries related to above android upload image to firebase storage example.

 

The post Android Upload Image to Firebase Storage Tutorial appeared first on The Crazy Programmer.


Checksum Program in C and C++

Here you will get checksum program in C and C++.

A checksum is a error detection method in Data Communication. It is used for errors which may have been introduced during transmission or storage. It is usually applied to an installation file after it is received from the download server.

The actual procedure which yields the checksum, given a data input is called a checksum function or checksum algorithm.

Checksum method can only detect errors but is unable to correct the error.

In this method a checksum is calculated based on the given binary strings which is sent with the data as redundant bits. This data + checksum is received at receiver end and checksum is calculated again, if checksum is 0 it means no error in data received, else there exists some error in the received data.

For the purpose of this program we are finding checksum for 2 binary strings.

Checksum Algorithm

  1. Take 2 binary input strings.
  2. Do their binary sum to find out the checksum which will be sent to the destination or to the receiver.
  3. In binary sum there are 6 cases:-
    1. If both bits are 0 and carry is 0, sum=0 and carry=0
    2. If both bits are 0 and carry is 1,sum=1 and carry=0
    3. If both bits are 1 and carry is 0,sum=0 and carry=1
    4. If both bits are 1 and carry is 1,sum=1 and carry=1
    5. If either bit is 1 and carry is 0,sum=1 and carry=0
    6. If either bit is 1 and carry is 1,sum=0 and carry=1
  4. While doing the addition we have to add the binary strings from rightmost end i.e LSB to MSB.
  5. When binary sum is done 1’s complement of it is taken by reversing 1’s to 0’s and vice versa.
  6. The resulting 1’s complement is the Checksum.
  7. Stop.

Checksum Program in C

#include<stdio.h>
#include<string.h>

int main()
{
    char a[20],b[20];
    char sum[20],complement[20];
    int i,length;
    
	printf("Enter first binary string\n");
    scanf("%s",&a);
    printf("Enter second binary string\n");
    scanf("%s",&b);
    
    if(strlen(a)==strlen(b)){
		length = strlen(a);
		char carry='0';
        
		for(i=length-1;i>=0;i--)
        {
			if(a[i]=='0' && b[i]=='0' && carry=='0')
            {
                sum[i]='0';
                carry='0';
            }
            else if(a[i]=='0' && b[i]=='0' && carry=='1')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='0' && b[i]=='1' && carry=='0')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='0' && b[i]=='1' && carry=='1')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='0' && carry=='0')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='1' && b[i]=='0' && carry=='1')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='1' && carry=='0')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='1' && carry=='1')
            {
                sum[i]='1';
                carry='1';

            }
            else
                break;
        }
        
		printf("\nSum=%c%s",carry,sum);
		
		for(i=0;i<length;i++)
        {
            if(sum[i]=='0')
                complement[i]='1';
            else
                complement[i]='0';
        }
        
        if(carry=='1')
            carry='0';
        else
            carry='1';
        
		printf("\nChecksum=%c%s",carry,complement);
	}
	else {
		printf("\nWrong input strings");
	}
}

Checksum Program in C++

#include<iostream>
#include<string.h>

using namespace std;

int main()
{
    char a[20],b[20];
    char sum[20],complement[20];
    int i;
    
	cout<<"Enter first binary string\n";
    cin>>a;
    cout<<"Enter second binary string\n";
    cin>>b;
    
	if(strlen(a)==strlen(b))
    {
        char carry='0';
        int length=strlen(a);
        
		for(i=length-1;i>=0;i--)
        {
            if(a[i]=='0' && b[i]=='0' && carry=='0')
            {
                sum[i]='0';
                carry='0';
            }
            else if(a[i]=='0' && b[i]=='0' && carry=='1')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='0' && b[i]=='1' && carry=='0')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='0' && b[i]=='1' && carry=='1')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='0' && carry=='0')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='1' && b[i]=='0' && carry=='1')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='1' && carry=='0')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='1' && carry=='1')
            {
                sum[i]='1';
                carry='1';

            }
            else
                break;
        }
        cout<<"\nSum="<<carry<<sum;

        for(i=0;i<length;i++)
        {
            if(sum[i]=='0')
                complement[i]='1';
            else
                complement[i]='0';
        }
        
		if(carry=='1')
            carry='0';
        else
            carry='1';
     
	    cout<<"\nChecksum="<<carry<<complement;
    }
    else
        cout<<"\nWrong input strings";
        
    return 0;
}

Output

Image may be NSFW.
Clik here to view.
Checksum Program in C and C++

This article is submitted by Rahul Maheshwari. You can connect with him on facebook.

Comment below if you have queries or found anything incorrect in above checksum program in C and C++.

The post Checksum Program in C and C++ appeared first on The Crazy Programmer.

Lexical Analyzer in C and C++

Here you will get program to implement lexical analyzer in C and C++.

Compiler is responsible for converting high level language in machine language. There are several phases involved in this and lexical analysis is the first phase.

Lexical analyzer reads the characters from source code and convert it into tokens.

Image may be NSFW.
Clik here to view.
Lexical Analyzer in C and C++

Different tokens or lexemes are:

  • Keywords
  • Identifiers
  • Operators
  • Constants

Take below example.

c = a + b;

After lexical analysis a symbol table is generated as given below.

Token Type
c identifier
= operator
a identifier
+ operator
b identifier
; separator

Now below I have given implementation of very simple lexical analyzer which reads source code from file and then generate tokens.

Program for Lexical Analyzer in C

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

int isKeyword(char buffer[]){
	char keywords[32][10] = {"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"};
	int i, flag = 0;
	
	for(i = 0; i < 32; ++i){
		if(strcmp(keywords[i], buffer) == 0){
			flag = 1;
			break;
		}
	}
	
	return flag;
}

int main(){
	char ch, buffer[15], operators[] = "+-*/%=";
	FILE *fp;
	int i,j=0;
	
	fp = fopen("program.txt","r");
	
	if(fp == NULL){
		printf("error while opening the file\n");
		exit(0);
	}
	
	while((ch = fgetc(fp)) != EOF){
   		for(i = 0; i < 6; ++i){
   			if(ch == operators[i])
   				printf("%c is operator\n", ch);
   		}
   		
   		if(isalnum(ch)){
   			buffer[j++] = ch;
   		}
   		else if((ch == ' ' || ch == '\n') && (j != 0)){
   				buffer[j] = '\0';
   				j = 0;
   				   				
   				if(isKeyword(buffer) == 1)
   					printf("%s is keyword\n", buffer);
   				else
   					printf("%s is indentifier\n", buffer);
   		}
   		
	}
	
	fclose(fp);
	
	return 0;
}

Program for Lexical Analyzer in C++

#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

using namespace std;

int isKeyword(char buffer[]){
	char keywords[32][10] = {"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"};
	int i, flag = 0;
	
	for(i = 0; i < 32; ++i){
		if(strcmp(keywords[i], buffer) == 0){
			flag = 1;
			break;
		}
	}
	
	return flag;
}

int main(){
	char ch, buffer[15], operators[] = "+-*/%=";
	ifstream fin("program.txt");
	int i,j=0;
	
	if(!fin.is_open()){
		cout<<"error while opening the file\n";
		exit(0);
	}
	
	while(!fin.eof()){
   		ch = fin.get();
   		
		for(i = 0; i < 6; ++i){
   			if(ch == operators[i])
   				cout<<ch<<" is operator\n";
   		}
   		
   		if(isalnum(ch)){
   			buffer[j++] = ch;
   		}
   		else if((ch == ' ' || ch == '\n') && (j != 0)){
   				buffer[j] = '\0';
   				j = 0;
   				   				
   				if(isKeyword(buffer) == 1)
   					cout<<buffer<<" is keyword\n";
   				else
   					cout<<buffer<<" is indentifier\n";
   		}
   		
	}
	
	fin.close();
	
	return 0;
}

Output

Image may be NSFW.
Clik here to view.
Lexical Analyzer in C and C++

The source code present in file is shown in above image.

Comment below if you have any queries regarding above program for lexical analyzer in C and C++.

 

The post Lexical Analyzer in C and C++ appeared first on The Crazy Programmer.

Bucket Sort in C and C++

Here you will get program for bucket sort in C and C++.

In bucket sort algorithm the array elements are distributed into a number of buckets. Then each bucket sorted individually either using any other sorting algorithm or by recursively applying bucket sort.

Take example shown in below image.

Image may be NSFW.
Clik here to view.
Bucket Sort

Elements are distributed among buckets

Image may be NSFW.
Clik here to view.
Bucket Sort

Then, elements are sorted within each bucket

Below is the program to implement this algorithm. In this program it is assumed that the array elements are between 0 to 10.

Program for Bucket Sort in C

#include<stdio.h>

#define SIZE 10

void bucketSort(int a[], int n) {
	int i, j, k, buckets[SIZE];
	
	for(i = 0; i < SIZE; ++i)
		buckets[i] = 0;
	
	for(i = 0; i < n; ++i)
		++buckets[a[i]];
		
	for(i = 0, j = 0; j < SIZE; ++j)
		for(k = buckets[j]; k > 0; --k)
			a[i++] = j;
}

int main() {
	int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8;
	
	printf("Before sorting:\n");
	for(i = 0; i < n; ++i)
		printf("%d ", a[i]);
	
	bucketSort(a, 8);
	
	printf("\n\nAfter sorting:\n");
	for(i = 0; i < n; ++i)
		printf("%d ", a[i]);
	
	return 0;
}

Program for Bucket Sort in C++

#include<iostream>

#define SIZE 10

using namespace std;

void bucketSort(int a[], int n) {
	int i, j, k, buckets[SIZE];
	
	for(i = 0; i < SIZE; ++i)
		buckets[i] = 0;
	
	for(i = 0; i < n; ++i)
		++buckets[a[i]];
		
	for(i = 0, j = 0; j < SIZE; ++j)
		for(k = buckets[j]; k > 0; --k)
			a[i++] = j;
}

int main() {
	int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8;
	
	cout << "Before sorting:\n";
	for(i = 0; i < n; ++i)
		cout << a[i] << " ";
	
	bucketSort(a, 8);
	
	cout<< "\n\nAfter sorting:\n";
	for(i = 0; i < n; ++i)
		cout<< a[i] << " ";
	
	return 0;
}

Output

Before sorting:
3 6 5 1 8 4 3 1

After sorting:
1 1 3 3 4 5 6 8

The post Bucket Sort in C and C++ appeared first on The Crazy Programmer.

C and C++ Program to Find Inverse of a Matrix

Here you will get C and C++ program to find inverse of a matrix.

We can obtain matrix inverse by following method.

  • First calculate deteminant of matrix.
  • Then calculate adjoint of given matrix. Adjoint can be obtained by taking transpose of cofactor matrix of given square matrix.
  • Finally multiply 1/deteminant by adjoint to get inverse.

The formula to find inverse of matrix is given below.

Image may be NSFW.
Clik here to view.
Matrix Inverse Formula

You can watch below video to learn how inverse is calculated.

In below program I have calculated the inverse of 3×3 matrix.

C Program to Find Inverse of a Matrix

#include<stdio.h>

int main(){
	int mat[3][3], i, j;
	float determinant = 0;
	
	printf("Enter elements of matrix row wise:\n");
	for(i = 0; i < 3; i++)
		for(j = 0; j < 3; j++)
           scanf("%d", &mat[i][j]);
	
	printf("\nGiven matrix is:");
	for(i = 0; i < 3; i++){
		printf("\n");
		
		for(j = 0; j < 3; j++)
			printf("%d\t", mat[i][j]);
	}
	
	//finding determinant
	for(i = 0; i < 3; i++)
		determinant = determinant + (mat[0][i] * (mat[1][(i+1)%3] * mat[2][(i+2)%3] - mat[1][(i+2)%3] * mat[2][(i+1)%3]));
	
	printf("\n\ndeterminant: %f\n", determinant);
	
	printf("\nInverse of matrix is: \n");
	for(i = 0; i < 3; i++){
		for(j = 0; j < 3; j++)
			printf("%.2f\t",((mat[(j+1)%3][(i+1)%3] * mat[(j+2)%3][(i+2)%3]) - (mat[(j+1)%3][(i+2)%3] * mat[(j+2)%3][(i+1)%3]))/ determinant);
		
		printf("\n");
	}

   return 0;
}

C++ Program to Find Inverse of a Matrix

#include<iostream>

using namespace std;

int main(){
	int mat[3][3], i, j;
	float determinant = 0;
	
	cout<<"Enter elements of matrix row wise:\n";
	for(i = 0; i < 3; i++)
		for(j = 0; j < 3; j++)
           cin>>mat[i][j];
	
	printf("\nGiven matrix is:");
	for(i = 0; i < 3; i++){
		cout<<"\n";
		
		for(j = 0; j < 3; j++)
			cout<<mat[i][j]<<"\t";
	}
	
	//finding determinant
	for(i = 0; i < 3; i++)
		determinant = determinant + (mat[0][i] * (mat[1][(i+1)%3] * mat[2][(i+2)%3] - mat[1][(i+2)%3] * mat[2][(i+1)%3]));
	
	cout<<"\n\ndeterminant: "<<determinant;
	
	cout<<"\n\nInverse of matrix is: \n";
	for(i = 0; i < 3; i++){
		for(j = 0; j < 3; j++)
			cout<<((mat[(j+1)%3][(i+1)%3] * mat[(j+2)%3][(i+2)%3]) - (mat[(j+1)%3][(i+2)%3] * mat[(j+2)%3][(i+1)%3]))/ determinant<<"\t";
		
		cout<<"\n";
	}

   return 0;
}

Output

Image may be NSFW.
Clik here to view.
C and C++ Program to Find Inverse of a Matrix

The post C and C++ Program to Find Inverse of a Matrix appeared first on The Crazy Programmer.

Hill Cipher in C and C++ (Encryption and Decryption)

Here you get encryption and decryption program for hill cipher in C and C++.

What is Hill Cipher?

In cryptography (field related to encryption-decryption) hill cipher is a polygraphic cipher based on linear algebra. Invented by Lester S. Hill in 1929 and thus got it’s name. It was the first cipher that was able to operate on 3 symbols at once.

Also Read: Caesar Cipher in C and C++ [Encryption & Decryption]

Encryption: The given message string and key string is represented in the form of matrix. Then key and message matrix are multiplied. Finally modulo 26 is taken for each element of matrix obtained by multiplication. The key matrix that we take here should be invertible, otherwise decryption will not be possible.

Decryption: The encrypted message matrix is multiplied by the inverse of key matrix and finally its modulo 26 is taken to get the original message.

To learn more about hill cipher you can visit following link.

https://en.wikipedia.org/wiki/Hill_cipher

Hill Cipher Program in C

#include<stdio.h>
#include<math.h>

float encrypt[3][1], decrypt[3][1], a[3][3], b[3][3], mes[3][1], c[3][3];

void encryption();	//encrypts the message
void decryption();	//decrypts the message
void getKeyMessage();	//gets key and message from user
void inverse();		//finds inverse of key matrix

void main() {
	getKeyMessage();
	encryption();
	decryption();
}

void encryption() {
	int i, j, k;
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 1; j++)
			for(k = 0; k < 3; k++)
				encrypt[i][j] = encrypt[i][j] + a[i][k] * mes[k][j];
	
	printf("\nEncrypted string is: ");
	for(i = 0; i < 3; i++)
		printf("%c", (char)(fmod(encrypt[i][0], 26) + 97));

}

void decryption() {
	int i, j, k;
	
	inverse();
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 1; j++)
			for(k = 0; k < 3; k++)
				decrypt[i][j] = decrypt[i][j] + b[i][k] * encrypt[k][j];
	
	printf("\nDecrypted string is: ");
	for(i = 0; i < 3; i++)
		printf("%c", (char)(fmod(decrypt[i][0], 26) + 97));
	
	printf("\n");
}

void getKeyMessage() {
	int i, j;
	char msg[3];

	printf("Enter 3x3 matrix for key (It should be inversible):\n");
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 3; j++) {
			scanf("%f", &a[i][j]);
			c[i][j] = a[i][j];
		}
	
	printf("\nEnter a 3 letter string: ");
	scanf("%s", msg);
	
	for(i = 0; i < 3; i++)
		mes[i][0] = msg[i] - 97;
}

void inverse() {
	int i, j, k;
	float p, q;
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 3; j++) {
			if(i == j)
				b[i][j]=1;
			else
				b[i][j]=0;
		}
		
	for(k = 0; k < 3; k++) {
		for(i = 0; i < 3; i++) {
			p = c[i][k];
			q = c[k][k];
				
			for(j = 0; j < 3; j++) {
				if(i != k) {
					c[i][j] = c[i][j]*q - p*c[k][j];
					b[i][j] = b[i][j]*q - p*b[k][j];
				}
			}
		}
	}
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 3; j++)
			b[i][j] = b[i][j] / c[i][i];
	
	printf("\n\nInverse Matrix is:\n");
	for(i = 0; i < 3; i++) {
		for(j = 0; j < 3; j++)
			printf("%d ", b[i][j]);
		
		printf("\n");
	}
}

Hill Cipher Program in C++

#include<iostream>
#include<math.h>

using namespace std;

float encrypt[3][1], decrypt[3][1], a[3][3], b[3][3], mes[3][1], c[3][3];

void encryption();	//encrypts the message
void decryption();	//decrypts the message
void getKeyMessage();	//gets key and message from user
void inverse();		//finds inverse of key matrix

int main() {
	getKeyMessage();
	encryption();
	decryption();
}

void encryption() {
	int i, j, k;
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 1; j++)
			for(k = 0; k < 3; k++)
				encrypt[i][j] = encrypt[i][j] + a[i][k] * mes[k][j];
	
	cout<<"\nEncrypted string is: ";
	for(i = 0; i < 3; i++)
		cout<<(char)(fmod(encrypt[i][0], 26) + 97);
}

void decryption() {
	int i, j, k;
	
	inverse();
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 1; j++)
			for(k = 0; k < 3; k++)
				decrypt[i][j] = decrypt[i][j] + b[i][k] * encrypt[k][j];
	
	cout<<"\nDecrypted string is: ";
	for(i = 0; i < 3; i++)
		cout<<(char)(fmod(decrypt[i][0], 26) + 97);
	
	cout<<"\n";
}

void getKeyMessage() {
	int i, j;
	char msg[3];

	cout<<"Enter 3x3 matrix for key (It should be inversible):\n";
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 3; j++) {
			scanf("%f", &a[i][j]);
			c[i][j] = a[i][j];
		}
	
	cout<<"\nEnter a 3 letter string: ";
	cin>>msg;
	
	for(i = 0; i < 3; i++)
		mes[i][0] = msg[i] - 97;
}

void inverse() {
	int i, j, k;
	float p, q;
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 3; j++) {
			if(i == j)
				b[i][j]=1;
			else
				b[i][j]=0;
		}
		
	for(k = 0; k < 3; k++) {
		for(i = 0; i < 3; i++) {
			p = c[i][k];
			q = c[k][k];
				
			for(j = 0; j < 3; j++) {
				if(i != k) {
					c[i][j] = c[i][j]*q - p*c[k][j];
					b[i][j] = b[i][j]*q - p*b[k][j];
				}
			}
		}
	}
	
	for(i = 0; i < 3; i++)
		for(j = 0; j < 3; j++)
			b[i][j] = b[i][j] / c[i][i];
	
	cout<<"\n\nInverse Matrix is:\n";
	for(i = 0; i < 3; i++) {
		for(j = 0; j < 3; j++)
			cout<<b[i][j]<<" ";
		
		cout<<"\n";
	}
}

Output

Image may be NSFW.
Clik here to view.
Hill Cipher in C and C++ (Encryption and Decryption)

Comment below if you have any queries related to above program for hill cipher in C and C++.

The post Hill Cipher in C and C++ (Encryption and Decryption) appeared first on The Crazy Programmer.

Viewing all 761 articles
Browse latest View live