Introduction to C language

Introduction to C


     C is a general purpose programming language. Programming language is the means to communicate with the system to get our thing done.

Need for a programming language:

  We all of us know system can only understand binary representation i.e. in the form of 0's and 1's.

Suppose we have to program which adds two numbers and save the result.

Steps involved:
  • First we should write the values in the memory.
  • Move those values into the registers.(registers are also a kind of memory where the CPU can perform operation on the values stored in the registers.)
  • Add the values in the registers.
  • Save the result in the register to the memory.

Machine Language                                                                                                                                                                                                                                                                               At the beginning machine code is used to write the program. 

Machine level programming consists of binary or hexadecimal instructions on which an processor can respond directly.  

Structure of machine language instruction.
Opcode   Operand 

Opcode represents the operation to be performed by the system on the operands.

In machine code:
Memory     opcode     operand 
location                                                                     
0000:           55            e4     10   // 55 represent move instruction, move 10 to location e4          
0001:           89            e5     20
0003:           83            e4     e5
0006:           54            c4     e4    

Its difficult to read and write opcode for every instruction. So instead of numerical value for instruction there should be an alternative, Then comes the assembly code.

Assembly language:

 Mnemonics are used to represent the opcode.
An Assembly code:
MOV  A, $20           // move value 20 to register A (MOV is a mnemonics)
MOV  B, $10           // move value 10 to register B
ADD   A, B              // Add value in register in A and B
MOV  #30, A           // move value in register A to address 30

Assemblers converts the assembly language into binary instructions.
Assembly language is referred to as low level language,
Assembler languages are simpler than opcodes. Their syntax is easier to read than machine language but as the harder to remember. So, their is a need for other language which is much more easy to read and write the code.
Then comes the C programming language.

C language

In C language:
 int main()
{
     int a,b,c;
     a=10;
     b=20;
     c=a+b;
}

Compiler converts the C language code into assembly language code.

C language is easier to write and read. 

Factorial program in python

#write a python program for factorial of a given number.

num = int(input("Enter a number: "))
factorial = 1
if num < 0:
   print("factorial not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)

  • We store the number we give in the num variable and by using the if, elif, and else loop we are executing the program. if statement executes when the given condition is true and same for elif also. After the iteration, it finally returns the factorial of the number we are given.
  • Normally we write as 12!=12*11*10*9*8*7*6*5*4*3*2*1=479001600




find substring python

 find substring():

  • The find substring is used to find the substring from the string.
  • Substring is the piece of characters from the string.
  • If the string consists of the given string then it returns the index number of the substring. 
  • The string must be enclosed with single or double-quotes.
  • It returns -1 if the substring does not found instead of an error.
  • find() has 3 parameters,they are:
  1. value: The value to be search
  2. start:  from where to search
  3. end:  from where to stop searching.
Syntax: str.find(value,start,end)

#write a python code to demonstrate the find substring function.

  1. txt="learning is a life time process"
  2. txt=txt.find("i")
  3. print(txt)
  4. s="apple"
  5. s=s.find("b")
  6. print(s)

Output: 5
              -1







python replaceall

  • In python, replace all is similar to replace() function. 
  • Here we are going to replace all the characters with new characters.
  • It also consists of 3 parameters like new value, old value, count.
  • The old value is the string that we have already given in string.
  • The new value is the that is to be replaced with.
  • The count is the number of times that string to be replaced in the string.
Syntax:  str.replace(old value,new value,count)

#write a python code to demonstrate the replace function.

  1. s="hello world"
  2. s=s.replace("hello world","my name is hello")
  3. print(s)
Output:    my name is hello


format function in python

  •  The format() function is used to format a specific value and insert that value in string placeholders.
  •  The placeholders are cost{20}, number index{1},empty{}
  • The place holder is defined by" curly braces"{}.
  • The format function consists of parameters called value.
  • It returns the formatted string.
Syntax:  str.format(values)

  • Inside the placeholders, we can add different formatting types
  • :+    indicates positive values.
  • : -    indicates negative values.
  • :      indicates the space before positive and also negative numbers.
  • :_    indicates as a thousand separator.
  • :,     uses as comma thousand separator.
  • :=    left most position.
  • :<    result in left alignment.
  • :>    result in right alignment.
  • :^     result in the center.
  • :%    percentage format.
  • :b     Binary format.
  • :c     Unicode format.
  • :d     Decimal format.
  • :e      format with lower case.
  • :E     format with upper case.
  • :f      format with fixpoint number.
  • :o    format is octal.
  • :x      format is Hexa.
  • :X     format is Hexa in uppercase.
  • :n      number format.

#write a python code to demonstrate format function.

  1. s0="my name is {fname},I m {age}".format("fname=abc",age=19)
  2. s1="my name is{0},I m {1}".format("abc",19)
  3. s2="my name is {},I m {}".format("abc",19)
  4. print(s0)
  5. print(s1)
  6. print(s2)

Output:    my name is abc, I m 19.
                 my name is abc, I m 19.
                 my name is abc, I m 19.


string reverse in python

  • The reverse string in python is not an in-built function.
  • By creating the slice operation we can perform the reverse function.
  • In this slice operation, we create the slice that starts with the end of the string and moves backward.
  • String reverse in python example program
Example: " abcdefg"[::-1]

                     gfedcba

 right to left indexing:              [-7]    [-6]    [-5]    [-4]      [-3]     [-2]      [-1]

                                                    a          b      c        d          e          f         g 

left to right indexing:             [0]         [1]     [2]     [3]     [4]       [5]        [6]

  • In the above example, we are having the string  "abcdefg " which we want to reverse. so create a slice that starts with the end of the string and moves backward.
  • here it starts with the end index that is indicated with -1 and moves backward as 5,4,3,2,1,0.
  • -1 index  is g
  • 5 index is f
  • 4 index is e
  • 3 index is d
  • 2 index is c
  • 1 index is b
  • 0 index is a
  • so the final output is gfedcba.

#write a python code to demonstrate string reverse.

  1. txt="today climate is very cool"[::-1]
  2. txt1="hello world"[::-1]
  3. print(txt)
  4. print(txt1)
Output:    looc yrev si etamilc yadot
                  dlrow olleh


python tolower

  •  In python, to lower is used to convert the uppercase letters to lower case.
  • It uses the function called lower().
  • It doesn't have any parameters.
  • The string must be enclosed with single or double-quotes.
  • If the string does not contain any upper case letters then it returns the same string.
Syntax: str.lower()

Example: s="HELLO"

             str.lower(s)=hello

#write a python code to demonstrate the lower() function.

  1. s="APPLE IS A FRUIT"
  2. print(str.lower(s))
  3. x="My NAme IS  aBCba"
  4. print(str.lower(x))
output: apple is a fruit
              my name is abcba


remove spaces from string python

  •  In python, we have different functions which remove the spaces between the strings.
  • There are three functions that remove the whitespace between the strings, they are:
  • strip(), rstrip(), lstrip()  are the three functions having the same meaning but some differences.
strip(): It removes the whitespace at the beginning and end.

syntax: str.strip()

lstrip(): It removes the whitespace at beginning of the string.

syntax: str.rstrip()

rstrip(): It removes the whitespace at end of the string.

syntax: str.rstrip()

Example: write a python to demonstrate the remove space function.

  1. txt="    hello"
  2. print(txt)
  3. print(txt.strip())
  4. print(txt.rstrip())
  5. print(txt.lstrip())
Output:         hello    //this is the original output
                  hello         //after removing both side space
                     hello      //no space at  end returns same 
                hello          //remove space at the beginning.


replace function in python

 replace function:

python having different types of in-built functions from them replace() is one of the function.
  • The replace() function name itself saying that "one string is replaced with the other string".
  • It consists of three parameters old value, new value, and count.
old value:  The value that we want to replace.

new value: The value we want to replace with is the new value.

count: The number of times of the value we want to replace old with the new value.

Syntax: str.replace(old value,new value,count)

#write a python code to demonstrate replace function.

  1. a="my name is java"
  2. b=" she is a very talented person"
  3. c="They have no knowledge in python"
  4. a=a.replace("java","python")
  5. b=b.replace("talented person","brave girl")
  6. c=c.replace("no","more",3)
  7. print(a)
  8. print(b)
  9. print(c)
  • In the above program in line 5, we want to replace no with more and we gave the count as 3 so in the string where we have no that will be replaced with more up to 3 times only.
  • so the output will be as shown in below.
Output:  my name is python
               she is a very brave girl
              They have more kmorewledge in python 



strip function in python


In Python, the str.strip() method is used to remove leading and trailing whitespaces from a string. By default, the strip() method removes any whitespace characters from the beginning and end of the string, such as spaces, tabs, and newlines. 
The strip() function is a string method that removes leading and trailing whitespace characters from a string. By default, it removes spaces, tabs, and newline characters from the beginning and end of a string. 
However, it can also be used to remove any specified characters from the beginning and end of a string.
Here's an example of strip() method:

It's important to note that the strip() function returns a new string and does not modify the original string.
We can also use lstrip() and rstrip() to remove leading and trailing whitespaces respectively.
strip() function in Python is a useful method for removing unwanted characters from the beginning and end of a string, which helps in cleaning up the data and making it ready for further processing or analysis.

original_string = "   Hello World   "
stripped_string = original_string.strip()
print(stripped_string)

This will print "Hello World" with leading and trailing whitespaces removed.

In addition to removing whitespaces, the strip() method can also remove specific characters from the beginning and end of the string. You can pass one or more characters as arguments to the strip() method, and it will remove those characters from the beginning and end of the string. Here's an example:


original_string = "!!Hello World!!"
stripped_string = original_string.strip('!')
print(stripped_string)

This will print "Hello World" with the leading and trailing '!' characters removed.

Alternatively, you can use lstrip() and rstrip() method to remove leading and trailing whitespaces respectively.


original_string = "   Hello World   "
stripped_string = original_string.lstrip()
print(stripped_string)

This will print "Hello World " with leading whitespaces removed.


original_string = "   Hello World   "
stripped_string = original_string.rstrip()
print(stripped_string)

This will print " Hello World" with trailing whitespaces removed.

It's worth noting that, the strip() method returns a new string with the leading and trailing whitespaces removed, it does not modify the original string.
  • In python, we are having another in-built function called "strip()".
  • The strip() function is used to remove the spaces of the starting and end of the string.
  • It is having one parameter character used to remove the begging or end character.
  • By default, it removes the white spaces at the beginning or end.
  • If there is no white space between the beginning or end, the string remains the same and returns the same string.
  • When the character we give does not match the start or end, it returns the same string.
  • If the character is given at start to remove then the space will be removed and the remaining will remain the same.
syntax: str. strip(char)

#write a python program to demonstrate the strip function()

  1. txt1="   my name is python"
  2. txt2="***my name is python***"
  3. txt3=",,,my name is python"
  4. txt1=txt1.strip()
  5. txt2=txt2.strip("*")
  6. txt3=txt3.strip(".")
  7. print(txt1)
  8. print(txt2)
  9. print(txt3)
Output: my name is python
               my name is python
               my name is python

length of string python

 length of the string:

  • The len() function gives the length of the string.
  • As it returns the result in integer type.
  • It takes the string as the parameter.
  • We can use len() for list,tuple,set,dictionry.
  • The len() is the built-in function in python programming.
  • Example:  "string"  its length is  6.
Syntax: str(length)

#write a python program to demonstrate the length of the string.

  1. string="america"
  2. print(len(string))
Output: 7


concat python

 concatenation:

  • In python, concatenation is defined as "the process of combining or joining or merging one string with the other string".
  •  It uses the plus operator for combining the strings.
  • The string must be enclosed with single quotations or double.
  • Type conversion is needed.
  • We can combine an integer value with a string by using the str(int) function.
  • The plus(+) operator is used to combine the string at the end of the string.
  • The % string format operator is used to combine the string anywhere we want.
Syntax: str1+str2

#write a python program to demonstrate concatenation function.

  1. a="python"
  2. b="programming"
  3. x=a+b
  4. print(x)
  5. str1="python"
  6. str2=str(3.0)
  7. str=str1+str2
  8. print(str)
Output: pythonprogramming
              python3.0



startswith python

  •  In python, we have another built-in method called startswith.
  • startswith is used to check whether the string startswith this specified string.
  • It returns the boolean type.
  • If the string startswith gave specified string then it returns true else false.
Syntax: str.startswith(value,start,end)

  • It consists of the 3 parameters.
  1. value:  The value that the string starts with.
  2. start:    The position to start the search of string.
  3. end:  The position to end the search.

#write a python program to demonstrate the startswith method.

  1. str="welcome to python"
  2. str=str.startswith("w",0,14)
  3. print(str)
Output:true

strftime python

 strftime :

  •  The method represents the string consists of data and time with objects as time and date or date time.
  • The datetime class is imported from the date time module.
  • It takes one or more input format codes and returns string representation.
Syntax: strftime(format)

  • The list of format codes are:
  1. %a:  It is used for weekdays representation in short forms as wed, thr, etc...
  2. %A: It is used for weekdays representation in the full name as of Sunday, Monday.
  3. %b: It is used for month name representation in short form as of Jan, Feb, etc
  4. %B: It is used for month name representation in the full name as of April, May, etc.
  5. %d: It is used as a representation of the day of the month as zero added.
  6.  %-d: day of the month as a decimal number.
  7. %m: Month as zero added decimal number. 
  8. %-m: Month as a decimal number.
  9. %H:  hours as zero added decimal number.
  10. %-H: hours as a decimal number.
  11. %M: minutes as zero added decimal number.
  12. %-M: minutes as a decimal number.
  13. %S: seconds as a zero added decimal number
  14. %-S: seconds as a decimal number.
  15. %J: day of the year as zero added decimal number.
  16. %-J: day of the year as a decimal number.

#write a python program to demonstrate strftime function.

  1. from datetime import datetime
  2. now=datetime.now()
  3. year=now.strftime("%Y")
  4. print("year:",year)
  5. month=now.strftime("%m")
  6. print("month:",month)
  7. day=now.strftime("%d")
  8. print("day:",day)
  9. time=now.strftime("%H:%M:%S")
  10. print("time:",time)
  11. date_time=now.strftime("%m%d%Y, %H%M%S")
  12. print("date and time:",date_time)
output:
year:2021
month:07
day:05
time:10:50:36
date and time:07052021,105036



is numeric python

is numeric:

  •  Is numeric is the built-in method that is used to check whether the string contains numbers or not.
  • It returns the true when the string contains numbers, if the string does not contain numbers then it returns false.
  • It is applicable for integers, Unicode values. and takes the exponents like 1/2.
  • It is not applicable for float and negative values.
  •  isnumeric does not have any parameters.
  • For negative values to check whether they are numeric or not we have to remove the negative sign.
syntax:  str.isnumeric()

Example: a="12345"

                 a=str.isnumeric(a)

                 true

#write a python program to demonstrate the isnumeric function.

  1. x="34567"
  2. x=str.isnumeric(x)
  3. print(x)
  4. y="123abc"
  5. y=str.isnumeric(y)
  6. priny(y)
  7. z="asd13434656"
  8. z=str.isnumeric(z)
  9. print(z)
output: true
             false
             false




 

is alpha python

 is alpha:

  • In python "is alpha" is the method used to check the alphabets whether they are present in the given string or substring.
  • In isalpha, it must carry only alphabets.
  • It carries the result in the boolean type
  • If the string contains all alphabets then it returns true, else false.
  • The isalpha is not applicable for the alphanumeric.
  • It is the built-in function of python.
syntax: str.isalpha()

Example:  s="abcdefg"
                   str.isalpha(s)
                    true

#write a python program to demonstrate is alpha function.

  1. a="india"
  2. b="india123"
  3. a=str.isalpha(a)
  4. b=str.isalpha(b)
  5. print(a)
  6. print(b)
output: true
             false


is digit python

is digit() python:  

  • The isdigit()  in python is defined as the string that consists of only digit values. 
  • It returns the result in boolean type if the string has only digits it returns true else false.
  • It accepts the Unicode of that characters also. and also the exponents like ^2.
  • It is not applicable to whitespace, special symbols, alphabets.
Syntax: str.isdigit().

Example:  str="123456"
                 str.isdigit(str) retrns true
Beacuse "123456" is perfectly a digit.
               str=\u00B0
               str.isdigit(str)returns true
Because it takes the Unicode as digit characters.

#write a python code  to demonstrate isdigit() function.

  1. a="7656734"
  2. a=str.isdigit(a)
  3. print(a)
  4. b="2344.60 
  5. b=str.isdigit(b)
  6. print(b)
  7. x="\u00B2"
  8. x=str.isdiigt(x)
  9. print(x)
output: true
            false
            true

2

python substring

  • In python, we have the string concept from that we have a small topic called substring.
  • "substring " is the string that is a part of the main string.
  • In other words, we can say that extraction of the characters from the string.
  • We can access the string by using the index and substring by using the concept of slicing.
  • For the creation of the list of substrings, we use the split().
  • It follows string[start:end: step] in slicing concept by this the substring is formed.
  • startIt is the starting index of the substring. By default, it is 0.
  • end: It is the ending index of the substring. By default, it is the length of the string.
  • step: It is used to increment the index by the given numbers.
  • We use some of the functions in the substrings.
  • In operator: It is used to find the substring that is present in the string.
  • Count(): It is used to count the number of times the substring occurred in the string.It is denoted by the "*" symbol.

#Write a python program to find the substring from a string.

  1. s="hello every one"
  2. print(s[:])
  3. print(s[:5])
  4. print("h" in s)
  5. s=s*3
  6. print(s)

output: hello every one
             hello
              true
              hello every one hello every one hello every one.


python string operations

  • In python, we have some operations that perform the specified operations on strings.
  • In this, the string must enclose with the codes that might be single or double.
  • Here are some python string operations.

1.  String assignment operator:

  • In this operator, the string is assigned to any of the variables.
  • The string may be in single or double codes.
  • It is represented by " =" equal to symbol.
Syntax: string ="any variable."

Example:  string1="python"
                  string2="java"

In the above example, we assign a "python" to string 1 and "java" to string 2 by using the" =" symbol.

# write a python program for the string assignment operator.

  1. str1="welcome to python"
  2. str2="Today topic is string operator"
  3. str3="python is easy  language"
  4. print(str1)
  5. print(str2)
  6. print(str3)
output:  welcome to python
             Today topic is string operator
             Python is easy to language



2. Cancatenate operator:

  • This operator has used to cancate the strings.
  • Concatenation means joining or combing the strings by using the plus symbol between the strings.
  • It is represented by the symbol " +".
       Syntax:  (str1+str2)

       Example:   "Hello"  +"world"
  •  Result is : "Helloworld"

#Write a python program using string cancatenate operator.

  1. str1="a"
  2. str2="is"
  3. str3="alphabet"
  4. print(str1+str2+str3)
output: aisaphabet


3. String repetition operator: 

  • In this operator, the string is repeated the number of times that we declare in the code.
  • It is represented by the symbol "*".
Syntax:  str*n    Here n is the number of times that the string can be repeated.

Example: str="apple"
                 str*2
The result is: apple apple
  • here we declare the string as apple it should be repeated for 2 times.

#Write a python code using the string repetition operator.

  1. str="welcome"
  2. print(str*5)
output: welcome welcome welcome


       

       4.Slicing operator:  

  • In this slicing operator, the strig is divided according to the given index values.
  • The string can y accessed by using the index.
  •  It is having positive index and negative index values.
  • Positive values start from  0 from left to right.
  • The negative index starts from -1 from right to left.
  • [:] this gives all values in the index 0 to end. 
  • The slicing never shows the error, if the index is out of range, it shows an empty list[].  

Syntax: str[]

Example:   str="string"
                   str[0]=s
                   str[1]=t
                   str[-1]=g
  • In the above example, the s index is 0 so it returns s when we write str[0].

#write a python code for slicing operator.

  1. str="coding"
  2. print(str[0])
  3. print(str[-1])
  4. print(str[1:6])
  5. print(str[1:])
  6. print(str[:3])
  7. print(str[1:-4])
  8. print(str[-3])
output:  c
             g
             oding
             oding
             cod
              o
              i                                                                                 


                                       

5. String comparison operator:

  • In the string comparison operator, we compare the strings.
  • In this, we have 2 operator
     1.Equal to(==): If both the strings are the same then it returns true else false.
  • It is represented by the symbol "==".
     Syntax:str1==str2.

       2.not equal(!=): If both strings are not the same then it true else false.
  • It is represented by the symbol "!=".
Syntax:  str1!=str2

#write a python coding using the python string comparison operator.

  1. str1="my name is A"
  2. str2="my name is B"
  3. str3="my name is A"
  4. str4="apple"
  5. str5="apple"
  6. print(str1==str2)
  7. print(str1==str1)
  8. print(str4==str5)
  9. print(str4!=str1)
  10. print(str3!=str2)
output: false
            true
            true
            true
            true



6. Membership operator:

  • In the membership operator, we check the string that is declared in the code is present in the given list or not.
  • There are 2 operators in membership.
  1. In:  It tells that the string is present in the given list.If it is present returns true else false.
  2. Not in: It tells that the string is not present in the given list returns true else false.
Example: str="string"
                r in the str
       The result is: true

#write python code using membership operator.

  1. str="Hello world"
  2. print("H" in str)
  3. print('s' in str)
  4. print("a" not in str)
output:  true
             false
             true



7. Escape sequence operator:

  • This operator is used when an unallowed character is present in the given string.
  • It is represented by the "\" symbol called backslash. 

Write a python program for escape sequence operator.

  1. str="welcome to \"python\" classes"
  2. print(string)
output: welcome to "python" classes





8.String formatting operator:

  • It is used to format the string as per our requirement.
  • There are different types of formats.
  • It is denoted by that "%" symbol.
  • Each format has its own meaning.
%d:  used for sign decimal integer.
%s: used for string.
%f: used for floating.
%u: used for unsigned decimal integer.
%c: used for the character.

#write a python code using the string formatting operator.

  1. name="abc"
  2. marks=78
  3. str1='hi % s'%(name)
  4. print(str1)
  5. str2='hi% s,my marks is %f'%(name,marks)
  6. print(str2)
output: hiabc,my marks is 78.000000


python string methods

 Python string methods:

  • Before going to string methods first of all we have to know what is meant by string.
  • A "String is a set of or group of characters."
  • The string always must be closed with single, double, or triple codes.
  • Triple codes (''' ''') are used for multi-line purposes.
  • In python, we are having some string functions, that are used to operate on strings.
  • As the string is immutable it always returns the new values only. The old values cannot be replaced.
  • The string function is defined as str().

Example:

#1.write python code using the str() methods.

  1. s'"Hello"
  2. print(s[0])
  3. print(s[1])
  4. print(s[2])
  5. print(s[3])
  6. print(s[4])
output:  H
              e
              l 
              l
             o


#2. write a python code using str() functions.

  1. str="Hello"
  2. print(str.lower())
  3. print(str.upper())
  4. print(str.count(str))
output: hello
             HELLO
              1



  • In the following table, we will find more functions and their respective actions in the string.

MethodDescription
len()used to determine the length of the string.
isalnum()used to define the string is alphanumeric.
islower()To define a string is in small letters.
isupper()To define a string is in capital letters.
isnumeric()The string consists of only numbers.
istitle()The string is in the title case.
isspace()The string has only white space.
find()Searches the string value and returns the position.
format()Formats specified values in a string
format_map()Formats specified values in a string
index() returns the position of string where it was found
count()Returns the number of times string occurs.
stratswith() the string starts with the given prefix.
isdecimal() all characters in the string are decimals
isdigit() all characters in the string are digits
isidentifier()Returns True if the string is an identifier
endswith() all characters in the string end with the given suffix. 
encode()it encodes the string.
isprintable()all characters in the string are printable.
capitalize()it returns all the capital strings.
center()Returns the center string. 
_contain_() the string we check is contained in another string or not.
join()Joins the elements of the string.
ljust()Returns a left-justified version of the string
hash()Returns the hash value of the given object.
lstrip()Returns a left trim version of the string
maketrans()Returns a translation table to be used in translations
partition()Returns a tuple where the string is parted into three parts
replace() string where a value is replaced with another value.
rfind()Search the string and returns the last position.
rindex()Search the string and returns the last position.
rjust()Returns a right-justified version of the string
rpartition()Returns a tuple where the string is parted into three parts
rsplit()Splits the string at the specified separator, and returns a list
rstrip()Returns a right trim  of the string
split()Splits the string at the specified separator, and returns a list
splitlines()Splits the string at line breaks and returns a list
id()Returns the identity of the string.
strip() It trims the space between the strings.
swap case()In this, the lower case becomes the upper case and vice versa
title()Converts the first character of each word to upper case
translate()Returns a translated string
upper()Converts a string into the upper case.
zfill()Fills string with a specified number of 0's at the beginning.

C initialize an array

  • Array is collection of similar data items.
  • An array can hold multiple values of same type of data
  • In c programming language an array can be declared as datatype arrayName [ arraySize ]; 
  • In c , while declaring an array we need to specify type of array , name of array and size of the array.
  • One can directly initialize an array while declaring itself with some values
  • int arrayVariable[2]=[10,20];
  • int count[]=[1,2,3,4,5]
  • directly initialize an array of particular : count[3]=10
  • Let us discuss about how to initialize an array with some default values.
  • Using for loop or while loop we can iterate an array and by accessing each index we can assign values 
  • If we are not initializing an array and try to print all the values then it will print some garbage values.
  • c initialize array of ints

#1Write a C program to declare an array and print default values
  1. #include <stdio.h>
  2. // write a c program to explain how to initialize an array
  3. int main () {

  4.    int number[ 15 ]; 
  5.    int i,k;
  6.    
  7.    
  8.    for (k = 0; k < 15; k++ ) {
  9.       printf("Array[%d] = %d\n", k, number[k] );
  10.    }
  11.  
  12.   getch();
  13. }


Output:
  1. Array[0] = -1551778920
  2. Array[1] = -2
  3. Array[2] = 1971427546
  4. Array[3] = 1971495162
  5. Array[4] = 5189464
  6. Array[5] = 5181048
  7. Array[6] = 2686776
  8. Array[7] = 1971494685
  9. Array[8] = 0
  10. Array[9] = 0
  11. Array[10] = 2686832
  12. Array[11] = 200
  13. Array[12] = 192
  14. Array[13] = 7161720
  15. Array[14] = 48


#2 write a C Program to initialize an array values to 0 (zeros).

initialize an array in c


Output:
  1. Array[0] = 0
  2. Array[1] = 0
  3. Array[2] = 0
  4. Array[3] = 0
  5. Array[4] = 0
  6. Array[5] = 0
  7. Array[6] = 0
  8. Array[7] = 0
  9. Array[8] = 0
  10. Array[9] = 0
  11. Array[10] = 0
  12. Array[11] = 0
  13. Array[12] = 0
  14. Array[13] = 0
  15. Array[14] = 0

spilt function in python

 Split function: 

  • The split() function is used to split the string by separating them with the split().
  • The split()  method contains the different separators  like comma(,) colon(:) semicolon(;)  and space also.
  • By default when we write split() function it will separate the values by "space ".
  • After splitting the string it returns a list of strings.
Syntax: str.split(separator,max split)
  • Example:
  • y=[int(x) for x in input("enter the 2 numbers:").slipt(",")]
  • Here, the 2 numbers are 10 2 by using split(",") these numbers are separated by"," as 10,5.
  • There are  3 parameters in the split() method
  1. separator: It separates the string by using separators if we do not use then by default it takes space.
  2. max split:  It is used to split the string by the max number of times. By default, it takes 1 i.e no limit for splitting. 
  3. Returns: After splitting the string it returns the list of string values.

# write a python code using the split().

  1. a="apple is a fruit"
  2. b=" dog is a animal"
  3. c="python is easy to learn"
  4. print(a.split())
  5. print(b.split())
  6. print(c.split())
output: ['apple' , 'is' , 'a' , 'fruit' ]
            ['dog'  ,'is'  ,'a', 'animal']
            ['pthon'  , 'is'   , 'easy'  ,'to' , 'learn']



python Ternary operator

Ternary operator: 

  • The ternary operator is defined as the operator that evaluates the conditions to find the final result.
  • It evaluates more than one expression.
  • A  single line code is written according to the condition.
syntax:  x= first value if condition else second value.
In this syntax, if the first value satisfies the condition then it returns the x value, if the first value doesn't satisfy the condition then it goes to the else part and checks the second condition.

Example: x=20 if 5<10 else 30 we get the result as 20.
Because here condition 5<10 is grue so it returns the x value as 10.

  • There is another syntax for the ternary operator when there are more than 2 conditions i.e;
  • syntax: x= first value if condition 1 else second value if condition 2 else third value.
Example: x=1 if 20>30 else 2 if 50>60 else  10. 
                The result is  10.
  • In the ternary operator, we can perform a nested loop also.
  • We can reduce the length of the code by using this ternary operator, in this operator we write a code in a single line.
  • So time is saved and less complexity in the code.

#write a python program for integers using the ternary operator.

  1. a=8
  2. b=9
  3. max= b if b>a else a.
  4. print(max)
output: 9



python not operator

 Python not operator:

  • python not operator is the complement of the given value i.e; if the value is true then it returns false and if the value is false then it returns true.
  • When we  apply the not operator we get result  in  boolean type .
  • example:
                 x=10 
                 not x, then the result is false because x=10 is true so not x is false.
  • syntax:(not x).

 # write a python program using not operator.

  1. x="python"
  2. y="java''
  3. print(not x==y)
output: true

 

Select Menu