C# - Count Vowels in Character Array Using Pointers

Here, we will learn how to count vowels in character array using pointers using the pointer in C#?
Submitted by Nidhi, on November 01, 2020 [Last updated : March 23, 2023]

Here, we will count vowels in character array using pointers. To use pointer we need to write unsafe code, to compile unsafe code we need to allow unsafe code by clicking on properties in solution explorer and then "Allow Unsafe Code" from the Build tab.

C# program to count vowels in character array using pointers

The source code to count vowels in character array using pointers is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to count vowels from character array using pointers.

using System;

class UnsafeEx
    static unsafe void Main(string[] args)
        int loop = 0;
        int countVowels=0;

        char[] str = { 'i','n','c','l','u','d','e','h','e','l','p'};
        fixed(char *ptr = str)
        for (loop = 0; loop<str.Length; loop++)
            if ((*(ptr + loop) == 'a') || (*(ptr + loop) == 'e') || (*(ptr + loop) == 'i') || (*(ptr + loop) == 'o') || (*(ptr + loop) == 'u'))
        Console.WriteLine("Total Vowels are: "+countVowels);


Total Vowels are: 4
Press any key to continue . . .


In the above program, we created class UnsafeEx that contains the Main() method, here we used the unsafe keyword with the Main() method to define the unsafe method that can use pointers.

In the Main() method, we created an array of characters elements then we assign the address of the array to the pointer and then count the vowels from the character array using the pointer. After that count of vowels will be printed on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.