Wednesday, 22 February 2017

PYTHON IF...ELIF...ELSE

Q. What is if else?
 The if/else means a statement that executes a block of code if a specified condition is true and if the condition is false, another block of code can be executed.
Example Of IF...ELSE

x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
 if x < 0:
    x = 0
    print 'Negative changed to zero'
 elif x == 0:
     print 'Zero'
 elif x == 1:
     print 'Single'
 else:

     print 'More'

Python Program To Check If a Number Is Odd or Even(Using IF...ELSE)

Q. What is ELIF?
With elif statement you can check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.
It is similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.


You May Like Also :-  Python Program To swap Two Variables

people = 30
cars = 40
trucks = 15


if cars > people:
    print "We should take the cars."
elif cars < people:
    print "We should not take the cars."
else:
    print "We can't decide."

if trucks > cars:
    print "That's too many trucks."
elif trucks < cars:
    print "Maybe we could take the trucks."
else:
    print "We still can't decide."

if people > trucks:
    print "Alright, let's just take the trucks."
else:
    print "Fine, let's stay home then."

Python program to check if a number is positive, negative or zero (Using IF...ELIF...ELSE )

num = float(input("Enter a number: "))
if num > 0:
   print("Positive number")
elif num == 0:
   print("Zero")
else:
   print("Negative number")



Python Program To Check Leap Year(Using Nested IF..ELSE)

 Python program to check if the input year is a leap year or not

year = 2000

# To get year (integer input) from the user
# year = int(input("Enter a year: "))

if (year % 4) == 0:
   if (year % 100) == 0:
       if (year % 400) == 0:
           print("{0} is a leap year".format(year))
       else:
           print("{0} is not a leap year".format(year))
   else:
       print("{0} is a leap year".format(year))
else:
   print("{0} is not a leap year".format(year))


Important JavaScript Interview Questions

 JavaScript Interview Questions 
1. What is JavaScript?
Javascript is client-side as well as server facet scripting language that can be inserted into HTML pages and is understood through internet browsers. javascript is likewise an item orientated programming language

2. Which company developed JavaScript?
Netscape is the software organization who evolved javascript. 

3. What is a prompt box?
a prompt box is a container which lets in the user to go into input by way of supplying a textual content box.  label and container will be supplied to enter the textual content or wide variety.

4. What is ‘this’ keyword in JavaScript?
‘this’ keyword refers to the object from where it became called.

5. What is the difference between ViewState and SessionState?

‘ViewState’ is specific to a page in a session.

‘SessionState’ is specific to user specific data that can be accessed across all pages in the web application.

6. What is = = = operator?
= = = is referred to as-is strict equality operator which returns authentic when the 2 operands are having the identical cost with none kind conversion.

7. Explain how can you submit a form using JavaScript?
to post a form using javascript use file.shape[0].publish();

report.shape[0].post();

8. Explain how to read and write a file using JavaScript?
To put up a shape the use of javascript use document.shape[0].post();

file.shape[0].submit();


there are  approaches to read and write a report the use of javascript

using javascript extensions
using a web page and energetic x gadgets.

9. Name some of the JavaScript features.

Following are the features of JavaScript −

*  javascript is a light-weight, interpreted programming language.
*  javascript is designed for developing community-centric programs
*  javascript is complementary to and integrated with java.
*  javascript is open and go platform.

10. What are the advantages of using JavaScript?

Following are the advantages of using JavaScript −

Much less server interplay − you can validate consumer input earlier than sending the page off to the server. this saves server site visitors, because of this much less load on your server.

Instantaneous remarks to the traffic − they do not ought to watch for a page reload to see in the event that they have forgotten to go into something.

Increased interactivity − you can create interfaces that react whilst the user hovers over them with a mouse or activates them through the keyboard.

Richer interfaces − you can use javascript to include such gadgets as drag-and-drop components and sliders to present a rich interface on your site visitors.

11. Is JavaScript a case-sensitive language?

sure! javascript is a case-sensitive language. which means that language keywords, variables, function names, and any other identifiers should usually be typed with a steady capitalization of letters.

12. How can you create an array in javascript?
you could outline arrays the use of the array literal as follows −

var x = [];
var y = [1, 2, 3, 4, 5];

13. How can you convert the string of any base to an integer in JavaScript?

the parseint() characteristic is used to convert numbers among extraordinary bases. parseint() takes the string to be transformed as its first parameter, and the second one parameter is the base of the given string.

on the way to convert 4f (of base 16) to integer, the code used might be –

parseInt ("4F", 16);

14. What is the function of delete operator?
The functionality of delete operator is used to delete all variables and gadgets in a software however it can not delete variables declared with var key-word.

15. What is The difference between an alert box and a confirmation box ?

an alert box presentations best one button which is the adequate button.


but a confirmation box presentations two buttons particularly ok and cancel.

16. What are the valid scopes of a variable in JavaScript?

the scope of a variable is the region of your program wherein it's far defined. javascript variable can have best  scopes.

Global variables − a global variable has global scope which means it's miles seen everywhere in your javascript code.

local variables − a local variable will be seen only within a characteristic where it's far defined. function parameters are always local to that feature.




Tuesday, 21 February 2017

10 reasons to use MySQL

10 reasons to use MySQL

So here’s the reasons why someone would use MySQL and why we shouldn’t be making funeral plans for it just yet.

1. It’s ubiquitous

Go to any Linux or Windows based web have, and there it is. Download an open source venture and a large portion of time that is what it's associated with. In case you're in a common facilitating condition you can't simply go an introduce something else, yet you can stay with MySQL and download pretty much any open source programming and utilize it. That is favorable position, particularly for new people.

2. It’s easy to find help

If you get stuck on something, there are countless places to find your solution. There are tens of thousands of tutorials, help docs and discussions about it. Chances are the problem you’re having isn’t anything new and someone has already solved it.

3. It’s easy to learn

Basically anybody can take in the rudiments and get up and running rapidly with MySQL. In case you're building something little and straightforward it's simple, and very sympathetic. While this constructs poor programming rehearses it likewise gives individuals preparing wheels until they take in more and choose to get a genuine database.

4. MySQL is considered proven

While it may not be impeccable, it is viewed as a demonstrated innovation in the business. Merchants endeavor to have their applications and apparatuses perfect with MySQL in light of the fact that it's so every now and again utilized effectively. There are a lot of uses that utilization MySQL intelligently to take care of their issues, and they work fine and dandy.

5. Less features mean less maintenance
you don’t want to rent a group of licensed dbas to run a mysql database. an normal programmer can study enough to keep their database servers for most programs. there are numerous features enterprise database providers provide that you can’t find in mysql, but you furthermore mght don’t want. maximum of the time the ones extra functions imply extra points of failure, and greater training needed to keep the server running, that is wasteful in case you aren’t actively using stated capabilities anyway. mysql may be very much “set it and neglect it” in many programs.

6. Total Cost of Ownership (TCO)

what number of startups available need to fork out hundreds of bucks for a microsoft or oracle answer? they’re operating on a shoestring so a loose database solution is a no brainer. mysql may be installed on as many servers as you need and it doesn’t require tons in the way of hardware. and as i cited earlier than the hard work costs for keeping it are a long way lower. even big set up agencies love saving money, and mysql saves money.

If you don’t need the extra features you aren’t going to pay through the nose for it, pure and simple.

7. MySQL is scalable

You and your brother in law decide to start a company in your garage. You choose MySQL based on price and build your application. Fast forward a year from now and things are growing good. You’ve added a couple more servers and things are fine. Another year goes by and you have some breakthrough and your business is 10 times larger overnight. You can use that money to build as much of an infrastructure as you need, and rather quickly. MySQL can handle everything from a megabyte of data to terabytes just fine. With good education about the system you can scale it up.

8. Native support for the new stuff
in case you really need to be hip and cutting facet you wouldn’t don't forget using that stale and uncool mysql proper? properly surely you might considering how properly it interfaces with such things as ruby and python. it’s properly supported out of the field, and ready for the contemporary and finest technologies coming out, in addition to fantastic aid for Hypertext Preprocessor.

9. Great transactional support

whilst mysql might not be the finest for statistics warehousing it’s tough to argue it’s horrific as a transactional database. the net itself is distinctly transactional and mysql meets that need well. it capabilities acid (atomic, steady, remoted, durable) aid, allotted transactions and server enforced referential integrity assessments on transactions.

10. RDBMS support for smaller businesses isn’t bad

for small to medium sized groups the reporting and evaluation capability is pretty enough. it can use a whole lot of improvement but it works great for smaller applications. the same type of businesses that advantage from value financial savings are the same ones that won’t probable need complicated analysis and in depth bi reporting provided in different databases. in case you’re using it to run your organisation blog or a few purchasing carts do you actually need a lot more than mysql offers? possibly no longer.

when you’re equipped to lose the schooling wheels

ok so if you’re a growing enterprise or your weblog receives huge you'll probable need to shake mysql sooner or later. there are many cases in which you don’t need to use it:

if you have large statistics
enterprise intelligence is more critical than value
you have got a competent and especially technical staff
records accuracy is extraordinarily crucial
your infrastructure is dependent on microsoft or java
you're a small enterprise but have someone who can run postgresql (giggle)
i've particular the motives you need to recall mysql on your answer, and why many people use it. if your targets are to drop in an smooth solution and save some cash it’s excellent. however what about the exceptions? i’ll be writing an editorial about that quickly, because there are masses of motives not to apply it as properly.

for my part i pick postgresql over mysql for a drop in substitute on linux based systems. it’s a ways advanced in many ways, and some thing you need to do not forget in case you’re capable of. in my opinion if i were to begin a brand new business or had a linux primarily based surroundings and become in the making plans section i'd choose postgresql from the start. however it’s now not usually the quality option for most people.

end

i'm hoping this helps shed some light on the truth that mysql is ubiquitous and present for a purpose. it’s not the best solution obtainable, but it’s the satisfactory answer for lots people. as i stated individually i decide on postgresql or ms-square a ways above mysql but i apprehend the reasoning behind choosing mysql and i wish you’ll remember that too.

have to you use mysql? the answer relies upon on what you’re using it for, and what your dreams are. it’s no longer as easy as some are trying to make it.

Why Should I Learn Java

Novice Friendliness 

By and large, Java was intended to be moderately fledgling benevolent in that it expect the software engineer is not that brilliant or watchful, so developers will be less inclined to shoot themselves in the foot when coding Java applications.

Generally Simple to Use 
Why Should I Learn Java
Why Should I Learn Java

Java is an abnormal state dialect, which implies Java abstracts away (i.e. handles for you) the vast majority of the mind-boggling points of interest of the machine (PC, for example, memory administration, and so forth. Therefore, you can concentrate on programming as opposed to agonizing over the little subtle elements many consider both dull and troublesome.

Less Rewarding from the Start 

Java is exceptionally unshakable and verbose, which implies you have to compose a great deal of code attempting to persuade the dialect to fabricate some element. Accordingly, you may need to invest a ton of energy coding before you can get a working application. This might be demotivating for coding amateurs.

Versatility 

Less demanding to Maintain 

Java is a statically-written dialect, which implies your code should be checked for mistakes before it can be incorporated with an application. This implies blunders will be simpler to find. Moreover, since statically-wrote dialects are additionally more strict with the meanings of things, you will have less bizarre and sudden mistakes, which implies your codebase will be less demanding to keep up as it develops in size and many-sided quality.

Quick 

As a statically wrote dialect, Java is speedier than powerfully written dialects since things are all the more unmistakably characterized. In this manner, when the application is running, your machine's assets won't be squandered on checking the meaning of something in your code.

Enhanced Performance 

Present day Java projects are currently significantly more performant on account of develop JIT (without a moment to spare) compilers and enhanced JVMs, as execution can be improved continuously to help a Java program run quicker. This is exceptionally useful as your application becomes bigger or necessities to deal with more procedures.

Group 

Group size is vital on the grounds that the bigger a programming dialect group is, the more support you'd probably get. As you venture into the programming scene, you'll soon see how imperative support is, as the engineer group is about giving and accepting assistance. Also, the bigger a group, the more individuals will assemble helpful apparatuses to make improvement in that specific dialect less demanding.

Starting at now, there are more than 600 striking programming dialects around the world. Thus, in view of that specific situation, how about we dive into the subtle elements of the Java people group estimate.

second Largest StackOverflow Community 

StackOverflow is a programming Q&A site you will probably get to be distinctly close with as a coding learner. Java has a tremendous group for both back-end web advancement and Android improvement.

fourth Largest Meetup Community 

At meetups, you can for the most part system and gain from kindred engineers. Meetups frequently offer mentorship to the individuals who need it also. There are more than 1.4k Java Meetup bunches, totaling more than 580k individuals around the world. Regarding programming dialects, Java has the fourth biggest meetup group.

second Most-labeled Language at GitHub

The more valuable ventures there are, the more probable somebody has officially assembled a capacity you require and fabricated it well, which will extraordinarily accelerate your advancement procedure. GitHub has more than 1.5 million Java ventures, more than 1.1k of which have been featured by more than 500 individuals, making it second place regarding valuable undertakings.,

All in all, the Java biological community is very enormous and develop, so there are a lot of good apparatuses and libraries that will extraordinarily facilitate the way toward creating Java applications and learning Java as a rule.

Vocation Opportunities 

Quickfacts 

Pay data from gooroo.io 

Java is the third Most Demanded Skill on Angel list. Numerous tech goliaths, for example, Google or Amazon additionally utilize Java to build up the back end of their sites, and on the grounds that Java has entirely great execution, a considerable measure of new businesses who achieve the scaling point would coordinate their applications with Java to power includes that need great execution.

As indicated by Indeed.com, Java designers are sought after contrasted with different software engineers:

Future 

As indicated by the TIOBE Index, Java is the Most Popular Language in 2015

Java has a somewhat moderate redesign cycle regarding new forms to guarantee in reverse similarity, and ventures are ease back to embrace changes too, so this works out fine for both sides. Prophet claims Java so the dialect is effectively chipped away at to remain significant, and bugs are settled moderately rapidly.

In spite of the fact that Java has been scrutinized ordinarily and numerous dialects have attempted to supplant it as a superior Java, with the arrival of a superior (Java 8) amid March eighteenth, 2014, Java will obviously keep on staying important and will go solid, particularly since it as of now has many develop apparatuses and libraries that won't be anything but difficult to supplant.

Enthusiasm learning Java developed by 22.4% in 2015 

A writing computer programs dialect's capacity to remain pertinent and survive additionally relies on upon whether the dialect is getting fresh recruits, so plainly Java will keep on dominating in the years to come.

You May Also Like :- Java Program To Print Pattern
                                    How To Reverse An Araay In Java

Python Program To Swap Two Variables

Python program to swap two variables

To swap two numbers in python, you can ask from user to enter the value of two numbers or you can manually put the values of two numbers, after that you can swap those two numbers using the third variable. Swapping of two numbers means placing the value of the first variable to the second variable and the value of the second variable to the first variable just by using another temporary variable. Or you can do it without using any third variable or temporary variable.
Python Program To Swap Two Variables
Python Program To Swap Two Variables

Following python program will ask the user to enter the value of two numbers to swap both the number.

 Python program to swap two variables 

while True:
print("Enter 'x' for exit.")
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
if num1 == 'x':
break
else:
number1 = int(num1)
number2 = int(num2)
swap = number1
number1 = number2
number2 = swap
print("Value of First and Second number after swapping:")
print("First Number =",number1,"\nSecond Number=",number2,"\n")

Python Program To Swap Two Variables(Using Temporary Variables)


x = 5
y = 10


temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Python Program To Swap Two Variables Without Using Third Variables


  Python program to swap two variables Addition And Subtractions Method

x = 5
y = 10

x = x + y
y = x - y
x = x - y

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))


 Python program to swap two variables Using Xor Swap Method

x = 5
y = 10

x = x ^ y
y = x ^ y
x = x ^ y

print('The value of x after swapping: {}'.format(x))

print('The value of y after swapping: {}'.format(y))


 Python program to swap two variables Using Multiplication and Division Method

x = 5
y = 10


x = x * y
y = x / y
x = x / y
print('The value of x after swapping: {}'.format(x))

print('The value of y after swapping: {}'.format(y))

You May Also like  Basic Python Program For Practice

Sunday, 19 February 2017

Java Program To Print Pattern (Important Pattern Program)

Pattern Program In Java:    Java programs to print patterns are one of the frequently asked interview programs mostly for freshers or students. Because they t
est the candidate’s logical ability as well as coding skills which are ‘must have skills’ for any software engineer. In this post, we have collected some of the different number pattern programs in java and have tried to solve them. 
Java Program To Print Pattern
Java Program To Print Pattern
Java Program To Print Pattern 
Pattern -1

5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1



public class series {
public static void main (String args[]){

for(int i=1;i<=5;i++){
for(int j=5;j>=i;j--){
System.out.print(j);
}
System.out.println();
}
for(int i=1;i<5;i++){
for(int j=5;j>4-i;j--){
System.out.print(j);
}
System.out.println();
}
}
}

Output

5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
Java Program To print This pattern

Pattern-2
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1


public class series {
public static void main (String args[]){
for(int i=1;i<=5;i++){
for(int j=i;j>=1;j--){
System.out.print(j);
}
System.out.println();
}
}

}

Output 
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1


Java Program To Print This Pattern
Pattern-3
-------- 1
------2 1 2
--- 3 2 1 2 3
--4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
-- 4 3 2 1 2 3 4 
- --- 3 2 1 2 3
- - ---- 2 1 2
-- -- ---- 1

public class series {
    public static void main ( String arg[] ){
            int num = 5;
            //upper triangle
            for(int i=1;i<=num;i++){
                for(int j=1;j < num-(i-1);j++){
                    System.out.print("-");
                }
                for(int k=i;k>=1;k--){
                    System.out.print(k);
                }
                for(int k1=2;k1<=i;k1++){
                        System.out.print(k1);
                    }
                System.out.println();
            }
            //lower triangle    
            for(int i=1;i<=num-1;i++){
                for(int j=i;j>=1;j--){
                    System.out.print("-");
                }
                for(int k=num-i;k>=1;k--){
                    System.out.print(k);
                    
                }
                for(int k1=2;k1<=num-i;k1++){
                        System.out.print(k1);
                    }
                System.out.println();     
            }
    }
}
Output

-------- 1
------2 1 2
--- 3 2 1 2 3
--4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
-- 4 3 2 1 2 3 4 
- --- 3 2 1 2 3
- - ---- 2 1 2
-- -- ---- 1

Java Program To Print This Pattern

Pattern-4

1
121
12321
1234321
123454321
1234321
12321
121
1

class series {
    public static void main(String Args[]) {
        int max = 5;    //max no. in series
        //Upper Triangle
        for(int i=1;i<=max;i++){
            for(int j=1;j<=i;j++){
                System.out.print(j);
            }
            for(int k=i-1;k>=1;k--){
                System.out.print(k);
            }
            System.out.println();
        }
        //Lower Triangle
        for(int i=1;i<=max-1;i++){
            for(int j=1;j<=max-i;j++){
                System.out.print(j);
            }
            for(int k=max-i-1;k>=1;k--){
                System.out.print(k);
            }
            System.out.println();
        }
    }

}

Output
1
121
12321
1234321
123454321
1234321
12321
121
1


Java Program To Print This Pattern
Pattern-5
Pattern-5(1)
T
TE
TEA
TEAC
TEACH
TEACHE
TEACHER

Pattern-5(2)

TEACHER
--EACHER
----ACHER 
------CHER
---------HER
-----------ER
-------------R 

Code For Pattern 1:
class series{
    public static void main(String args[]){
        String txt = "TEACHER";
        for(int i=1;i<=txt.length();i++){
            System.out.println(txt.substring(0, i));
        }
    }
}

Output
T
TE
TEA
TEAC
TEACH
TEACHE
TEACHER


Code for Pattern 2:
class series{
    public static void main(String args[]){
        String txt = "TEACHER";
        for(int i=0;i<txt.length();i++){
            for(int s=i;s>0;s--)    System.out.print("-");
            System.out.println(txt.substring(i, txt.length()));
        }
    }
}

Output
TEACHER
--EACHER
----ACHER 
------CHER
---------HER
-----------ER
-------------R 

Java Program to Print This pattern

Pattern-6
A
A B A 
A B C B A
A B C D C B A
A B C B A
A B A
A

public class series {
    public static void main ( String arg[] ){
        String txt = "ABCD";
        for(int i=0;i<txt.length();i++){
            for(int s=1;s<txt.length()-i;s++) System.out.print(" ");
            for(int j=0,k=i;j<=i*2;j++){
                if(j<=i) System.out.print(txt.substring(j, j+1)+" ");
                else{
                    System.out.print(txt.substring(k-1, k)+" ");
                    k--;
                }
            }
            System.out.println();
        }
        for(int i=0;i<txt.length();i++){
            for(int s=-1;s<i*2;s++) System.out.print(" ");
            for(int j=txt.length()-i-1,n=0;j>0;j--,n++)
                System.out.print(txt.substring(n, n+1)+" ");
            for(int j=txt.length()-i-2;j>0;j--)
                System.out.print(txt.substring(j-1, j)+" ");
            System.out.println();
        }
    }
}

Output
A
A B A 
A B C B A
A B C D C B A
A B C B A
A B A
A


Java Program To Print This Pattern

Pattern-7

999999999999999999
88888888  88888888
7777777    7777777
666666      666666
55555        55555
4444          4444
Java Program To Print Pattern
Java Program To Print Pattern
333            333
22              22
1                1

public class CurveOutput {

    public static void main(String args[]) {
        int startNumber = 9;

        for (int currentNum = startNumber; currentNum >= 0; currentNum--) {
            StringBuilder line = new StringBuilder();
            for (int i = 0; i < currentNum; i++) {
                line.append(currentNum);
            }
            for (int i = 0; i < startNumber - currentNum; i++) {
                line.append(" ");
            }
            System.out.println(line.toString() + line.reverse().toString());
        }
    }
}

Output

999999999999999999
88888888  88888888
7777777    7777777
666666      666666
55555        55555
4444          4444
333            333
22              22
1                1

You May Also Like :- How To Reverse An Array In Java

Saturday, 18 February 2017

Structures In C With Examples

Q. What is a Structure?
The structure is a data type defined by a user it allows to combine data items of different kinds. Structure helps to construct a complex data type in a more meaningful way. a structure is somewhat similar to an Array. The only difference between an array and a structure is that array is used to store a collection of similar data types while a structure can store a collection of any type of data.
In this post we will talk about:

1. How to define a structure?
2. Short Example of Structure
3. C program For  Adding Two Numbers Using Structure
4.  Passing Structure To Function In C By Value

Q. How to define a structure?
 The struct statement used to define a Structure. It defines a new data type, with more than one member.

struct structure_name // Your Structure name
{
    Statements definitions;
 
};

Short Example Of Structure

struct song {
   char  title[50];
   char  singer[50];
   int  rating[10];

}
Here the struct song declares a structure to hold the details of a song which consists of three data fields, namely title, singer and mood. These fields are called structure elements or members. Each member can have a different data type, like in this case, the title is of char type rating is of int type etc. song is the name of the structure and is called structure tag.

C program For  Adding Two Numbers Using Structure


#include<stdio.h>
#include<conio.h>

struct sum
{
int a;
int b;
};

void main()
{
int sum1;
struct sum s;
clrscr();

printf(“Enter two numbers:”);
scanf(“%d%d”,&s.a,&s.b);

sum1=s.a+s.b;
printf(“nSum=%d”,sum1);
getch();
}


Passing Structure To Function In C By Value

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

struct student
{
            int id;
            char name[20];
            float percentage;
};

void func(struct student record);

int main()
{
            struct student record;

            record.id=1;
            strcpy(record.name, "Prince");
            record.percentage = 86.5;

            func(record);
            return 0;
}

void func(struct student record)
{
            printf(" Id is: %d \n", record.id);
            printf(" Name is: %s \n", record.name);
            printf(" Percentage is: %f \n", record.percentage);
}

Output
Id is: 1
Name is: Prince

Percentage is: 86.500000
If you need any suggestion or help regarding structures program in c comment below. and if you like this post please do a share.

In this post we talked about:

1. How to define a structure?
2. Short Example of Structure
3. C program For  Adding Two Numbers Using Structure
4.  Passing Structure To Function In C By Value

Friday, 10 February 2017

How To Find Armstrong Number In C

 Armstrong number is a number which is equal to a Sum of digits raise to the power total number of digits in the number.

Here Is The Code For Armstrong Number.

How to find Armstrong number in c using for loop


#include<stdio.h>
int main(){
    int num,r,sum=0,temp;

    printf("Enter a number to find Armstrong Number: ");
    scanf("%d",&num);

    for(temp=num;num!=0;num=num/10){
         r=num%10;
         sum=sum+(r*r*r);
    }
    if(sum==temp)
         printf("%d is an Armstrong Number",temp);
    else
         printf("%d is not an Armstrong Number",temp);

    return 0;
}

How To Find Armstrong Number Of n digits

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

int main()
{
    int number, originalNumber, remainder, result = 0, n = 0 ;

    printf("Enter an integer: ");
    scanf("%d", &number);

     originalNumber = number;

    while (originalNumber != 0)
    {
        originalNumber /= 10;
        ++n;
    }

    originalNumber = number;

    while (originalNumber != 0)
    {
        remainder = originalNumber%10;
        result += pow(remainder, n);
        originalNumber /= 10;
    }

    if(result == number)
        printf("%d is an Armstrong number.", number);
    else
        printf("%d is not an Armstrong number.", number);

    return 0;
}


How To Find Armstrong Numbers From 1 To 500

#include<stdio.h>
int main(){
    int num,r,sum,temp;

//Armstrong Number In C

    for(num=1;num<=500;num++){
         temp=num;
         sum = 0;

         while(temp!=0){
             r=temp%10;
             temp=temp/10;
             sum=sum+(r*r*r);
         }
         if(sum==num)
             printf("%d ",num); // This line prints Armstrong Number
    }

    return 0;
}


Output:-  1     153     370    371    407

How To Find Armstrong Number Of Three Digits

#include <stdio.h>
int main()
{
    int number, originalNumber, remainder, result = 0;

    printf("Enter a three digit integer to check Armstrong Number: ");
    scanf("%d", &number);
//Armstrong Number Of Three Digits
    originalNumber = number;

    while (originalNumber != 0)
    {
        remainder = originalNumber%10;
        result += remainder*remainder*remainder;
        originalNumber /= 10;
    }

    if(result == number)
        printf("%d is an Armstrong number.",number);
    else
        printf("%d is not an Armstrong number.",number);

    return 0;

}





How To Find Armstrong Number Using Function
#include <stdio.h>

int check_armstrong(long long);
long long power(int, int);

int main () {
   long long n;

   printf("Input a number\n");
   scanf("%lld", &n);

   if (check_armstrong(n) == 1)
      printf("%lld is an Armstrong Number.\n", n);
   else
      printf("%lld is not an Armstrong Number.\n", n);

   return 0;
}

int check_armstrong(long long n) {
   long long sum = 0, temp;
   int remainder, digits = 0;

   temp = n;

   while (temp != 0) {
      digits++;
      temp = temp/10;
   }

   temp = n;

   while (temp != 0) {
      remainder = temp%10;
      sum = sum + power(remainder, digits);
      temp = temp/10;
   }

   if (n == sum)
      return 1;
   else
      return 0;
}

long long power(int n, int r) {
   int c;
   long long p = 1;

   for (c = 1; c <= r; c++)
      p = p*n;

   return p;

}



Thursday, 2 February 2017

A Simple Program Using Array

A Simple Program Using Array 
Let us try to write a program to find average marks obtained by a class of 30 students in a test.

main( )

{
int avg, sum = 0 ; int i ;
int marks[30] ; /* array declaration */

for ( i = 0 ; i <= 29 ; i++ )

{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ; /* store data in array */
}

for ( i = 0 ; i <= 29 ; i++ )

sum = sum + marks[i] ; /* read data from an array*/

avg = sum / 30 ;

printf ( "\nAverage marks = %d", avg ) ;
}

There is a lot of new material in this program, so let us take it apart slowly.

Array Declaration

To begin with, like other variables an array needs to be declared so that the compiler will know what kind of an array and how large an array we want. In our program we have done this with the statement:

int marks[30] ;

Here, int specifies the type of the variable, just as it does with ordinary variables and the word marks specifies the name of the variable. The [30] however is new. The number 30 tells how many elements of the type int will be in our array. This number is often called the ‘dimension’ of the array. The bracket ( [ ] ) tells the compiler that we are dealing with an array.

Accessing Elements of an Array

Once an array is declared, let us see how individual elements in the array can be referred. This is done with subscript, the number in the brackets following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. Thus, marks[2] is not the second element of the array, but the third. In our program we are using the variable i as a subscript to refer to various elements of the array. This variable can take different values and hence can refer to the different elements in the array in turn. This ability to use variables as subscripts is what makes arrays so useful.

 Entering Data into an Array

Here is the section of code that places data into an array:

for ( i = 0 ; i <= 29 ; i++ )

{

printf ( "\nEnter marks " ) ; scanf ( "%d", &marks[i] ) ;

}

The for loop causes the process of asking for and receiving a student’s marks from the user to be repeated 30 times. The first time through the loop, i has a value 0, so the scanf( ) function will cause the value typed to be stored in the array element marks[0], the first element of the array. This process will be repeated until i

becomes 29. This is last time through the loop, which is a good thing, because there is no array element like marks[30].

In scanf( ) function, we have used the “address of” operator (&) on the element marks[i] of the array, just as we have used it earlier on other variables (&rate, for example). In so doing, we are passing the address of this particular array element to the scanf( ) function, rather than its value; which is what scanf( ) requires.

Reading Data from an Array

The balance of the program reads the data back out of the array and uses it to calculate the average. The for loop is much the same, but now the body of the loop causes each student’s marks to be added to a running total stored in a variable called sum. When all the marks have been added up, the result is divided by 30, the number of students, to get the average.

for ( i = 0 ; i <= 29 ; i++ ) sum = sum + marks[i] ;

avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;

To fix our ideas, let us revise whatever we have learnt about arrays:

            An array is a collection of similar elements.

            The first element in the array is numbered 0, so the last element is 1 less than the size of the array.

            An array is also known as a subscripted variable.
            Before using an array its type and dimension must be declared.
            However big an array its elements are always stored in contiguous memory locations. This is a very important point which we would discuss in more detail later on.