Trending February 2024 # Complete Guide To How Does C Ftell() Working With Examples # Suggested March 2024 # Top 7 Popular

You are reading the article Complete Guide To How Does C Ftell() Working With Examples updated in February 2024 on the website Daihoichemgio.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 March 2024 Complete Guide To How Does C Ftell() Working With Examples

Introduction to C ftell()

The C ftell() function is used to return the current position of the specified file stream. The ftell() function is a built-in function in c. Some times in program while we reading or writing the data from or to the file we need to get the current position of the file to read data from a specific location or to write the data to a specific location, so to get the current location of the file pointer we can use ftell() function and the later to change or move the pointer location we can use the fseek() function(), which is also a built-in function. The ftell() function accepts file pointer which points to the specific file, so this function returns the current position of that specific file and this function also can be used to return the size of the file by moving the pointer to the end of the file with the help of SEEK_END constant value.

Start Your Free Software Development Course

The Syntax of the ftell() function in C

Following is the syntax to call the ftell() function in c –

long int ftell(FILE *fstream);

Parameters –

*fstream – *fstream parameter specifies the FILE type pointer which points to specific FILE object.

Return value –

The return value of the function as is int, it returns the current location of the file pointer pointing, otherwise returns -1L if any error occurs.

Working and Examples of ftell() function in C

Next, we write the C code to understand the ftell() function working more clearly with the following example where we use ftell() function to get the current location of the file pointed by the pointer, as below –

Example #1

Code:

void main() { char fdata[50]; FILE *fstream = fopen(“data.txt”,”r”); printf(“The current location of th pointer before reading from the file is : %ldn”, ftell(fstream)); fscanf(fstream,”%s”,fdata); printf(“The current data read from the file is : %sn”, fdata); printf(“The current location of th pointer after reading from the file is : %ldn”, ftell(fstream)); }

Output:

As in the above code, the file “data.txt” is opened and the fstream is a FILE type pointer which is pointing to this file, if any operation needs to perform-like read, write, append, etc, we can perform with the help of this FILE pointer(fstream). When the new file is open the file pointer always points to the starting position of the file that is 0 in the file. Farther in the code the ftell() function is used before and after reading some data from the file. So before reading the data the ftell() return the pointer location is 0, after reading data “This” which is of four lengths the ftell() return the pointer location is 4, which are correct.

Next, we write the C code to understand the ftell() function working where we use ftell() function to get the total length of the file by using the file pointer, as below –

Example #2

Code:

void main() { char fdata[50]; int length; FILE *fstream = fopen(“data.txt”,”r”); printf(“The current location of th pointer before seek is : %ldn”, ftell(fstream)); fseek(fstream, 0, SEEK_END); length = ftell(fstream); printf(“The total length the file is : %ldn”, length); printf(“The current location of th pointer after seek is : %ldn”, ftell(fstream)); }

Output:

As in the above code, the file “data.txt” is open which stores the data “This is the file data.” of length 22 and the fstream is a FILE type pointer which is pointing to this file. Farther in the code the fseek() function is used to move the pointer to the end of the file with the help of SEEK_END constant value and then after moved with the help of ftell() function return the pointer location which is 22 that is the last location or index pointing by the point and that is what the length of the file.

Example #3

Code:

void main() { int i; FILE *fstream = fopen( “data1.txt”,”r” ); i = ftell(fstream); if(i == -1L) { printf( “A file error has occurred!!n” ); } printf( “The current location of the pointer is : %ldn”, ftell(fstream) ); }

Output:

As in the above code, the file “data1.txt” is trying to open but that file does not exist. The fstream FILE type pointer is trying to point to this file as the file does not exist the fopen() function return 0 and so the ftell(fstream) function return -1L, as because the error occurs to open the file.

Conclusion

The ftell() function is a built-in function in C, which is used to return the current position of the file stream. The ftell() function accepts one parameter of File type pointer which points to the file.

Recommended Articles

This is a guide to C ftell(). Here we discuss an introduction to ftell() with the working of this function and respective examples for better understanding. You may also look at the following articles to learn more –

You're reading Complete Guide To How Does C Ftell() Working With Examples

Complete Guide To Working Of C# Thread Methods & Class

Introduction to C# Thread

Web development, programming languages, Software testing & others

Syntax:

public sealed class Thread: System.Runtime.ConstrainedExecution.CriticalFinalizerObject Working of C# Thread Class

The time an object of System.Threading.Thread class is created when the life cycle of the thread starts. When there is termination of thread or completion of execution of thread, the thread is created and ends.

There are several states in the life cycle of a thread.

2. The Ready state: This state is a situation when the thread is all set to run and is waiting for the cycle of Central Processing Unit.

3. The Not Runnable State: This state is a situation when the thread cannot be executed when:

There has been a call to the Sleep method.

There has been a call to the Wait method.

There has been a block by input/output operations.

4. The dead State: This state is a situation when the execution of the thread is complete, or the execution of the thread is aborted.

The thread that will be first executed in the entire process is called as Main thread.

The main thread is automatically created when the execution of C# program begins.

The CurrentThread property of Thread class is used to access a thread.

Below program demonstrates the execution of main thread:

Code:

using System; using System.Threading; namespace Multithreading { class MainThread { static void Main(string[] args) { Thread thr = Thread.CurrentThread; thr.Name = "Thread Class"; Console.WriteLine("Welcome to {0}", thr.Name); Console.ReadKey(); } } }

Output:

In the above program, a namespace called multithreading is created. Then a class called mainthread is created under multithreading namespace. Then a main method is called. Then an instance of the thread class is created. Then Name method of thread class is accessed using the instance of the thread class. Finally the output is displayed on the screen.

Methods of Thread Class

Given below are the several methods of thread class:

1. Abort()

Whenever Abort() method is invoked on a thread, ThreadAbortException is raised and the process of termination of thread begins. The termination of thread is caused by calling this method.

Example: 

Code:

using System; using System.Threading; class ExThread { public void thr() { for (int y = 0; y < 3; y++) { Console.WriteLine(y); } } } class Example { public static void Main() { ExThread ob = new ExThread(); Thread th = new Thread(new ThreadStart(ob.thr)); th.Start(); Console.WriteLine("Aborting the thread"); th.Abort(); } }

Output:

2. Interrupt()

Whenever Interrupt() method is called, a thread which is in the thread state of WaitSleepJoin is interrupted.

3. Join()

Whenever Join() method is called, a calling thread is blocked until the termination of a thread and the standard COM and SendMessage pumping are continued to be performed along with blocking of the thread.

Example to implement Interrupt() and Join():

using System; using System.Threading; class Thr { Thread th; public Thr(String name1) { th = new Thread(this.Runaway); th.Name = name1; th.Start(); } public void Runaway() { Thread th1 = Thread.CurrentThread; try { Console.WriteLine(" Execution of " + chúng tôi + " has begun"); for(int y=0; y<3; y++) { Console.WriteLine(" Printing of " + chúng tôi + " has begun" + y); Thread.Sleep(200); } Console.WriteLine(" Execution of " + chúng tôi + " is finished"); } catch(ThreadInterruptedException e) { Console.WriteLine("Thread Interruption" + e); } } public static void Main(String[] ar) { Thr ob = new Thr("Thread demo"); ob.th.Interrupt(); ob.th.Join(); } }

Output:

4. ResetAbort()

Whenever ResetAbort() method is called, the termination request for the current thread is cancelled.

Example:

Code:

using System; using System.Threading; using System.Security.Permissions; class Thread1 { public void Jobthread() { try { for (int r = 0; r < 3; r++) { Console.WriteLine(" Working of thread has begun "); Thread.Sleep(10); } } catch (ThreadAbortException e) { Console.WriteLine("ThreadAbortException is caught and must be reset"); Console.WriteLine("The message looks like this: {0}", e.Message); Thread.ResetAbort(); } Console.WriteLine("Thread is working fine"); Thread.Sleep(200); Console.WriteLine("Thread is done"); } } class Driver { public static void Main() { Thread1 obj = new Thread1(); Thread Th = new Thread(obj.Jobthread); Th.Start(); Thread.Sleep(100); Console.WriteLine("thread abort"); Th.Abort(); Th.Join(); Console.WriteLine("end of main thread"); } }

Output:

5. Start()

Whenever Start() method is called, a thread is started.

Example:

Code:

using System; using System.Threading; class Test { static void Main() { Thread td = new Thread (new ThreadStart (Got)); td.Start(); } static void Got() { Console.WriteLine ("this is thread Start() method"); } }

Output:

6. Sleep(int millisecondsTimeout)

Whenever Sleep(int millisecondsTimeout) method is called, the thread is paused for the specified time period.

Example:

Code:

using System; using System.Threading; namespace Examplethr { class MyThread { static void Main(string[] args) { Thread th = Thread.CurrentThread; th.Name = "This is the First Thread"; Console.WriteLine("The Name of the thread is : {0}", th.Name); Console.WriteLine("The priority of the thread is : {0}", th.Priority); Console.WriteLine("Pausing the child thread"); Thread.Sleep(100); Console.WriteLine("Resuming the child thread"); Console.ReadKey(); } } }

Output:

7. Suspend()

Whenever Suspend() method is called, the current thread is suspended if it is not suspended.

8. Resume()

Whenever Resume() method is called, the suspended thread is resumed.

9. Yield()

Whenever Yield() method is called, the calling thread must result in execution to the other thread which is ready to start running on the current processor. The thread to yield to is selected by the operating system.

Example to implement Suspend() Resume() and Yield()

Code:

using System; using System.Runtime.CompilerServices; using System.Threading; class Program { public static void Main () { bool finish = false; while (!finish) {} }); while (!finish) { GC.Collect (); Thread.Yield (); } }); th.Start (); th1.Start (); Thread.Sleep (10); for (int j = 0; j < 5 * 4 * 2; ++j) { th.Suspend (); Thread.Yield (); th.Resume (); if ((j + 1) % (5) == 0) Console.Write ("Hello "); if ((j + 1) % (5 * 4) == 0) Console.WriteLine (); } finish = true; th.Join (); th1.Join (); } }

Output:

Recommended Articles

This is a guide to C# Thread. Here we discuss the introduction to C# Thread, working of thread class and several methods respectively. You may also have a look at the following articles to learn more –

Python Range() Function: A Complete Guide (With Examples)

In Python, you can use the built-in range() function to generate a range of numbers from a start point to an end point.

For instance, let’s create a range of numbers from 0 to 5 and print them out:

numbers = range(0,6) for number in numbers: print(number)

Output:

0 1 2 3 4 5

Notice how the last number in the range() call is 6. This means the last number included in the range is actually 5.

In Python, you can call the range() function with one, two, or three parameters.

Here are some examples:

# Range from 0 to 9 range(10) # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 # Range from 5 to 9 range(5, 10) # 5, 6, 7, 8, 9 # Range from 1 to 100 with step size of 10 range(0, 110, 10) # 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 # Reversed range from 100 to 0 with step size of -10. range(100, -10, -10) # 100, 90, 80, 70, 60, 50, 40, 30, 20, 10

If you’re looking for a short answer, I’m sure the above examples help you. But to truly learn how to use the range() function in different situations, I recommend reading the entire post.

This is a comprehensive guide to the range() function in Python. In this guide, you will learn thoroughly how to use the range() function in Python.

The range() Function in Python

In Python, the built-in range() function produces an immutable sequence of numbers between start and end values.

The complete syntax of using range() function is as follows:

range(start, stop, step)

Where:

start is the lower limit for the range. This is an optional parameter with a default value of 0.

stop is the upper limit for the range. The range consists of numbers until this value. Notice how it never includes the stop value in the range!

step is the step size for the range. This is an optional argument that defaults to 1. Each number in the range is generated by adding step to the previous value.

The range() function returns a range object. You can loop through this range object with a for loop. It is also possible to convert the range object into a list.

In Python 3, there are three syntactical variations of how to use the range() function:

range(stop)

range(start, stop)

range(start, stop, step)

Let’s go through each of these alternatives in more detail.

1. range(start)

The most basic way to use the range() function in Python is by specifying only the end value for the range.

range(stop)

When you do this, the range automatically starts from 0 and takes steps of size 1. It ends one before the stop value.

For example, let’s generate a range of numbers from 0 to 5:

numbers = range(6) for number in numbers: print(number)

Output:

0 1 2 3 4 5

Here the range starts from 0 because you did not specify a starting value. The range ends at the value of 5 instead of 6 due to the exclusive nature of range() function.

2. range(start, stop)

Another way you can call the range() function in Python is by specifying both start and stop values. This is useful if you want the range to start from a value other than 0, which commonly is the case.

range(start, stop)

For instance, let’s generate values from 5 to 10:

numbers = range(5,11) for number in numbers: print(number)

Output:

5 6 7 8 9 10

Notice that the start value 5 is included in the range, but the end value 11 is not. This might cause confusion if it’s your first time using the range() function.

3. range(start, stop, step)

The third option to call the range() function is by specifying start, stop, and step parameters.

range(start, stop, step)

The step parameter sets the interval for the range. In other words, it affects the way the range is generated by adding a value other than 1 to the previous number.

For example, let’s generate a range of values from 50 to 100 with by using 10 as a step size:

numbers = range(50,110,10) for number in numbers: print(number)

Output:

50 60 70 80 90 100 The range() Function Return Value

Now that you know how to use the range() function in Python, let’s take a closer look at the return value.

In Python, the range() function returns a range object.

For example, let’s create a range of numbers and print the object. Let’s also print the type of the range using the built-in type() function:

numbers = range(5, 10) print(numbers) print(type(numbers))

Output:

range(5, 10)

The result of printing the range is not a list of numbers as you might expect. Instead, it’s a range object. In other words, the range() function returns a special range object.

The range object is iterable by nature. This means you can loop through it like any other iterable, such as a list. This is what you already saw in the previous examples.

Of course, you can also convert the range object into another iterable type, such as a list.

For example, let’s generate a range of numbers and convert it to a list with the built-in list() function:

numbers = range(50,110,10) numbers_list = list(numbers) print(numbers_list)

Output:

[50, 60, 70, 80, 90, 100]

Now the result is a regular Python list instead of a range object. So if you need to generate a range as a list, you can easily cast the range object into a list.

Keep in mind the range object is a range object for performance reasons. If there’s no need to cast the range to a list, don’t do it!

Reversed Range in Python

In Python, it is possible to create a reversed range by specifying a negative step size to the range() function call.

For example, let’s generate a range of numbers from 100 to 50:

numbers = range(100, 40, -10) for number in numbers: print(number)

Output:

100 90 80 70 60 50

Make sure you understand why this works.

The range starts from the start parameter, but it stops one step before the stop parameter. Thus the stop is set to 40 to include 50 in the range.

As the step is -10, the range takes steps of size -10. In other words, it decreases the start by 10 until the stop value.

But why do you need to specify the step value at all? How about range(100, 40)?

As you remember, the range(100, 40) would mean that the step is 1 (by default) which would mean range(100, 40, 1).

This confuses Python as it tries to get from 100 to 40 by adding ones to 100, which is impossible.

Thus the result is an empty range.

numbers = range(100, 40) numbers_list = list(numbers) print(numbers_list)

Output:

[] Negative Range in Python

In Python, you can use the built-in range() function to produce a range of negative numbers.

When speaking about negative ranges in Python, you may refer to:

Negative range with increasing numbers, that is, a positive step.

Negative range with decreasing numbers, that is, a negative step.

Let’s see an example of each.

Negative Range with Increasing Numbers

For example, let’s create a range of numbers from -1 to -5:

numbers = range(-1, -6, -1) for number in numbers: print(number)

Output:

-1 -2 -3 -4 -5

Notice how you need a negative step size to make the range work. This is because it is not possible to get smaller values by adding positive values.

In other words, if you did not specify a negative step:

numbers = range(-1, -6) print(list(numbers))

Your result would be an empty range, that is, no values at all:

[] Negative Range with Increasing Numbers

To produce a range of negative values in increasing order, use the built-in range() function the same as you use it with positive numbers.

For example, let’s create a range of negative numbers from -10 to -5.

numbers = range(-10, -4) for number in numbers: print(number)

Output:

-10 -9 -8 -7 -6 -5

Notice how the step parameter is not needed as you are increasing the numbers by one.

Range Indexing in Python

In Python, the range() function produces a range object. This range object supports indexing the same way other iterables, such as lists, do.

For example, let’s get the second number in a range of numbers:

numbers = range(1, 6) # 1, 2, 3, 4, 5 second = numbers[1] print(second)

Output:

2

Needless to mention range objects support negative indexing too.

For example, let’s get the last element of a range using negative indexing -1:

numbers = range(1, 6) # 1, 2, 3, 4, 5 last = numbers[-1] print(last)

Output:

5 Range Slicing in Python

Python range objects support slicing. This means you can get a partial group of numbers from a range using slicing.

When you slice a range object in Python, you get a range object as a result. This range object contains the part of the original range.

If you are unfamiliar with slicing in Python, feel free to check this article.

For example, let’s get the first 3 numbers in a range:

numbers = range(1, 10) first_three = numbers[0:3] for number in first_three: print(number)

Output:

range(1, 4)

A common way to use slicing in Python is to reverse an iterable with slicing by [::-1]. You can do the same for a range of numbers too.

For instance, let’s reverse a range of numbers from 1 to 5:

numbers = range(1, 6) rev = numbers[::-1] for number in rev: print(number)

Output:

5 4 3 2 1 Inclusive Range

The Python range() function produces a range of values that does not include the last value by default.

For example range(0,5) produces a range of values 0, 1, 2, 3, 4.

To create an inclusive range, that is, to add the stop value into the range too, add the step value to the stop value.

For example, let’s create a range of values from 1 to 5 inclusively:

step = 1 numbers = range(1, 5 + step, step) print(list(numbers))

Output:

[1, 2, 3, 4, 5] For Loops with range() in Python

A common way to utilize the range() function is with for loops.

Loop Through Numbers with range()

The most basic use case is when looping through numbers from n to m.

For example, let’s print numbers from 1 to 5:

numbers = range(1,6) for number in numbers: print(number)

Output:

1 2 3 4 5 Loop with an Index Using range() Function

Another common use case for the range() is to access the index (or indexes) of an element with a for loop.

For example, let’s print a list of names and their index in the list:

queue = ["Alice", "Bob", "Charlie", "David"] for pos in range(len(queue)): print(f"{pos}: {queue[pos]}")

Output:

0: Alice 1: Bob 2: Charlie 3: David

Although there’s a much better solution to get the indexes by using the enumerate() function. Let’s have a look at how this function works.

Alternative to range() Function with For Loops

Now you know the range() can be used in a for loop to get the index of the elements. Meanwhile, this is commonly taught for beginners, it is not the ideal way to do it.

Instead, you should use a built-in enumerate() function.

For example, let’s repeat the example of printing the list of names and their index. Let’s not use range() this time, but enumerate() instead:

queue = ["Alice", "Bob", "Charlie", "David"] for pos, name in enumerate(queue): print(f"{pos}: {name}")

Output:

0: Alice 1: Bob 2: Charlie 3: David

In short, the enumerate() function couples the list elements with their index.

In the above example, the enumerate(queue) produces an object with position, name pairs:

[(0, 'Alice'), (1, 'Bob'), (2, 'Charlie'), (3, 'David')] Conclusion

Today you learned how to use the range() function in Python.

To recap, the range() function returns a range of values from n until m.

For example range(5) returns numbers 0,1,2,3,4.

The result of the range() function is a range object. You can use the range object to loop through the range. Alternatively, you can cast the range object to a list to get a list that represents a range of numbers.

There are three ways to call the range function in Python:

range(start)

range(start, stop)

range(start, stop, step)

Thanks for reading. Happy coding!

Further Reading

50 Python Interview Questions

How Sizeof() Operator Work In C++ With Examples

Introduction to C++ sizeof()

The sizeof() is an operator in C and C++. It is an unary operator which assists a programmer in finding the size of the operand which is being used. The result of this operator is an integral type which is usually signified by size_t. This operator is usually used with data types which can be primitive data types like integer, float, pointer, etc. It can also give size of complex datatypes like structure, union, etc. It is a compile time operator which will tell the size of any data type and compute the size of operand.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Below is the syntax of using sizeof():

sizeof(type) sizeof expression

The sizeof function in the first type, will give the output as an size in bytes of the object of the type which is sent. The second type is the size in bytes of the object which is in the type of expression. The size will be the size once the expression is evaluated. In both these versions the constant expression of the standard type that is size_t.

How sizeof() Operator work in C++?

The sizeof() operator can be used to find the size of datatype or expressions. They work in a very easy manner of taking these as arguments and work on them by returning the size in bytes.

Code:

using namespace std; int main() { cout << “Size of char : ” << sizeof(char) << endl; cout << “Size of int : ” << sizeof(int) << endl; cout << “Size of expression 5 + 8 is : ” << sizeof(5 + 8) << endl; return 0; }

As stated earlier the sizeof function will help us in getting the size of every datatype. Hence it uses these data types as an argument and return the data size of each data type. We have also taken size of expression where we are adding 2 integers. It will calculate these and the result will also be an integer. Hence the output for this will be also 4. The output of above function and code will be the number of bytes each variable uses. To check a few the output for char will be as below.

Output:

Examples of C++ sizeof()

Given below are the examples mentioned:

Example #1

Operand as a data type.

Code:

using namespace std; int main() { cout << “The size of char data type is ” << sizeof(char)<<“n”; cout << “The size of int data type is ” << sizeof(int)<<“n”; cout << “The size of float data type is “<< sizeof(float)<<“n”; cout << “The size of double data type is ” << sizeof(double)<<“n”; return 0; }

Output:

Example #2

Operand as an expression.

Code:

using namespace std; int main() { int a = 7; float d = 15.21; cout << “The addition of int and float is a float as follows: ” << a + d; cout << “nThe size of the expression is ” << sizeof(a + d); return 0; }

The above code with return the size of the data type of the resulting expression. Here we have declared two variables. One variable is an integer and the second variable is a float. We are now adding these two variables in the expression of which we will be finding the size of. The result of this expression will be a float. Hence the sizeof will be the size of float data type.

Output:

Example #3

Finding number of elements in the array.

Code:

using namespace std; int main() { int array1[] = { 1,5,76,89,23,06 }; cout << “The number of elements which are present in the array are : “ <<(sizeof(array1) / sizeof(array1[0])); return 0; }

In addition to giving the size of expressions and data types, the sizeof operator can also be used to find the number of elements in an array. Here we have defined an array ‘array1’. We have a few elements added to it. In order to get the count of these elements and get exactly how many elements are present in it we can simply make use of the sizeof operator.

We specify the array name and the first index that is array1[0] which helps us in starting he count from beginning. It will start from index 0 and count till the end. Once it reached the end it will display the number of elements. It will be returned by this sizeof() function that we have.

Output:

Conclusion

The sizeof() operator is a function which returns the size of any data type, expression, array, etc. It takes the data type or expression as a part of argument which is mandatory and returns the result which is size of that data type in bytes. If it is an array it will return the number of elements present in it. It is a very useful function when we have to allocate memory. We can calculate the size and allocate memory as per requirement and as a result save a lot of space which otherwise will be occupied.

Recommended Articles

This is a guide to C++ sizeof(). Here we discuss how sizeof() operator work in C++ along with examples respectively. You may also have a look at the following articles to learn more –

How Does React Fragment Work With Examples

Introduction to React Fragment

React Fragments were first launched in the version React 16.2.0. These are used where, earlier, the developers used wrapper div as React Fragments help us group a set of children without adding additional nodes to the DOM. Earlier, the elements were wrapped in a div for returning multiple aspects. This led to some irrelevant markup or rendering of irrelevant HTML, which could have been better for the website. React Fragments solved this problem. This easily returns multiple elements without the need for a wrapper div. This article will explain how to use this with some examples.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

render() { return ( ); } How does React Fragment work with Examples? 1. Short Example

Components inside src folder:

index.js

style.css

chúng tôi

import React from 'react' import ReactDOM from 'react-dom' function App() { return ( ) }

chúng tôi

.App { font-family: 'Times New Roman', Times, serif, sans-serif; text-align: center; }

Output:

2. Basic

Components inside src folder:

chúng tôi

import React , { Component , Fragment } from "react"; import { render } from "react-dom"; class Columns extends Component { render() { const heros = [ { name: 'Dr. Strange', id: 1 }, { name: 'Ironman', id: 2 }, { name: 'Rocket', id: 3 } ]; return ( <Fragment key={hero.id {hero.name } is SUPER AMAZING!!.... ))} ); } } class Table extends Component { render() { return ( ); } }

Output:

3. With SignIn and SignOut buttons

Components inside src folder:

config folder

admin.js

home.js

login.js

index.js

Components inside config folder:

switch.js

routes.js

chúng tôi

import { Switch } from "react-router-dom"; import React , { Fragment } from "react"; export default function FragmentSupportingSwitch({ children }) { const flattenedChildren = []; flatten(flattenedChildren, children); return React.createElement.apply( React, [Switch, null].concat(flattenedChildren) ); } function flatten(target, children) { if (React.isValidElement(child)) { if (child.type === Fragment) { flatten(target, child.props.children); } else { target.push(child); } } }); }

chúng tôi

import React , { Fragment } from "react"; import { Router , Route } from "react-router-dom"; import Switch from "./Switch"; import createBrowserHistory from "history/createBrowserHistory"; import Login from "../Login"; import Home from "../Home"; import Admin from "../Admin"; export const history = createBrowserHistory(); return ( {!isLoggedIn && ( )} ) : ( <Route exact path="/admin" )} ); }; export default Routes;

chúng tôi

import React from "react"; ); import React from "react"; import { Link } from "react-router-dom"; );

chúng tôi

import React from "react"; );

chúng tôi

import React from "react"; import { render } from "react-dom"; import Routes from "./config/routes"; class App extends React.Component { state = { isLoggedIn: false }; this.setState({ isLoggedIn: true }); }; this.setState({ isLoggedIn: false }); }; render() { return ( <Routes login={this.login} logout={this.logout} isLoggedIn={this.state.isLoggedIn} ); } }

Output:

4. With Switch

Components inside src folder:

chúng tôi

import React from "react"; import ReactDOM from "react-dom"; import { Switch as BaseSwitch , Route , BrowserRouter , Link } from "react-router-dom"; import flattenChildren from "react-flatten-children"; ); class App extends React.Component { state = { private: false }; render() { return ( <button type="button" > {this.state.private ? "Sign Out" : "Sign In"} {this.state.private && ( )} {this.state.private && ( )} ); } } const rootElement = document.getElementById("root");

Output:

5. With Render Fragment

Files to develop this:

fragment.js

Hello.js

index.html

index.js

chúng tôi

import React from 'react'; import PropTypes from 'prop-types'; const [reactMajorVersion] = React.version.split('.'); Wrapper : React.Children.toArray(children) ); if (process.env.NODE_ENV !== 'production') { RenderArrayOrDiv.propTypes = { as: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), children: PropTypes.node.isRequired, }; } RenderArrayOrDiv.defaultProps = { as: canReturnArray ? undefined : 'div', }; console.log(React.Fragment); const Fragment = React.Fragment ? React.Fragment : RenderArrayOrDiv; console.log(Fragment); export default Fragment;

chúng tôi

import React from 'react';

index.html

chúng tôi

import React from 'react'; import { render } from 'react-dom'; import Fragment from 'render-fragment'; import Hello from './Hello'; );

Output:

Conclusion

In this article, we understood This and why it is so helpful to the developers. We went through five different examples to understand the different ways to use this same. This is easy to use, and I hope this article would have explained the ways to use it in a simple and meaningful way.

Recommended Articles

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

Gude To How Does Mysql Alias Works With Examples

Introduction to MySQL Alias

MySQL Alias is used when we are willing to provide an alternate name for the column or table. Temporarily assigning a name for a column or table that is user-friendly and understandable. Alias is mainly used for the column and table. Column Alias gives an alternate name for the column headings, accessible for the end-user to understand. Table aliasing involves assigning alternate names to tables, which makes it more convenient to read and use them, particularly in the context of joins.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

Given below is the syntax of the alias and how it is used in the column and table:

Here in the above syntax, we provide the column name which we want an alternate to be given. “AS” is optional. And at last, we provide the alias name.

Here in the above syntax, we provide the table name we want to give the alternate. “AS” is optional. And at last we provide the alias name.

How does MySQL Alias works?

MySQL Alias works in the following way:

1. Column Alias

Code:

CREATE TABLE EMPLOYEE_INFORMATION ( EMPLOYEE_ID VARCHAR(10), EMPLOYEE_NAME VARCHAR(20), DEPT_ID VARCHAR(10), EMPLOYEE_SAL INT );

Now let us insert data into the above table:

Code:

INSERT INTO EMPLOYEE_INFORMATION VALUES ('E1','SAM','D1', 90000); INSERT INTO EMPLOYEE_INFORMATION VALUES ('E2','WILL','D1', 80000); INSERT INTO EMPLOYEE_INFORMATION VALUES ('E3','SOMY','D1', 50000); INSERT INTO EMPLOYEE_INFORMATION VALUES ('E4','FRED','D1', 10000); INSERT INTO EMPLOYEE_INFORMATION VALUES ('E5','HARRY','D2', 70000); INSERT INTO EMPLOYEE_INFORMATION VALUES ('E6','PONY','D2', 70000); INSERT INTO EMPLOYEE_INFORMATION VALUES ('E7','DAVID','D2', 40000); INSERT INTO EMPLOYEE_INFORMATION VALUES ('E8','PETER','D3', 30000); INSERT INTO EMPLOYEE_INFORMATION VALUES ('E9','RAM','D3', 60000); INSERT INTO EMPLOYEE_INFORMATION VALUES ('E10','SAI','D3', 50000); select * from EMPLOYEE_INFORMATION;

Output:

Now let us give an alias to each column above without an underscore in the column name.

The below example is for the column aliasing:

Code:

SELECT EMPLOYEE_ID AS "EMPLOYEE ID", EMPLOYEE_NAME AS "EMPLOYEE NAME", DEPT_ID AS "DEPARTMENT_ID", EMPLOYEE_SAL AS "EMPLOYEE SALARY" FROM EMPLOYEE_INFORMATION;

Output:

2. Table Alias

A table alias is mainly used when we are performing joins on the table.

Below are the sample table with sample data to show how the alias is performed.

Code:

CREATE TABLE SAMPLE_A ( COL_A INT, COL_B INT );

Insert data into the table:

Code:

INSERT INTO SAMPLE_A VALUES (1, 5); INSERT INTO SAMPLE_A VALUES (2, 4); INSERT INTO SAMPLE_A VALUES (3, 3); INSERT INTO SAMPLE_A VALUES (4, 2); INSERT INTO SAMPLE_A VALUES (5, 1); select * from SAMPLE_A;

Output:

Now let us create another table.

Code:

CREATE TABLE SAMPLE_B ( COL_A INT, COL_B INT );

Insert data into the table:

Code:

INSERT INTO SAMPLE_B VALUES (1, 5); INSERT INTO SAMPLE_B VALUES (2, 4); INSERT INTO SAMPLE_B VALUES (3, 3); INSERT INTO SAMPLE_B VALUES (4, 2); INSERT INTO SAMPLE_B VALUES (5, 1); Select * from SAMPLE_B;

Output:

Now let us perform joining on above and use an alias:

a. Without Table alias

Code:

SELECT * FROM SAMPLE_A JOIN SAMPLE_B ON  SAMPLE_A.COL_A = SAMPLE_B.COL_A

Output:

b. With Table alias

Code:

SELECT * FROM SAMPLE_A A JOIN SAMPLE_B B ON A.COL_A = B.COL_A

Output:

Examples of MySQL Alias

Given below are the examples:

Example #1 – Column alias

Now let us find the maximum and minimum salary that each department has for the above table which we created earlier.

Code:

SELECT DEPT_ID AS "DEPARTMENT ID", MAX(EMPLOYEE_SAL)AS "MAXIMUM EMPLOYEE SALARY", MIN(EMPLOYEE_SAL)AS "MINIMUN EMPLOYEE SALARY" FROM EMPLOYEE_INFORMATION GROUP BY DEPT_ID;

Output:

Example #2 – Table alias

If we consider a table giving an alternate name for the table is said to be table aliasing.

Code:

SELECT * FROM SAMPLE_A JOIN SAMPLE_B ON SAMPLE_A.COL_A = SAMPLE_B.COL_A

Output:

Here every time mentioning the whole table name in the joining condition would be difficult.

b. With Table alias

Code:

SELECT * FROM SAMPLE_A A JOIN SAMPLE_B B ON A.COL_A = B.COL_A

Output:

Here every time mentioning the whole table name in the joining condition would be difficult. Hence, we have mentioned the alias for the table. SAMPLE_A has alias name as “A”. And SAMPLE_B table has “B” alias.

We could see that ‘AS’ is not written while mentioning the alias.

We can mention alias as below as well:

Code:

SELECT * FROM SAMPLE_A AS A JOIN SAMPLE_B AS B ON A.COL_A = B.COL_A

Output:

Conclusion

Things that need to put in mind regarding the MySQL Alias are if you want space to be provided in the alias_name, then we must enclose the alias_name in quotes. Spaces are accepted when we are defining in the column name. However, it is not good practice to use space in the table name aliasing. The alias_name is only valid within the scope of the SQL statement.

Recommended Articles

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

Update the detailed information about Complete Guide To How Does C Ftell() Working With Examples on the Daihoichemgio.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!