Trending December 2023 # C# Stack With Push & Pop Examples # Suggested January 2024 # Top 13 Popular

You are reading the article C# Stack With Push & Pop Examples updated in December 2023 on the website Cattuongwedding.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 C# Stack With Push & Pop Examples

What is Stack in C#?

The stack is a special case collection which represents a last in first out (LIFO) concept. To first understand LIFO, let’s take an example. Imagine a stack of books with each book kept on top of each other.

The concept of last in first out in the case of books means that only the top most book can be removed from the stack of books. It is not possible to remove a book from between, because then that would disturb the setting of the stack.

Hence in C#, the stack also works in the same way. Elements are added to the stack, one on the top of each other. The process of adding an element to the stack is called a push operation. To remove an element from a stack, you can also remove the top most element of the stack. This operation is known as pop.

Let’s look at the operations available for the Stack collection in more detail.

Declaration of the stack

A stack is created with the help of the Stack Data type. The keyword “new” is used to create an object of a Stack. The object is then assigned to the variable st.

Stack st = new Stack() Adding elements to the stack

The push method is used to add an element onto the stack. The general syntax of the statement is given below.

Stack.push(element) Removing elements from the stack

The pop method is used to remove an element from the stack. The pop operation will return the topmost element of the stack. The general syntax of the statement is given below

Stack.pop() Count

This property is used to get the number of items in the Stack. Below is the general syntax of this statement.

Stack.Count Contains

This method is used to see if an element is present in the Stack. Below is the general syntax of this statement. The statement will return true if the element exists, else it will return the value false.

Stack.Contains(element)

Now let’s see this working at a code level. All of the below-mentioned code will be written to our Console application. The code will be written to our chúng tôi file.

In the below program, we will write the code to see how we can use the above-mentioned methods.

Example 1: Stack.Push() Method

In this example, we will see

How a stack gets created.

How to display the elements of the stack, and use the Count and Contain methods.

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoApplication { class Program { static void Main(string[] args) { Stack st = new Stack(); st.Push(1); st.Push(2); st.Push(3); foreach (Object obj in st) { Console.WriteLine(obj); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("The number of elements in the stack " +st.Count); Console.WriteLine("Does the stack contain the elements 3 "+st.Contains(3)); Console.ReadKey(); } } }

Code Explanation:-

The first step is used to declare the Stack. Here we are declaring “st” as a variable to hold the elements of our stack.

Next, we add 3 elements to our stack. Each element is added via the Push method.

Now since the stack elements cannot be accessed via the index position like the array list, we need to use a different approach to display the elements of the stack. The Object (obj) is a temporary variable, which is declared for holding each element of the stack. We then use the foreach statement to go through each element of the stack. For each stack element, the value is assigned to the obj variable. We then use the Console.Writeline command to display the value to the console.

We are using the Count property (st.count) to get the number of items in the stack. This property will return a number. We then display this value to the console.

We then use the Contains method to see if the value of 3 is present in our stack. This will return either a true or false value. We then display this return value to the console.

If the above code is entered properly and the program is run the following output will be displayed.

Output:

From the output, we can see that the elements of the stack are displayed. Also, the value of True is displayed to say that the value of 3 is defined on the stack.

Note: You have noticed that the last element pushed onto the stack is displayed first. This is the topmost element of the stack. The count of stack elements is also shown in the output.

Example 2: Stack.Pop() Method

Now let’s look at the “remove” functionality. We will see the code required to remove the topmost element from the stack.

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoApplication { class Program { static void Main(string[] args) { Stack st = new Stack(); st.Push(1); st.Push(2); st.Push(3); st.Pop(); foreach (Object obj in st) { Console.WriteLine(obj); } Console.ReadKey(); } } }

Code Explanation:-

Here we just issue the pop method which is used to remove an element from the stack.

If the above code is entered properly and the program is run, the following output will be displayed.

Output:

We can see that the element 3 was removed from the stack.

Summary

A Stack is based on the last in first out concept. The operation of adding an element to the stack is called the push operation. The operation of removing an element to the stack is called the pop operation.

You're reading C# Stack With Push & Pop Examples

How Haskell Stack Works With Examples?

Definition of Haskell Stack

In Haskell we have stack data structure which is also used to store the element inside it. Also to use the stack we have to include libraries into the application it is not present in Haskell. In this section, we will use Data. Stack library, also it provide us so many functions which is used to perform different operations in element present inside it. In Stack data structure we add and delete the element at the top of the stack only, it works in the last in first out manner. In the coming section of the tutorial, we will see the internal working of the stack in detail which will help us to get a clear idea of how to use this while programming in Haskell and also its implementation in detail to get start with.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

stackNew:: Stack a

As you can see in the above line of syntax we are creating a simple stack by using the keyword ‘stack’ but to implement this we have to use the Data. Stack library into our code. Let’s take a sample piece of syntax for better understanding see below;

e.g. :

As you can see in the above line of syntax we are trying to use one of the methods from the Data. Stack library in Haskell. Without this library, it will not work in code. In the coming section of the tutorial, we will see the internal working of the stack in detail and how it functions internally with different types of functions available inside the Data. Stack library.

How Haskell stack works?

As we already know the stack is a data structure available in Haskell which is used to store the elements inside it. This stack works in the same way like any other programming language, but it mainly has two operations which are very important to understand the stack working in detail. In this section, we will see the flow of the stack in Haskell in detail also with the flow chart diagram with all the steps in detail for beginners to understand it better. First, take a look at the flow chart see below;

1) Stack works in the LIFO manner which means last in first out order. This approach suggests or indicted that the element which has entered first will be the last to come out or vice versa in general.

2) In Stack we always remove or add the elements from the one end only. that means this satisfies the LIFO completely here.

3) In the stack we generally use the push and pop method to add r delete the element from the stack.

4) If we have used to push method that ends it will add a new element to the stack.

5) If we use the pop method then it will remove the first element or the available first element from the given stack.

6) After all the operations being performed it will exit.

Now we will see some of the methods which are available inside the Data. Stack package which we can use to perform some operations on the stack, let’s take a closer look for better understanding see below;

1) stackPush: This is the function available inside the Data. Stack we have to have this package into the code.

e.g. :

As you can see it is the official documentation of the stack push declaration given by Haskell.

2) stackNew: This is the function available inside the Data. Stack we have to have this package into the code. Basically, this function is used to create an empty stack. Let’s take a closer look at the syntax for this function given by the Haskell documentation see below;

e.g. :

stack new :: Stack a

As you can see it is the official documentation of the stack push declaration given by Haskell.

e.g. :

As you can see it is the official documentation of the stack push declaration given by Haskell.

4) stackIsEmpty: This is the function available inside the Data. Stack we have to have this package into the code.

e.g. :

As you can see it is the official documentation of stackPush declaration given by Haskell.

5) stackSize: This is the function available inside the Data. Stack we have to have this package into the code. Basically, this function is used to check the size of the stack how many elements present inside it. Let’s take a closer look at the syntax for this function given by the Haskell documentation see below;

e.g. :

As you can see it is the official documentation of stackPush declaration given by Haskell.

Now we can see one example of how it works in actuality see below;

stack = [2, 3, 4, 5 ]

Suppose we have this stack created with some numbers inserted inside it. So let’s suppose we have inserted 2 then it will be the last to remove because it works in the LIFO manner. after that, we have inserted 3 then if we want to remove them it will remove 3 first then the first inserted element.

Conclusion

By the use of stack, we can store our elements inside it, also easy to use and handle in Haskell. But it is not presented in Haskell directly we have to include the Data. Stack library for this to work otherwise it will not work. These are very easy to use and handle also readable by the developers as well.

Recommended Articles

We hope that this EDUCBA information on “Haskell Stack” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

To The Moon With C

Before President Kennedy promised America the Moon, NASA was already planning its manned lunar landing mission. What the spacecraft would look like and what rocket would launch it were major questions without obvious answers, but for the engineers at NASA’s Langley Research Centre, rendezvous — having two spacecraft meet and connect in space — was expected to be a key maneuver. The only unknown was whether the rendezvous would happen in Earth or lunar orbit, though in 1961 the former was the preferred method. Earth Orbit Rendezvous is the method John Bird sketched out in 1961 with the caption “To the Moon with C-1s or Bust.” Here’s what this mission would have looked like.

John Bird.

R_1967-L-03303 002

The first missions to the Moon were designed with one central assumption: that the entire spacecraft would land on the Moon, launch from its surface, then return to Earth. This meant, by default, that the spacecraft would be huge and heavy. It would have to carry all the fuel for the multistage mission and provisions to set up a launch site on the Moon without the help of specially trained ground crews.

Following this model, early estimates said the spacecraft could be as large as the Atlas rocket, the nearly 100-foot launch vehicle that sent the last four Mercury missions into orbit. To launch a spacecraft that big directly to the Moon required a massive rocket like Nova, the never-built rocket with eight engines in its first stage, three more than the Saturn V eventually had.

The alternative mission had astronauts assemble the same spacecraft in Earth orbit, a mission that required complicated rendezvous maneuvers but took a simpler path to orbit. Because each piece is lighter than the whole spacecraft, NASA could launch the mission on multiple smaller rockets. This is the mission, properly called an Earth Orbit rendezvous mission, that John Bird sketched out.

John Bird was an engineer at Langley, and in the early 1960s he worked on designs for a dedicated lunar landing vehicle as part of the centre’s studies into a potential Lunar Orbit Rendezvous mission (the mission profile eventually adopted by Apollo). Among Bird’s areas of expertise was the intricate business of assembling a spacecraft in Earth orbit. He became enough of an expert in the subject to be the voice of Earth orbital rendezvous maneuvers during meeting and presentations.

Bird’s sketch shows an Earth Orbit Rendezvous spacecraft configuration wherein the lunar spacecraft is assembled using ten C-1 rockets, the rocket that eventually became the Saturn I. According to this plan, NASA would have needed ten C-1s to launch this mission.

Bird’s “To the Moon or Bust” Sketch

Not only would it have been a challenge to launch all ten C-1s in quick enough succession to keep the mission running on schedule, it would have been a real feat for a crew to undertake all the rendezvous maneuvers to get every piece lined up in the right spot and docked. And all that before going to the Moon for a landing mission! Still, launching multiple rockets was preferred method for a lot of NASA centers. It forced development of rendezvous capability and promised jobs for the men and women who built the rockets.

“To the Moon with C-1s or Bust” was evidently the theme of the day at Langley on May 22, 1961, the day John Bird drew this sketch. These hand drawn concepts for missions are such a fascinating look into futures that didn’t materialize that they’re well worth sharing.

_Source, including Bird’s drawing: The Apollo Spacecraft Chronology volume 1 (Ivan Ertel and Mary Louise Morse). _

How To Do A Push

Push-ups are a strength-building exercise that works on the triceps, pectoral muscles and shoulders. If they are done correctly, they can also strengthen the lower back and core by pulling in the abdominal muscles. Doing push-ups may sound easy as they can be done virtually anywhere and don’t require any equipment. All you have to do is lower your body to the floor and push back up again. However, you need to do it correctly. May it be a traditional or a modified version; push-ups are an important part of strength training workouts like CrossFit, circuit training or high-intensity interval training (HIIT).

Doing push-ups every day can be beneficial for following a consistent exercise routine. In this article, we will explore how to include push-ups in your exercise routine and the scientifically proven health benefits of doing push-ups regularly.

How to Do a Push-up Correctly?

Push-ups are a full-body workout which if done correctly can strengthen the muscles of the arms, chest, abdomen, quadriceps and back. You need to be careful while doing push-ups and if you are a beginner, you may start with a modified push-up like box push-ups, knee push-ups or standing push-ups which are done against a wall. Beginners may have to modify push-ups for months or years before they can progress to a standard push-up. You should always consult your doctor before attempting push-ups if you have any health conditions that may aggravate due to push-ups.

The step-by-step instructions for the correct form for modified push-ups and traditional push-ups are given below −

Modified Box Push-ups

Modified push-ups groom your body for traditional push-ups. Box push-ups are one of the types of modified push-ups which can be done as follows −

You can take a sturdy box or stack of risers and place your hand shoulder-width apart on the box.

Now, straighten your legs out towards the back side and keep your feet at a comfortable distance apart. Ensure that the body is in a straight line from head to heels. Make sure that your core is engaged and the head is in a neutral position.

Now, bend your elbows slowly to form a 45-degree angle with your torso and lower the chest towards the box. Try to go as far as you can without changing your body form.

Hold that position for a few seconds and rise back up to the starting position.

Modified Knee Push-ups

Knee push-ups are another form of modified push-ups which you can incorporate into an exercise routine.

Begin by standing on all fours on the ground and move your body into a modified plank position. Now, you can wider your hands slightly than your shoulders and knees on the ground. Your body should be in a straight line from head to knees and your head should be in a neutral position.

Now, keep your knees on the floor and make sure that you don’t cross your feet.

Bend your elbows slowly to form a 45-degree angle with the torso and lower your chest towards the floor. Ensure that your back is straight. Lower your body so that the chest can touch the floor. You can go down as much as possible without changing the body position.

Stay in the position for some time and rise back up to the starting position.

How to Do a Traditional Push-up?

Once your body is accustomed to modified push-ups, you can go for traditional push-ups.

Lower your body to start in an all-fours position and keep your hands wider than your shoulders and knees on the ground. You should keep your head in a neutral position.

Now, straighten your legs out and back. You may do it one at a time. Keep your feet at a comfortable distance apart so that you are in a high plank position. Your body must be in a straight line parallel to the ground from the top of your head to the heels. Your body will have more stability if your feet are positioned wider on the ground.

Now, slowly bend your elbows backwards and make a 45-degree angle with your torso. You have to lower your chest till it almost touches the floor. You need to keep your core muscles tight and your back should be as flat as possible.

Pause in this position for a moment and then push your body back up into a high- plank position. Maintain a flat back and engage your core, front deltoids, triceps, chest and forearms for maximum benefit from a traditional push-up.

Health Benefits of Push-ups

Doing push-ups regularly can have many health benefits. However, you should avoid overdoing them to avoid major injuries. The health benefits of push-ups, if done correctly and consistently, are as follows −

Strengthen multiple muscle groups − Push-ups engage multiple muscle groups like the chest, shoulders, arms, back, core and hips. If push-ups are done correctly, they can strengthen your body muscles and increase muscle endurance.

Upper body strength − Push-up is an effective way of strengthening and toning the upper body muscles. These muscles are used daily for many activities like picking or pushing things. Upper body strength can improve functional fitness, boost athletic performance and make it easier to do daily activities.

Core strength − Whenever you do push-ups, you will hear repeatedly that your core should stay engaged while doing a push-up. Doing push-ups can keep your trunk stable and help in maintaining a proper form. Advanced push-ups if done on an unstable surface may stabilise the core effectively.

Posture improvement − Push-ups can stabilise your core and strengthen your back, shoulders and abs. This way, you can improve your posture. Poor posture may cause back pain, headache and impaired breathing and is often linked to low energy and muscle fatigue.

Bone health − Bone strength is defined by bone mineral density. The lower the bone density, the higher the risk of fractures and chronic conditions like osteoporosis. Push-ups can help in building strong bones.

Heart health − Regular exercise which is inclusive of aerobics and strength training can help to boost heart health. This reduces the risk of chronic heart problems and hence, push-ups may help in improving heart health indirectly.

Conclusion

Doing push-ups every day may help you gain overall body strength. You can begin with modified push-ups and once the body is accustomed to them, you can move on to do traditional push-ups. You can also mix up the types of push-ups to continue to challenge your muscles. However, if you have had a prior injury or have any health condition, always consult your doctor before incorporating push-ups into your workout.

Motorola I1 Is World’S First Push

Motorola i1 is World’s First Push-to-Talk Android Smartphone

Sprint is continuing to push ahead with their Android-powered handset revolution. This time around, they’ve got their hands on the world’s first Android-powered Push-to-Talk handset. It’s going to be utilizing Sprint’s Nextel Direct Connect network, so if you’re a fan of that kind of thing, this device should be right up your alley. Other than that, the features are just about as standard as they get.

It’s got the 3.1-inch HVGA touchscreen display; the 5MP camera with flash; MicroSD card slot; WiFi; and EVDO Rev.A. It’s also got Bluetooth for all your handset-free talking, and Motorola has taken it upon themselves to pre-load the Opera Mobile Mini web browser, and the Swype keyboard. It’s got some means to protect itself from dust, drops, rain, and vibration, all up to par with military specifications.

Unfortunately, Motorola is telling us that we’ll have to wait until summer for this thing to show up, but we don’t know how much it will be. With CTIA 2010 going on this week, we’re sure that we’ll see some kind of word on this before the end of the week. Is the i1 something you’d be interested in? Full press release just below.

Press Release:

Motorola and Sprint Announce World’s First Push-To-Talk Android-Powered Smartphone – Motorola i1

Combines military spec ruggedness with the latest in smartphone technology, into a sleek touch screen design

LAS VEGAS – CTIA WIRELESS – March 22, 2010 – Motorola, Inc. (NYSE: MOT) and Sprint (NYSE: S) today broke new ground with the announcement of Motorola i1, the world’s first push-to-talk Android™-powered smartphone. Sleek and attractive, yet durable, Motorola i1 is the first iDEN device to carry the features of a modern smartphone including a 3.1-inch touch screen, Wi-Fi®, optimized browsing experience with the latest Opera Mini 5 browser, access to thousands of apps and a push-to-talk experience that includes exciting new features. Sprint will begin offering Motorola i1 this summer.

With more than 17 years of expertise, Sprint is the industry leader in push-to-talk, serving the world’s largest push-to-talk community with millions of Nextel Direct Connect subscribers on the fastest national push-to-talk network. Nextel Direct Connect® has set the industry standard for push-to-talk worldwide. More U.S. workers communicate in less than a second with Nextel Direct Connect than with any other push-to-talk service.

“Motorola remains focused on delivering differentiated Android experiences within our product portfolio,” said Mark Shockley, senior vice president, Motorola Mobile Devices. “With the Motorola i1, we’re excited to offer iDEN users the opportunity to enjoy a feature-rich smartphone with push-to-talk, whether it’s for work or play.”

“As the first Nextel Direct Connect Android smartphone, Motorola i1 with Wi-Fi offers a powerful tool for our customers with access to thousands of applications in the Android Market™,” said Fared Adib, vice president – Product Development, Sprint. “With rugged durability, a full touchscreen and 5.0 megapixel camera, Motorola i1 gives push-to-talk customers a compelling smartphone that can withstand some of the harshest environments.”

Motorola i1 enhances the push-to-talk experience with the ability to view who is calling regardless of what application you are in, whether you are managing your emails, checking your calendar, composing messages or viewing media.

Must-have Features and Nextel Direct Connect

With solid body construction that meets military specifications for protection against dust, shock, vibration and blowing rain1, Motorola i1 is designed for those who work and play hard. It automatically syncs and integrates office and personal information such as emails, calendar appointments and contacts. Key features include: Popular business tools such as Microsoft Document Viewer and corporate sync ensure Word or PowerPoint files can be accessed on the go.

A 5 megapixel camera with flash, geo-tagging and panoramic capabilities provides crisp photos and clearly displays them on the vibrant 3.1-inch HVGA screen. Video can also be recorded and stored on a provided microSD for sharing or future viewing straight from the device.

The latest Opera Mini 5 browser enables quick browsing over the Nextel National Network and Wi-Fi. The Android browser allows you to see web pages and Flash 8-enabled sites in full view using Wi-Fi.

Motorola i1 can be continuously customized with thousands of applications from Android Market™.

Application development information for Motorola i1 is available on the Sprint Application Developer web site at chúng tôi Sprint offers developers a free sandbox with iDEN capabilities to test their apps. Sprint is a charter member of the Open Handset Alliance™ and the Sprint Application Developer Program has been providing tools for third-party developers since Sprint first launched the Wireless Web on its phones in 2001.

New Relationship with Mike Rowe

In addition to introducing Android into push-to-talk devices, Motorola is also bringing a new face to its iDEN portfolio: Mike Rowe. Mike has worked as an apprentice at more than 250 of the toughest jobs in America, and his experience and reputation as a hard worker are a perfect fit for Motorola’s iDEN portfolio. The new relationship announced today will feature Mike as a spokesperson for Motorola’s rugged push-to-talk devices.

“Typically, the work I’ve done tends to take its toll on my phones and I end up breaking ’em on the job,” said Mike. “It’ll be fun to use one that’s not afraid of a little dirt.”

Motorola is also supporting mikeroweWORKS, a public relations campaign for skilled labor that Mike launched on Labor Day of 2008.

“It’s really gratifying to see some big companies getting behind the notion that working hard is just as important as working smart,” said Mike. “I’m happy to talk about a phone that can do both.”

Availability and Pricing

Sprint’s business customers can also select Sprint Business Advantage Messaging & Data PlansSM, starting at $59.99 per month. This includes unlimited Direct Connect; Wireless Web; unlimited text, picture and video messaging; 200 anytime minutes with nationwide long distance and Any Mobile, Anytime, unlimited nights and weekends starting at 7 p.m. and GPS Navigation.

[via Motorola]

Functions In C Programming With Examples: Recursive & Inline

What is a Function in C?

Function in C programming is a reusable block of code that makes a program easier to understand, test and can be easily modified without changing the calling program. Functions divide the code and modularize the program for better and effective results. In short, a larger program is divided into various subprograms which are called as functions

In this tutorial, you will learn-

Library Vs. User-defined Functions

Every ‘C’ program has at least one function which is the main function, but a program can have any number of functions. The main () function in C is a starting point of a program.

In ‘C’ programming, functions are divided into two types:

Library functions

User-defined functions

The difference between the library and user-defined functions in C is that we do not need to write a code for a library function. It is already present inside the header file which we always include at the beginning of a program. You just have to type the name of a function and use it along with the proper syntax. Printf, scanf are the examples of a library function.

Whereas, a user-defined function is a type of function in which we have to write a body of a function and call the function whenever we require the function to perform some operation in our program.

C programming functions are divided into three activities such as,

Function declaration

Function definition

Function call

Function Declaration

Function declaration means writing a name of a program. It is a compulsory part for using functions in code. In a function declaration, we just specify the name of a function that we are going to use in our program like a variable declaration. We cannot use a function unless it is declared in a program. A function declaration is also called “Function prototype.”

The function declarations (called prototype) are usually done above the main () function and take the general form:

return_data_type function_name (data_type arguments);

The return_data_type: is the data type of the value function returned back to the calling statement.

The function_name: is followed by parentheses

Arguments names with their data type declarations optionally are placed inside the parentheses.

We consider the following program that shows how to declare a cube function to calculate the cube value of an integer variable

/*Function declaration*/ int add(int a,b); /*End of Function declaration*/ int main() {

Keep in mind that a function does not necessarily return a value. In this case, the keyword void is used.

For example, the output_message function declaration indicates that the function does not return a value: void output_message();

Function Definition

Function definition means just writing the body of a function. A body of a function consists of statements which are going to perform a specific task. A function body consists of a single or a block of statements. It is also a mandatory part of a function.

int add(int a,int b) { int c; c=a+b; return c; } Function call

A function call means calling a function whenever it is required in a program. Whenever we call a function, it performs an operation for which it was designed. A function call is an optional part of a program.

result = add(4,5);

Here, is th complete code:

int add(int a, int b); int main() { int a=10,b=20; int c=add(10,20); printf(“Addition:%dn”,c); getch(); } int add(int a,int b) { int c; c=a+b; return c; }

Output:

Addition:30 Function Arguments

A function’s arguments are used to receive the necessary values by the function call. They are matched by position; the first argument is passed to the first parameter, the second to the second parameter and so on.

By default, the arguments are passed by value in which a copy of data is given to the called function. The actually passed variable will not change.

We consider the following program which demonstrates parameters passed by value:

int add (int x, int y); int main() { int a, b, result; a = 5; b = 10; result = add(a, b); printf("%d + %d = %dn", a, b, result); return 0;} int add (int x, int y) { x += y; return(x);}

The program output is:

5 + 10 = 15

Keep in mind that the values of a and b were passed to add function were not changed because only its value was passed into the parameter x.

Variable Scope

Variable scope means the visibility of variables within a code of the program.

In C, variables which are declared inside a function are local to that block of code and cannot be referred to outside the function. However, variables which are declared outside all functions are global and accessible from the entire program. Constants declared with a #define at the top of a program are accessible from the entire program. We consider the following program which prints the value of the global variable from both main and user defined function :

int global = 1348; void test(); int main() { printf(“from the main function : global =%d n”, global); test () ; return 0;}

void test (){ printf(“from user defined function : global =%d n”, global);}

Result:

from the main function : global =1348 from user defined function : global =1348

We discuss the program details:

We declare an integer global variable with 1348 as initial value.

We declare and define a test() function which neither takes arguments nor returns a value. This function only prints the global variable value to demonstrate that the global variables can be accessed anywhere in the program.

We print the global variable within the main function.

We call the test function in order to print the global variable value.

In C, when arguments are passed to function parameters, the parameters act as local variables which will be destroyed when exiting the function.

When you use global variables, use them with caution because can lead to errors and they can change anywhere in a program. They should be initialized before using.

Static Variables

The static variables have a local scope. However, they are not destroyed when exiting the function. Therefore, a static variable retains its value forever and can be accessed when the function is re-entered. A static variable is initialized when declared and needs the prefix static.

The following program uses a static variable:

void say_hi(); int main() { int i; for (i = 0; i < 5; i++) { say_hi();} return 0;} void say_hi() { static int calls_number = 1; printf(“Hi number %dn”, calls_number); calls_number ++; }

The program displays :

Hi number 1 Hi number 2 Hi number 3 Hi number 4 Hi number 5 Recursive Functions

Consider the factorial of a number which is calculated as follow 6! =6* 5 * 4 * 3 * 2 * 1.

This calculation is done as repeatedly calculating fact * (fact -1) until fact equals 1.

A recursive function is a function which calls itself and includes an exit condition in order to finish the recursive calls. In the case of the factorial number calculation, the exit condition is fact equals to 1. Recursion works by “stacking” calls until the exiting condition is true.

For example:

int factorial(int number); int main() { int x = 6; printf(“The factorial of %d is %dn”, x, factorial(x)); return 0;} int factorial(int number) { if (number == 1) return (1); /* exiting condition */ else return (number * factorial(number – 1)); }

The program displays:

The factorial of 6 is 720

Here, we discuss program details:

We declare our recursive factorial function which takes an integer parameter and returns the factorial of this parameter. This function will call itself and decrease the number until the exiting, or the base condition is reached. When the condition is true, the previously generated values will be multiplied by each other, and the final factorial value is returned.

We declare and initialize an integer variable with value”6″ and then print its factorial value by calling our factorial function.

Consider the following chart to more understand the recursive mechanism which consists of calling the function its self until the base case or stopping condition is reached, and after that, we collect the previous values:

Inline Functions

Function in C programming is used to store the most frequently used instructions. It is used for modularizing the program.

Whenever a function is called, the instruction pointer jumps to the function definition. After executing a function, instruction pointer falls back to the statement from where it jumped to the function definition.

In an inline function, a function call is directly replaced by an actual program code. It does not jump to any block because all the operations are performed inside the inline function.

Inline functions are mostly used for small computations. They are not suitable when large computing is involved.

An inline function is similar to the normal function except that keyword inline is place before the function name. Inline functions are created with the following syntax:

inline function_name () { }

Let us write a program to implement an inline function.

inline int add(int a, int b) { return(a+b); } int main() { int c=add(10,20); printf("Addition:%dn",c); getch(); }

Output:

Addition: 30

Above program demonstrates the use of an inline function for addition of two numbers. As we can see, we have returned the addition on two numbers within the inline function only without writing any extra lines. During function call we have just passed values on which we have to perform addition.

Summary

A function is a mini-program or a subprogram.

Functions are used to modularize the program.

Library and user-defined are two types of functions.

A function consists of a declaration, function body, and a function call part.

Function declaration and body are mandatory.

A function call can be optional in a program.

C program has at least one function; it is the main function ().

Each function has a name, data type of return value or a void, parameters.

Each function must be defined and declared in your C program.

Keep in mind that ordinary variables in a C function are destroyed as soon as we exit the function call.

The arguments passed to a function will not be changed because they passed by value none by address.

The variable scope is referred to as the visibility of variables within a program

There are global and local variables in C programming

Update the detailed information about C# Stack With Push & Pop Examples on the Cattuongwedding.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!